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
304.1 KiB6023 linesraw
1#include "b60_mtp_q8_cache.hpp"
2#include "b60_weight_cache.hpp"
3#include "b60_layout_state.hpp"
4// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
5// ggml/src/ggml-cuda/{quantize.cu,vecdotq.cuh,mmvq.cu,common.cuh}
6// and ggml/src/ggml-common.h. See docs/native-mmvq.md for exact scope.
7//
8// MIT License
9// Copyright (c) 2023-2026 The ggml authors
10//
11// Permission is hereby granted, free of charge, to any person obtaining a copy
12// of this software and associated documentation files (the "Software"), to deal
13// in the Software without restriction, including without limitation the rights
14// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
15// copies of the Software, and to permit persons to whom the Software is
16// furnished to do so, subject to the following conditions:
17//
18// The above copyright notice and this permission notice shall be included in all
19// copies or substantial portions of the Software.
20//
21// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
22// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
23// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
24// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
25// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
26// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27// SOFTWARE.
28
29#define DPCT_PROFILING_ENABLED
30#include <sycl/sycl.hpp>
31#include "strata/kprof.hpp"
32#include <sycl/ext/intel/esimd.hpp>
33#include <sycl/ext/intel/esimd/xmx/dpas.hpp>
34#include <sycl/ext/intel/experimental/grf_size_properties.hpp>
35#include <sycl/ext/oneapi/matrix/matrix-intel.hpp>
36#include <dpct/dpct.hpp>
37#include "strata/sycl_math.hpp"
38#include "strata/sycl_queue.hpp"
39#include "strata/workload_trace.hpp"
40#include "strata/kernels/native_mmvq.hpp"
41#include "strata/kernels/iq4_lut.hpp"
42#include "strata/kernels/dp4a.hpp"
43#include "strata/kernels/q8_1_finite.hpp"
44#include "strata/kernels/iq4_lut.hpp"
45#include "strata/kernels/iq_kernels.hpp"
46#include "s26_tsum.dp.hpp"
47
48#include <algorithm>
49#include <cstdint>
50#include <cstdlib>
51#include <cstring>
52#include <limits>
53#include <stdexcept>
54#include <type_traits>
55#include <string>
56#include <unordered_map>
57#include <cstdio>
58#include <vector>
59#include <cmath>
60
61namespace strata::kernels {
62namespace {
63
64#ifndef STRATA_MMVQ_UNROLL
65#define STRATA_MMVQ_UNROLL 2
66#endif
67constexpr int QK = 256;
68constexpr int Q8K = 32;
69constexpr int QI = 32;
70constexpr int VDR = 2;
71constexpr int WARPS = 4;
72constexpr int WARP = 32;
73constexpr int QUANT_THREADS = 256;
74
75struct Q5KBlock {
76    sycl::half2 dm;
77    uint8_t scales[12];
78    uint8_t qh[32];
79    uint8_t qs[128];
80};
81struct Q81Block {
82    sycl::half2 ds;
83    int8_t qs[32];
84};
85struct Q20Block {
86    sycl::half d;
87    uint8_t qs[16];
88};
89struct Q3KBlock {
90    uint8_t hmask[32];
91    uint8_t qs[64];
92    uint8_t scales[12];
93    sycl::half d;
94};
95struct IQ4XSBlock {
96    sycl::half d;
97    uint16_t scales_h;
98    uint8_t scales_l[4];
99    uint8_t qs[128];
100};
101struct Q4KBlock {
102    sycl::half2 dm;
103    uint8_t scales[12];
104    uint8_t qs[128];
105};
106struct Q6KBlock {
107    uint8_t ql[128];
108    uint8_t qh[64];
109    int8_t scales[16];
110    sycl::half d;
111};
112struct Q40Block {
113    sycl::half d;
114    uint8_t qs[16];
115};
116struct Q50Block {
117    sycl::half d;
118    uint8_t qh[4];
119    uint8_t qs[16];
120};
121struct Q80Block {
122    sycl::half d;
123    int8_t qs[32];
124};
125struct IQ4NLBlock {
126    sycl::half d;
127    uint8_t qs[16];
128};
129static_assert(sizeof(Q5KBlock) == 176 && alignof(Q5KBlock) == 4);
130static_assert(sizeof(Q81Block) == 36 && alignof(Q81Block) == 4);
131static_assert(sizeof(Q20Block) == 18 && alignof(Q20Block) == 2 && offsetof(Q20Block, qs) == 2);
132static_assert(sizeof(Q3KBlock) == 110 && alignof(Q3KBlock) == 2 && offsetof(Q3KBlock, qs) == 32 &&
133              offsetof(Q3KBlock, scales) == 96 && offsetof(Q3KBlock, d) == 108);
134static_assert(sizeof(IQ4XSBlock) == 136 && alignof(IQ4XSBlock) == 2 &&
135              offsetof(IQ4XSBlock, scales_h) == 2 && offsetof(IQ4XSBlock, scales_l) == 4 &&
136              offsetof(IQ4XSBlock, qs) == 8);
137static_assert(offsetof(Q5KBlock, scales) == 4 && offsetof(Q5KBlock, qh) == 16 &&
138              offsetof(Q5KBlock, qs) == 48 && offsetof(Q81Block, qs) == 4);
139static_assert(sizeof(Q4KBlock) == 144 && alignof(Q4KBlock) == 4 &&
140              offsetof(Q4KBlock, scales) == 4 && offsetof(Q4KBlock, qs) == 16);
141static_assert(sizeof(Q6KBlock) == 210 && alignof(Q6KBlock) == 2 &&
142              offsetof(Q6KBlock, qh) == 128 && offsetof(Q6KBlock, scales) == 192 &&
143              offsetof(Q6KBlock, d) == 208);
144static_assert(sizeof(Q40Block) == 18 && alignof(Q40Block) == 2 && offsetof(Q40Block, qs) == 2);
145static_assert(sizeof(Q50Block) == 22 && alignof(Q50Block) == 2 &&
146              offsetof(Q50Block, qh) == 2 && offsetof(Q50Block, qs) == 6);
147static_assert(sizeof(Q80Block) == 34 && alignof(Q80Block) == 2 && offsetof(Q80Block, qs) == 2);
148static_assert(sizeof(IQ4NLBlock) == 18 && alignof(IQ4NLBlock) == 2 && offsetof(IQ4NLBlock, qs) == 2);
149
150__dpct_inline__ float warp_sum(float x) {
151#pragma unroll
152    for (int offset = WARP / 2; offset > 0; offset >>= 1) {
153        /*
154        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
155        feature masked sub_group function which may not be supported by all
156        compilers or runtimes. You may need to adjust the code.
157        */
158        x += dpct::experimental::permute_sub_group_by_xor(
159            0xffffffff, sycl::ext::oneapi::this_work_item::get_sub_group(), x,
160            offset);
161    }
162    return x;
163}
164
165template <int SG> __dpct_inline__ float sg_sum(float x) {   // SYCL port: warp_sum for a SG-wide sub-group
166#pragma unroll
167    for (int offset = SG / 2; offset > 0; offset >>= 1)
168        x += sycl::permute_group_by_xor(sycl::ext::oneapi::this_work_item::get_sub_group(), x, offset);
169    return x;
170}
171__dpct_inline__ float warp_max(float x) {
172#pragma unroll
173    for (int offset = WARP / 2; offset > 0; offset >>= 1) {
174        /*
175        DPCT1108: '__shfl_xor_sync' was migrated with the experimental
176        feature masked sub_group function which may not be supported by all
177        compilers or runtimes. You may need to adjust the code.
178        */
179        x = sycl::fmax(x,
180                       dpct::experimental::permute_sub_group_by_xor(
181                           0xffffffff,
182                           sycl::ext::oneapi::this_work_item::get_sub_group(),
183                           x, offset));
184    }
185    return x;
186}
187
188__dpct_inline__ void native_quantize_q8_1_kernel(const float *__restrict__ x,
189                                                 Q81Block *__restrict__ y,
190                                                 int n_in) {
191    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
192    const int i = int(item_ct1.get_group(2)) * QUANT_THREADS +
193                  int(item_ct1.get_local_id(2));
194    if (i >= n_in) return; // n_in is a multiple of 32: only whole warps return.
195    const float xi = x[i];
196    const float amax = warp_max(sycl::fabs(xi));
197    const float sum = warp_sum(xi);
198    const float d = q8_1_finite(amax / 127.0f);   // #606: q8_1_finite.hpp - the same bits for every finite block
199    const int8_t q = q8_1_quant(xi, d, amax);
200    y[i / Q8K].qs[i % Q8K] = q;
201    if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum);
202}
203
204__dpct_inline__ void
205native_swiglu_quantize_q8_1_kernel(const float *__restrict__ gate,
206                                   const float *__restrict__ up,
207                                   Q81Block *__restrict__ y, int n_in) {
208    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
209    const int i = int(item_ct1.get_group(2)) * QUANT_THREADS +
210                  int(item_ct1.get_local_id(2));
211    if (i >= n_in) return; // n_in is a multiple of 32: only whole warps return.
212    const float gi = gate[i];
213    /*
214    DPCT1013: The rounding mode could not be specified and the generated
215    code may have different accuracy than the original code. Verify the
216    correctness. SYCL math built-in function rounding mode is aligned with
217    OpenCL C 1.2 standard.
218    */
219    const float xi = gi / (1.0f + sycl::native::exp(-gi)) * up[i];
220    const float amax = warp_max(sycl::fabs(xi));
221    const float sum = warp_sum(xi);
222    const float d = q8_1_finite(amax / 127.0f);   // #606, as native_quantize_q8_1_kernel: finite blocks bit for bit
223    const int8_t q = q8_1_quant(xi, d, amax);
224    y[i / Q8K].qs[i % Q8K] = q;
225    if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum);
226}
227
228// Exact pinned vec_dot_q5_K_q8_1_impl_vmmq expression and integer dot order.
229__dpct_inline__ float
230q5_q8_dot_impl(const int *__restrict__ vl, const int *__restrict__ vh,
231               const int *__restrict__ u, const uint8_t *__restrict__ sc,
232               const uint8_t *__restrict__ m, const sycl::half2 &dm5,
233               const float *__restrict__ d8) {
234    float sumf_d = 0.0f;
235    float sumf_m = 0.0f;
236#pragma unroll
237    for (int i = 0; i < 2; ++i) {
238        const int vl0i = (vl[0] >> (4 * i)) & 0x0f0f0f0f;
239        const int vl1i = (vl[1] >> (4 * i)) & 0x0f0f0f0f;
240        const int vh0i = ((vh[0] >> i) << 4) & 0x10101010;
241        const int vh1i = ((vh[1] >> i) << 4) & 0x10101010;
242        const int v0i = vl0i | vh0i;
243        const int v1i = vl1i | vh1i;
244        const int dot1 = STRATA_DP4A(v0i, u[2 * i], STRATA_DP4A(v1i, u[2 * i + 1], 0));
245        const int dot2 = STRATA_DP4A(0x01010101, u[2 * i], STRATA_DP4A(0x01010101, u[2 * i + 1], 0));
246        sumf_d += d8[i] * (dot1 * sc[i]);
247        sumf_m += d8[i] * (dot2 * m[i]);
248    }
249    const sycl::float2 dm5f =
250        dm5.template convert<float, sycl::rounding_mode::automatic>();
251    return dm5f.x() * sumf_d - dm5f.y() * sumf_m;
252}
253
254/*
255DPCT1110: The total declared local variable size in device function
256q5_q8_dot exceeds 128 bytes and may cause high register pressure. Consult with
257your hardware vendor to find the total register size available and adjust the
258code, or use smaller sub-group size to avoid high register pressure.
259*/
260__dpct_inline__ float q5_q8_dot(const Q5KBlock *__restrict__ bq5,
261                                const Q81Block *__restrict__ bq8, int iqs) {
262    int vl[2];
263    int vh[2];
264    int u[4];
265    float d8[2];
266    const int bq8_offset = 2 * ((iqs / 2) / 4);
267    const int* ql = reinterpret_cast<const int*>(bq5->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
268    const int* qh = reinterpret_cast<const int*>(bq5->qh + 4 * ((iqs / 2) % 4));
269    vl[0] = ql[0];
270    vl[1] = ql[4];
271    vh[0] = qh[0] >> bq8_offset;
272    vh[1] = qh[4] >> bq8_offset;
273
274    const uint16_t* scales = reinterpret_cast<const uint16_t*>(bq5->scales);
275    const int j = bq8_offset / 2;
276    const int jm = j & 1;
277    const uint32_t s0 = scales[jm];
278    const uint32_t s2 = scales[jm + 2];
279    const uint32_t s4 = scales[jm + 4];
280    const uint32_t hi = uint32_t(-int32_t(j >= 2));
281    uint16_t aux[2];
282    aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) |
283                     ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
284    aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) |
285                     ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
286    const uint8_t* sc = reinterpret_cast<const uint8_t*>(aux);
287    const uint8_t* m = sc + 2;
288#pragma unroll
289    for (int i = 0; i < 2; ++i) {
290        const Q81Block* bq8i = bq8 + bq8_offset + i;
291        d8[i] = bq8i->ds[0];
292        const int* q8 = reinterpret_cast<const int*>(bq8i->qs) + ((iqs / 2) % 4);
293        u[2 * i] = q8[0];
294        u[2 * i + 1] = q8[4];
295    }
296    return q5_q8_dot_impl(vl, vh, u, sc, m, bq5->dm, d8);
297}
298
299// The generic ncols=1 oracle uses 4 warps and 1 row (or 4 rows for small K),
300// eight weight blocks per K iteration, warp-ascending shared sum, then XOR tree.
301template <bool SmallK>
302__dpct_inline__ void native_q5_k_mmvq_kernel(const Q5KBlock *__restrict__ w,
303                                             const Q81Block *__restrict__ x,
304                                             float *__restrict__ y, int n_in,
305                                             int n_out) {
306    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
307    constexpr int ROWS = SmallK ? WARPS : 1;
308    constexpr int BLOCKS_PER_ITER = VDR * WARPS * WARP / QI;
309    const int tid =
310        WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
311    const int row0 = ROWS * int(item_ct1.get_group(2));
312    const int blocks_per_row = n_in / QK;
313    float tmp[ROWS] = {};
314    for (int kbx = tid / (QI / VDR); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
315        const int kby = kbx * (QK / Q8K);
316        const int kqs = VDR * (tid % (QI / VDR));
317#pragma unroll
318        for (int i = 0; i < ROWS; ++i) {
319            // The source assumes allocator padding for partial row groups. This
320            // guard preserves every valid row's math without an out-of-bounds read.
321            if (row0 + i < n_out) {
322                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
323                tmp[i] += q5_q8_dot(w + block, x + kby, kqs);
324            }
325        }
326    }
327    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
328        float[WARPS - 1][ROWS][WARP]>(
329        sycl::ext::oneapi::this_work_item::get_work_group<3>());
330    if (item_ct1.get_local_id(1) > 0) {
331#pragma unroll
332        for (int i = 0; i < ROWS; ++i)
333            partial[item_ct1.get_local_id(1) - 1][i][item_ct1.get_local_id(2)] =
334                tmp[i];
335    }
336    /*
337    DPCT1065: Consider replacing sycl::nd_item::barrier() with
338    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
339    performance if there is no access to global memory.
340    */
341    item_ct1.barrier();
342    if (item_ct1.get_local_id(1) > 0) return;
343#pragma unroll
344    for (int i = 0; i < ROWS; ++i) {
345#pragma unroll
346        for (int l = 0; l < WARPS - 1; ++l) tmp[i] +=
347            partial[l][i][item_ct1.get_local_id(2)];
348        tmp[i] = warp_sum(tmp[i]);
349        if (item_ct1.get_local_id(2) == i && row0 + i < n_out) y[row0 + i] =
350            tmp[i];
351    }
352}
353
354// Exact pinned vec_dot_q2_0_q8_1: each thread handles one 32-element chunk.
355// The weight block is only 2-byte aligned, so qs is intentionally loaded as
356// int16_t, unlike the naturally 4-byte aligned activation codes.
357__dpct_inline__ float q2_q8_dot(const Q20Block *__restrict__ w,
358                                const Q81Block *__restrict__ x, int iqs) {
359    const float d2 = w->d;
360    const int16_t* qs = reinterpret_cast<const int16_t*>(w->qs) + iqs * 4;
361    const Q81Block* chunk = x + iqs;
362    const int* q8 = reinterpret_cast<const int*>(chunk->qs);
363    int sumi = 0;
364#pragma unroll
365    for (int j = 0; j < 4; ++j) {
366        const int q = qs[j];
367        const int u = q8[j * 2];
368        const int v = q8[j * 2 + 1];
369        const int qe = dpct::byte_level_permute(0x020100ff, 0x020100ff, q >> 0);
370        const int qo = dpct::byte_level_permute(0x020100ff, 0x020100ff, q >> 2);
371        const int qx = dpct::byte_level_permute(qe, qo, 0x5140);
372        const int qy = dpct::byte_level_permute(qe, qo, 0x7362);
373        sumi = STRATA_DP4A(u, qx, sumi);
374        sumi = STRATA_DP4A(v, qy, sumi);
375    }
376    const float d8 = chunk->ds[0];
377    return d2 * d8 * sumi;
378}
379
380// Q2_0 generic MMVQ: QK=64, QI=2, VDR=1, 64 blocks per iteration.
381// Preserve the same outer accumulation and cross-warp reduction as the oracle.
382template <bool SmallK>
383__dpct_inline__ void native_q2_0_mmvq_kernel(const Q20Block *__restrict__ w,
384                                             const Q81Block *__restrict__ x,
385                                             float *__restrict__ y, int n_in,
386                                             int n_out) {
387    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
388    constexpr int ROWS = SmallK ? WARPS : 1;
389    constexpr int BLOCKS_PER_ITER = WARPS * WARP / 2;
390    const int tid =
391        WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
392    const int row0 = ROWS * int(item_ct1.get_group(2));
393    const int blocks_per_row = n_in / 64;
394    float tmp[ROWS] = {};
395    for (int kbx = tid / 2; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
396        const int kby = kbx * 2;
397        const int kqs = tid % 2;
398#pragma unroll
399        for (int i = 0; i < ROWS; ++i) {
400            if (row0 + i < n_out) {
401                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
402                tmp[i] += q2_q8_dot(w + block, x + kby, kqs);
403            }
404        }
405    }
406    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
407        float[WARPS - 1][ROWS][WARP]>(
408        sycl::ext::oneapi::this_work_item::get_work_group<3>());
409    if (item_ct1.get_local_id(1) > 0) {
410#pragma unroll
411        for (int i = 0; i < ROWS; ++i)
412            partial[item_ct1.get_local_id(1) - 1][i][item_ct1.get_local_id(2)] =
413                tmp[i];
414    }
415    /*
416    DPCT1065: Consider replacing sycl::nd_item::barrier() with
417    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
418    performance if there is no access to global memory.
419    */
420    item_ct1.barrier();
421    if (item_ct1.get_local_id(1) > 0) return;
422#pragma unroll
423    for (int i = 0; i < ROWS; ++i) {
424#pragma unroll
425        for (int l = 0; l < WARPS - 1; ++l) tmp[i] +=
426            partial[l][i][item_ct1.get_local_id(2)];
427        tmp[i] = warp_sum(tmp[i]);
428        if (item_ct1.get_local_id(2) == i && row0 + i < n_out) y[row0 + i] =
429            tmp[i];
430    }
431}
432
433// Q3_K's 110-byte stride gives alternate blocks only two-byte alignment.
434// Preserve the pinned helper's pair of 16-bit loads and little-endian combine.
435__dpct_inline__ int load_int_b2(const void *ptr, int i32) {
436    const auto* x = static_cast<const uint16_t*>(ptr);
437    int value = x[2 * i32] << 0;
438    value |= x[2 * i32 + 1] << 16;
439    return value;
440}
441
442__dpct_inline__ float q3_q8_dot_impl(int vl, int vh, const int *__restrict__ u,
443                                     const uint8_t *__restrict__ scales,
444                                     int scale_offset, float d3,
445                                     const float *__restrict__ d8) {
446    float sumf = 0.0f;
447#pragma unroll
448    for (int i = 0; i < 4; ++i) {
449        const int isc = scale_offset + 2 * i;
450        const int isc_low = isc % 8;
451        const int sc_shift_low = 4 * (isc / 8);
452        const int sc_low = (scales[isc_low] >> sc_shift_low) & 0xf;
453        const int isc_high = isc % 4;
454        const int sc_shift_high = 2 * (isc / 4);
455        const int sc_high = ((scales[8 + isc_high] >> sc_shift_high) & 3) << 4;
456        const int sc = (sc_low | sc_high) - 32;
457        const int vil = (vl >> (2 * i)) & 0x03030303;
458        const int vih = ((vh >> i) << 2) & 0x04040404;
459        const int vi =
460            dpct::vectorized_binary<sycl::char4>(vil, vih, dpct::sub_sat());
461        sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);
462    }
463    return d3 * sumf;
464}
465
466__dpct_inline__ float q3_q8_dot(const Q3KBlock *__restrict__ w,
467                                const Q81Block *__restrict__ x, int iqs) {
468    const int bq8_offset = 4 * (iqs / 8);
469    const int scale_offset = iqs - iqs % 8 + (iqs % 8) / 4;
470    const float d = w->d;
471    const int vl = load_int_b2(w->qs, iqs);
472    const int vh = ~load_int_b2(w->hmask, iqs % 8) >> bq8_offset;
473    int u[4];
474    float d8[4];
475#pragma unroll
476    for (int i = 0; i < 4; ++i) {
477        u[i] = reinterpret_cast<const int*>(x[bq8_offset + i].qs)[iqs % 8];
478        d8[i] = x[bq8_offset + i].ds[0];
479    }
480    return q3_q8_dot_impl(vl, vh, u, w->scales, scale_offset, d, d8);
481}
482
483// Q3_K generic MMVQ: QK=256, QI=16, VDR=1, eight blocks per iteration.
484template <bool SmallK>
485__dpct_inline__ void native_q3_k_mmvq_kernel(const Q3KBlock *__restrict__ w,
486                                             const Q81Block *__restrict__ x,
487                                             float *__restrict__ y, int n_in,
488                                             int n_out) {
489    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
490    constexpr int ROWS = SmallK ? WARPS : 1;
491    constexpr int BLOCKS_PER_ITER = WARPS * WARP / 16;
492    const int tid =
493        WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
494    const int row0 = ROWS * int(item_ct1.get_group(2));
495    const int blocks_per_row = n_in / 256;
496    float tmp[ROWS] = {};
497    for (int kbx = tid / 16; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
498        const int kby = kbx * 8;
499        const int kqs = tid % 16;
500#pragma unroll
501        for (int i = 0; i < ROWS; ++i) {
502            if (row0 + i < n_out) {
503                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
504                tmp[i] += q3_q8_dot(w + block, x + kby, kqs);
505            }
506        }
507    }
508    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
509        float[WARPS - 1][ROWS][WARP]>(
510        sycl::ext::oneapi::this_work_item::get_work_group<3>());
511    if (item_ct1.get_local_id(1) > 0) {
512#pragma unroll
513        for (int i = 0; i < ROWS; ++i)
514            partial[item_ct1.get_local_id(1) - 1][i][item_ct1.get_local_id(2)] =
515                tmp[i];
516    }
517    /*
518    DPCT1065: Consider replacing sycl::nd_item::barrier() with
519    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
520    performance if there is no access to global memory.
521    */
522    item_ct1.barrier();
523    if (item_ct1.get_local_id(1) > 0) return;
524#pragma unroll
525    for (int i = 0; i < ROWS; ++i) {
526#pragma unroll
527        for (int l = 0; l < WARPS - 1; ++l) tmp[i] +=
528            partial[l][i][item_ct1.get_local_id(2)];
529        tmp[i] = warp_sum(tmp[i]);
530        if (item_ct1.get_local_id(2) == i && row0 + i < n_out) y[row0 + i] =
531            tmp[i];
532    }
533}
534
535// The pinned nonlinear IQ4 codebook and its CUDA two-stage byte lookup. The
536// explicit alignment satisfies the four 32-bit table loads; values are unchanged.
537inline dpct::global_memory<int8_t, 1>& iq4nl_values = *new dpct::global_memory<int8_t, 1>(sycl::range(16), {-127, -104, -83, -65, -49, -35, -22, -10, 1,
538                                   13, 25, 38, 53, 69, 89, 113});
539
540static constexpr int8_t kIq4nlTable[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
541__dpct_inline__ sycl::int2 iq4_table_lookup(int q4, int8_t *iq4nl_values) {
542#if defined(STRATA_HIP_GFX906)
543    // AMD: llama.cpp's HIP lookup (see iq_kernels.cu get_int_from_table_16): 4 v_perm_b32 per 8 values
544    const uint32_t* v32 = reinterpret_cast<const uint32_t*>(iq4nl_values);
545    const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;
546    const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);
547    const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);
548    const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);
549    const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);
550    return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),
551                     (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));
552#else
553    const uint32_t* table32 = reinterpret_cast<const uint32_t*>(iq4nl_values);
554    uint32_t tmp[2];
555    const uint32_t low_high_selection_indices = 0x32103210 | ((q4 & 0x88888888) >> 1);
556#pragma unroll
557    for (uint32_t i = 0; i < 2; ++i) {
558        const uint32_t shift = 16 * i;
559        const uint32_t low =
560            dpct::byte_level_permute(table32[0], table32[1], q4 >> shift);
561        const uint32_t high =
562            dpct::byte_level_permute(table32[2], table32[3], q4 >> shift);
563        tmp[i] = dpct::byte_level_permute(low, high,
564                                          low_high_selection_indices >> shift);
565    }
566    return sycl::int2(dpct::byte_level_permute(tmp[0], tmp[1], 0x6420),
567                      dpct::byte_level_permute(tmp[0], tmp[1], 0x7531));
568#endif
569}
570
571// Exact pinned vec_dot_iq4_xs_q8_1: a lane consumes one 32-element subblock,
572// computes integer dot products, applies signed scale in the integer domain,
573// then multiplies the two half scales and integer sum in the original order.
574__dpct_inline__ float iq4_xs_q8_dot(const IQ4XSBlock *__restrict__ w,
575                                    const Q81Block *__restrict__ x, int iqs,
576                                    int8_t *iq4nl_values) {
577    int sumi = 0;
578#pragma unroll
579    for (int j = 0; j < 4; ++j) {
580        const int aux_q4 = reinterpret_cast<const int*>(w->qs)[iqs + j];
581        const sycl::int2 v = iq4_table_lookup(aux_q4, iq4nl_values);
582        const int u0 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j];
583        const int u1 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j + 4];
584        sumi = STRATA_DP4A(v.x(), u0, sumi);
585        sumi = STRATA_DP4A(v.y(), u1, sumi);
586    }
587    const int ls = ((w->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0f) |
588                   (((w->scales_h >> (iqs / 2)) & 0x03) << 4);
589    sumi *= ls - 32;
590    const float d = sycl::vec<sycl::half, 1>(w->d)
591                        .convert<float, sycl::rounding_mode::automatic>()[0] *
592                    x[iqs / 4].ds[0];
593    return d * sumi;
594}
595
596// IQ4_XS generic MMVQ: QK=256, QI=32, VDR=4,16 blocks per iteration.
597template <bool SmallK>
598__dpct_inline__ void
599native_iq4_xs_mmvq_kernel(const IQ4XSBlock *__restrict__ w,
600                          const Q81Block *__restrict__ x, float *__restrict__ y,
601                          int n_in, int n_out, int8_t *iq4nl_values) {
602    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
603    constexpr int ROWS = SmallK ? WARPS : 1;
604    constexpr int BLOCKS_PER_ITER = 4 * WARPS * WARP / 32;
605    const int tid =
606        WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
607    const int row0 = ROWS * int(item_ct1.get_group(2));
608    const int blocks_per_row = n_in / 256;
609    float tmp[ROWS] = {};
610    for (int kbx = tid / 8; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
611        const int kby = kbx * 8;
612        const int kqs = 4 * (tid % 8);
613#pragma unroll
614        for (int i = 0; i < ROWS; ++i) {
615            if (row0 + i < n_out) {
616                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
617                tmp[i] += iq4_xs_q8_dot(w + block, x + kby, kqs, iq4nl_values);
618            }
619        }
620    }
621    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
622        float[WARPS - 1][ROWS][WARP]>(
623        sycl::ext::oneapi::this_work_item::get_work_group<3>());
624    if (item_ct1.get_local_id(1) > 0) {
625#pragma unroll
626        for (int i = 0; i < ROWS; ++i)
627            partial[item_ct1.get_local_id(1) - 1][i][item_ct1.get_local_id(2)] =
628                tmp[i];
629    }
630    /*
631    DPCT1065: Consider replacing sycl::nd_item::barrier() with
632    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
633    performance if there is no access to global memory.
634    */
635    item_ct1.barrier();
636    if (item_ct1.get_local_id(1) > 0) return;
637#pragma unroll
638    for (int i = 0; i < ROWS; ++i) {
639#pragma unroll
640        for (int l = 0; l < WARPS - 1; ++l) tmp[i] +=
641            partial[l][i][item_ct1.get_local_id(2)];
642        tmp[i] = warp_sum(tmp[i]);
643        if (item_ct1.get_local_id(2) == i && row0 + i < n_out) y[row0 + i] =
644            tmp[i];
645    }
646}
647
648// Exact pinned vec_dot_q4_K_q8_1_impl_vmmq expression and integer dot order.
649__dpct_inline__ float
650q4_q8_dot_impl(const int *__restrict__ v, const int *__restrict__ u,
651               const uint8_t *__restrict__ sc, const uint8_t *__restrict__ m,
652               const sycl::half2 &dm4, const float *__restrict__ d8) {
653    float sumf_d = 0.0f;
654    float sumf_m = 0.0f;
655#pragma unroll
656    for (int i = 0; i < 2; ++i) {
657        const int v0i = (v[0] >> (4 * i)) & 0x0f0f0f0f;
658        const int v1i = (v[1] >> (4 * i)) & 0x0f0f0f0f;
659        const int dot1 = STRATA_DP4A(v1i, u[2 * i + 1], STRATA_DP4A(v0i, u[2 * i], 0));
660        const int dot2 = STRATA_DP4A(0x01010101, u[2 * i + 1], STRATA_DP4A(0x01010101, u[2 * i], 0));
661        sumf_d += d8[i] * (dot1 * sc[i]);
662        sumf_m += d8[i] * (dot2 * m[i]);
663    }
664    const sycl::float2 dm4f =
665        dm4.template convert<float, sycl::rounding_mode::automatic>();
666    return dm4f.x() * sumf_d - dm4f.y() * sumf_m;
667}
668
669__dpct_inline__ float q4_q8_dot(const Q4KBlock *__restrict__ bq4,
670                                const Q81Block *__restrict__ bq8, int iqs) {
671    int v[2];
672    int u[4];
673    float d8[2];
674    const int bq8_offset = 2 * ((iqs / 2) / 4);
675    const int* ql = reinterpret_cast<const int*>(bq4->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
676    v[0] = ql[0];
677    v[1] = ql[4];
678
679    const uint16_t* scales = reinterpret_cast<const uint16_t*>(bq4->scales);
680    const int j = bq8_offset / 2;
681    const int jm = j & 1;
682    const uint32_t s0 = scales[jm];
683    const uint32_t s2 = scales[jm + 2];
684    const uint32_t s4 = scales[jm + 4];
685    const uint32_t hi = uint32_t(-int32_t(j >= 2));
686    uint16_t aux[2];
687    aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) |
688                     ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
689    aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) |
690                     ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
691    const uint8_t* sc = reinterpret_cast<const uint8_t*>(aux);
692    const uint8_t* m = sc + 2;
693#pragma unroll
694    for (int i = 0; i < 2; ++i) {
695        const Q81Block* bq8i = bq8 + bq8_offset + i;
696        d8[i] = bq8i->ds[0];
697        const int* q8 = reinterpret_cast<const int*>(bq8i->qs) + ((iqs / 2) % 4);
698        u[2 * i] = q8[0];
699        u[2 * i + 1] = q8[4];
700    }
701    return q4_q8_dot_impl(v, u, sc, m, bq4->dm, d8);
702}
703
704// The generic ncols=1 oracle uses 4 warps and 1 row (or 4 rows for small K),
705// eight weight blocks per K iteration, warp-ascending shared sum, then XOR tree.
706template <bool SmallK>
707__dpct_inline__ void native_q4_k_mmvq_kernel(const Q4KBlock *__restrict__ w,
708                                             const Q81Block *__restrict__ x,
709                                             float *__restrict__ y, int n_in,
710                                             int n_out) {
711    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
712    constexpr int ROWS = SmallK ? WARPS : 1;
713    constexpr int BLOCKS_PER_ITER = VDR * WARPS * WARP / QI;
714    const int tid =
715        WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
716    const int row0 = ROWS * int(item_ct1.get_group(2));
717    const int blocks_per_row = n_in / QK;
718    float tmp[ROWS] = {};
719    for (int kbx = tid / (QI / VDR); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
720        const int kby = kbx * (QK / Q8K);
721        const int kqs = VDR * (tid % (QI / VDR));
722#pragma unroll
723        for (int i = 0; i < ROWS; ++i) {
724            // The source assumes allocator padding for partial row groups. This
725            // guard preserves every valid row's math without an out-of-bounds read.
726            if (row0 + i < n_out) {
727                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
728                tmp[i] += q4_q8_dot(w + block, x + kby, kqs);
729            }
730        }
731    }
732    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
733        float[WARPS - 1][ROWS][WARP]>(
734        sycl::ext::oneapi::this_work_item::get_work_group<3>());
735    if (item_ct1.get_local_id(1) > 0) {
736#pragma unroll
737        for (int i = 0; i < ROWS; ++i)
738            partial[item_ct1.get_local_id(1) - 1][i][item_ct1.get_local_id(2)] =
739                tmp[i];
740    }
741    /*
742    DPCT1065: Consider replacing sycl::nd_item::barrier() with
743    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
744    performance if there is no access to global memory.
745    */
746    item_ct1.barrier();
747    if (item_ct1.get_local_id(1) > 0) return;
748#pragma unroll
749    for (int i = 0; i < ROWS; ++i) {
750#pragma unroll
751        for (int l = 0; l < WARPS - 1; ++l) tmp[i] +=
752            partial[l][i][item_ct1.get_local_id(2)];
753        tmp[i] = warp_sum(tmp[i]);
754        if (item_ct1.get_local_id(2) == i && row0 + i < n_out) y[row0 + i] =
755            tmp[i];
756    }
757}
758
759// Exact pinned vec_dot_q6_K_q8_1: keep signed per-16-element scales,
760// signed-byte subtraction, DP4A order, and the float accumulation sequence.
761__dpct_inline__ float q6_q8_dot_impl(int vl, int vh, const int *__restrict__ u,
762                                     const int8_t *__restrict__ scales, float d,
763                                     const float *__restrict__ d8) {
764    float sumf = 0.0f;
765#pragma unroll
766    for (int i = 0; i < 2; ++i) {
767        const int sc = scales[4 * i];
768        const int vil = (vl >> (4 * i)) & 0x0f0f0f0f;
769        const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;
770        const int vi = dpct::vectorized_binary<sycl::char4>(
771            vil | vih, 0x20202020, dpct::sub_sat());
772        sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);
773    }
774    return d * sumf;
775}
776
777__dpct_inline__ float q6_q8_dot(const Q6KBlock *__restrict__ w,
778                                const Q81Block *__restrict__ x, int iqs) {
779    const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8;
780    const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4;
781    const int vh_shift = 2 * ((iqs % 16) / 8);
782    const int vl = load_int_b2(w->ql, iqs);
783    const int vh = load_int_b2(w->qh, 8 * (iqs / 16) + iqs % 8) >> vh_shift;
784    int u[2];
785    float d8[2];
786#pragma unroll
787    for (int i = 0; i < 2; ++i) {
788        u[i] = reinterpret_cast<const int*>(x[bq8_offset + 2 * i].qs)[iqs % 8];
789        d8[i] = x[bq8_offset + 2 * i].ds[0];
790    }
791    return q6_q8_dot_impl(vl, vh, u, w->scales + scale_offset, w->d, d8);
792}
793
794// Q6_K generic MMVQ: QK=256, QI=32, VDR=1, four blocks per iteration.
795template <bool SmallK>
796__dpct_inline__ void native_q6_k_mmvq_kernel(const Q6KBlock *__restrict__ w,
797                                             const Q81Block *__restrict__ x,
798                                             float *__restrict__ y, int n_in,
799                                             int n_out) {
800    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
801    constexpr int ROWS = SmallK ? WARPS : 1;
802    constexpr int BLOCKS_PER_ITER = WARPS * WARP / 32;
803    const int tid =
804        WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
805    const int row0 = ROWS * int(item_ct1.get_group(2));
806    const int blocks_per_row = n_in / 256;
807    float tmp[ROWS] = {};
808    for (int kbx = tid / 32; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
809        const int kby = kbx * 8;
810        const int kqs = tid % 32;
811#pragma unroll
812        for (int i = 0; i < ROWS; ++i) {
813            if (row0 + i < n_out) {
814                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
815                tmp[i] += q6_q8_dot(w + block, x + kby, kqs);
816            }
817        }
818    }
819    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
820        float[WARPS - 1][ROWS][WARP]>(
821        sycl::ext::oneapi::this_work_item::get_work_group<3>());
822    if (item_ct1.get_local_id(1) > 0) {
823#pragma unroll
824        for (int i = 0; i < ROWS; ++i)
825            partial[item_ct1.get_local_id(1) - 1][i][item_ct1.get_local_id(2)] =
826                tmp[i];
827    }
828    /*
829    DPCT1065: Consider replacing sycl::nd_item::barrier() with
830    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
831    performance if there is no access to global memory.
832    */
833    item_ct1.barrier();
834    if (item_ct1.get_local_id(1) > 0) return;
835#pragma unroll
836    for (int i = 0; i < ROWS; ++i) {
837#pragma unroll
838        for (int l = 0; l < WARPS - 1; ++l) tmp[i] +=
839            partial[l][i][item_ct1.get_local_id(2)];
840        tmp[i] = warp_sum(tmp[i]);
841        if (item_ct1.get_local_id(2) == i && row0 + i < n_out) y[row0 + i] =
842            tmp[i];
843    }
844}
845
846// The four 32-element formats use native two-byte loads and VDR=2. The affine
847// Q4_0/Q5_0 correction consumes the original-input sum stored in Q8_1, exactly
848// as the pinned CUDA dot does; a signed-integer code substitution would differ.
849__dpct_inline__ float small_q8_dot(const Q40Block *__restrict__ w,
850                                   const Q81Block *__restrict__ x, int iqs,
851                                   int8_t *iq4nl_values) {
852    int sumi = 0;
853#pragma unroll
854    for (int i = 0; i < 2; ++i) {
855        const int v = load_int_b2(w->qs, iqs + i);
856        const int vi0 = (v >> 0) & 0x0f0f0f0f;
857        const int vi1 = (v >> 4) & 0x0f0f0f0f;
858        sumi = STRATA_DP4A(vi0, reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
859        sumi = STRATA_DP4A(vi1, reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
860    }
861    const sycl::float2 ds =
862        (x->ds).template convert<float, sycl::rounding_mode::automatic>();
863    const float d = w->d;
864    return d * (sumi * ds.x() - 4 * ds.y());
865}
866
867__dpct_inline__ float small_q8_dot(const Q50Block *__restrict__ w,
868                                   const Q81Block *__restrict__ x, int iqs,
869                                   int8_t *iq4nl_values) {
870    int sumi = 0;
871#pragma unroll
872    for (int i = 0; i < 2; ++i) {
873        const int vl = load_int_b2(w->qs, iqs + i);
874        const int vh = load_int_b2(w->qh, 0) >> (4 * (iqs + i));
875        int vi0 = (vl >> 0) & 0x0f0f0f0f;
876        vi0 |= (vh << 4) & 0x00000010;
877        vi0 |= (vh << 11) & 0x00001000;
878        vi0 |= (vh << 18) & 0x00100000;
879        vi0 |= (vh << 25) & 0x10000000;
880        sumi = STRATA_DP4A(vi0, reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
881        int vi1 = (vl >> 4) & 0x0f0f0f0f;
882        vi1 |= (vh >> 12) & 0x00000010;
883        vi1 |= (vh >> 5) & 0x00001000;
884        vi1 |= (vh << 2) & 0x00100000;
885        vi1 |= (vh << 9) & 0x10000000;
886        sumi = STRATA_DP4A(vi1, reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
887    }
888    const sycl::float2 ds =
889        (x->ds).template convert<float, sycl::rounding_mode::automatic>();
890    const float d = w->d;
891    return d * (sumi * ds.x() - 8 * ds.y());
892}
893
894__dpct_inline__ float small_q8_dot(const Q80Block *__restrict__ w,
895                                   const Q81Block *__restrict__ x, int iqs,
896                                   int8_t *iq4nl_values) {
897    int sumi = 0;
898#pragma unroll
899    for (int i = 0; i < 2; ++i) {
900        const int v = load_int_b2(w->qs, iqs + i);
901        const int u = reinterpret_cast<const int*>(x->qs)[iqs + i];
902        sumi = STRATA_DP4A(v, u, sumi);
903    }
904    const float d0 = w->d;
905    const float d1 = x->ds[0];
906    return d0 * d1 * float(sumi);
907}
908
909__dpct_inline__ float small_q8_dot(const IQ4NLBlock *__restrict__ w,
910                                   const Q81Block *__restrict__ x, int iqs,
911                                   int8_t *iq4nl_values) {
912    const int* q8 = reinterpret_cast<const int*>(x->qs) + iqs;
913    int sumi = 0;
914#pragma unroll
915    for (int i = 0; i < 2; ++i) {
916        const sycl::int2 v =
917            iq4_table_lookup(load_int_b2(w->qs, iqs + i), iq4nl_values);
918        sumi = STRATA_DP4A(v.x(), q8[i], sumi);
919        sumi = STRATA_DP4A(v.y(), q8[i + 4], sumi);
920    }
921    const float d = sycl::vec<sycl::half, 1>(w->d)
922                        .convert<float, sycl::rounding_mode::automatic>()[0] *
923                    x->ds[0];
924    return d * sumi;
925}
926
927// QI=4 for Q4_0/Q5_0/IQ4_NL and QI=8 for Q8_0. With VDR=2 this preserves
928// the pinned 64/32-block iteration and 2048/1024-element small-K thresholds.
929template <typename Weight, int Qi, bool SmallK>
930__dpct_inline__ void native_small_mmvq_kernel(const Weight *__restrict__ w,
931                                              const Q81Block *__restrict__ x,
932                                              float *__restrict__ y, int n_in,
933                                              int n_out, int8_t *iq4nl_values) {
934    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
935    constexpr int ROWS = SmallK ? WARPS : 1;
936    constexpr int BLOCKS_PER_ITER = 2 * WARPS * WARP / Qi;
937    const int tid =
938        WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
939    const int row0 = ROWS * int(item_ct1.get_group(2));
940    const int blocks_per_row = n_in / 32;
941    float tmp[ROWS] = {};
942    for (int kbx = tid / (Qi / 2); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
943        const int kqs = 2 * (tid % (Qi / 2));
944#pragma unroll
945        for (int i = 0; i < ROWS; ++i) {
946            if (row0 + i < n_out) {
947                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
948                tmp[i] += small_q8_dot(w + block, x + kbx, kqs, iq4nl_values);
949            }
950        }
951    }
952    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
953        float[WARPS - 1][ROWS][WARP]>(
954        sycl::ext::oneapi::this_work_item::get_work_group<3>());
955    if (item_ct1.get_local_id(1) > 0) {
956#pragma unroll
957        for (int i = 0; i < ROWS; ++i)
958            partial[item_ct1.get_local_id(1) - 1][i][item_ct1.get_local_id(2)] =
959                tmp[i];
960    }
961    /*
962    DPCT1065: Consider replacing sycl::nd_item::barrier() with
963    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
964    performance if there is no access to global memory.
965    */
966    item_ct1.barrier();
967    if (item_ct1.get_local_id(1) > 0) return;
968#pragma unroll
969    for (int i = 0; i < ROWS; ++i) {
970#pragma unroll
971        for (int l = 0; l < WARPS - 1; ++l) tmp[i] +=
972            partial[l][i][item_ct1.get_local_id(2)];
973        tmp[i] = warp_sum(tmp[i]);
974        if (item_ct1.get_local_id(2) == i && row0 + i < n_out) y[row0 + i] =
975            tmp[i];
976    }
977}
978
979// ============================ plan v0.3 P3: ncols = 2..8 (speculative verify, small batches) ============================
980//
981// One generic kernel for every format, parameterized by the format's iteration traits below, which are
982// transcribed from the ncols = 1 kernels above (same thread-to-block mapping, same blocks per iteration, same
983// small-K rule). Column j reads activation blocks x + j * (n_in / 32) and writes y + j * n_out. Each (column,
984// row) value is accumulated over kbx in the same order, summed across warps in the same order and reduced with
985// the same warp tree as the ncols = 1 kernel, so every column is BITWISE equal to a single-column call on that
986// column (checked by bench/micro/native_mmvq_multi.cpp). The ncols = 1 kernels are untouched.
987constexpr int MAX_NCOLS = 8;
988
989// Each format splits its dot product into `load` (everything that depends only on the weight block: codes,
990// unpacked scales, block scale) and `apply` (the activation loads and the original *_impl expression). `load` runs
991// once per (row, block) and `apply` once per column, so adding columns adds only activation work. `apply` calls
992// the same impl functions, in the same order, with the same values as the ncols = 1 dot, which is what keeps
993// every column bitwise equal to it.
994struct Q5KTraits {
995    using Block = Q5KBlock;
996    static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI;
997    static int kqs(int tid) { return VDR * (tid % (QI / VDR)); }
998    struct W {
999        int vl[2], vh[2]; uint16_t aux[2]; sycl::half2 dm; int bq8_offset;
1000    };
1001    static W load(const Block* __restrict__ bq5, int iqs) {
1002        W r;
1003        r.bq8_offset = 2 * ((iqs / 2) / 4);
1004        const int* ql = reinterpret_cast<const int*>(bq5->qs + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4));
1005        const int* qh = reinterpret_cast<const int*>(bq5->qh + 4 * ((iqs / 2) % 4));
1006        r.vl[0] = ql[0];
1007        r.vl[1] = ql[4];
1008        r.vh[0] = qh[0] >> r.bq8_offset;
1009        r.vh[1] = qh[4] >> r.bq8_offset;
1010        const uint16_t* scales = reinterpret_cast<const uint16_t*>(bq5->scales);
1011        const int j = r.bq8_offset / 2;
1012        const int jm = j & 1;
1013        const uint32_t s0 = scales[jm];
1014        const uint32_t s2 = scales[jm + 2];
1015        const uint32_t s4 = scales[jm + 4];
1016        const uint32_t hi = uint32_t(-int32_t(j >= 2));
1017        r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
1018        r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
1019        r.dm = bq5->dm;
1020        return r;
1021    }
1022    static float apply(const W& r, const Q81Block* __restrict__ bq8, int iqs) {
1023        int u[4];
1024        float d8[2];
1025#pragma unroll
1026        for (int i = 0; i < 2; ++i) {
1027            const Q81Block* bq8i = bq8 + r.bq8_offset + i;
1028            d8[i] = bq8i->ds[0];
1029            const int* q8 = reinterpret_cast<const int*>(bq8i->qs) + ((iqs / 2) % 4);
1030            u[2 * i] = q8[0];
1031            u[2 * i + 1] = q8[4];
1032        }
1033        const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux);
1034        return q5_q8_dot_impl(r.vl, r.vh, u, sc, sc + 2, r.dm, d8);
1035    }
1036};
1037struct Q4KTraits {
1038    using Block = Q4KBlock;
1039    static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI;
1040    static int kqs(int tid) { return VDR * (tid % (QI / VDR)); }
1041    struct W { int v[2]; uint16_t aux[2]; sycl::half2 dm; int bq8_offset; };
1042    static W load(const Block* __restrict__ bq4, int iqs) {
1043        W r;
1044        r.bq8_offset = 2 * ((iqs / 2) / 4);
1045        const int* ql = reinterpret_cast<const int*>(bq4->qs + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4));
1046        r.v[0] = ql[0];
1047        r.v[1] = ql[4];
1048        const uint16_t* scales = reinterpret_cast<const uint16_t*>(bq4->scales);
1049        const int j = r.bq8_offset / 2;
1050        const int jm = j & 1;
1051        const uint32_t s0 = scales[jm];
1052        const uint32_t s2 = scales[jm + 2];
1053        const uint32_t s4 = scales[jm + 4];
1054        const uint32_t hi = uint32_t(-int32_t(j >= 2));
1055        r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
1056        r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
1057        r.dm = bq4->dm;
1058        return r;
1059    }
1060    static float apply(const W& r, const Q81Block* __restrict__ bq8, int iqs) {
1061        int u[4];
1062        float d8[2];
1063#pragma unroll
1064        for (int i = 0; i < 2; ++i) {
1065            const Q81Block* bq8i = bq8 + r.bq8_offset + i;
1066            d8[i] = bq8i->ds[0];
1067            const int* q8 = reinterpret_cast<const int*>(bq8i->qs) + ((iqs / 2) % 4);
1068            u[2 * i] = q8[0];
1069            u[2 * i + 1] = q8[4];
1070        }
1071        const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux);
1072        return q4_q8_dot_impl(r.v, u, sc, sc + 2, r.dm, d8);
1073    }
1074};
1075struct Q20Traits {
1076    using Block = Q20Block;
1077    static constexpr int DIV = 64, T = 2, KBY = 2, BPI = WARPS * WARP / 2;
1078    static int kqs(int tid) { return tid % 2; }
1079    struct W { int qx[4], qy[4]; float d2; };
1080    static W load(const Block* __restrict__ w, int iqs) {
1081        W r;
1082        r.d2 = w->d;
1083        const int16_t* qs = reinterpret_cast<const int16_t*>(w->qs) + iqs * 4;
1084#pragma unroll
1085        for (int j = 0; j < 4; ++j) {
1086            const int q = qs[j];
1087            const int qe =
1088                dpct::byte_level_permute(0x020100ff, 0x020100ff, q >> 0);
1089            const int qo =
1090                dpct::byte_level_permute(0x020100ff, 0x020100ff, q >> 2);
1091            r.qx[j] = dpct::byte_level_permute(qe, qo, 0x5140);
1092            r.qy[j] = dpct::byte_level_permute(qe, qo, 0x7362);
1093        }
1094        return r;
1095    }
1096    static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1097        const Q81Block* chunk = x + iqs;
1098        const int* q8 = reinterpret_cast<const int*>(chunk->qs);
1099        int sumi = 0;
1100#pragma unroll
1101        for (int j = 0; j < 4; ++j) {
1102            sumi = STRATA_DP4A(q8[j * 2], r.qx[j], sumi);
1103            sumi = STRATA_DP4A(q8[j * 2 + 1], r.qy[j], sumi);
1104        }
1105        const float d8 = chunk->ds[0];
1106        return r.d2 * d8 * sumi;
1107    }
1108};
1109struct Q3KTraits {
1110    using Block = Q3KBlock;
1111    static constexpr int DIV = 256, T = 16, KBY = 8, BPI = WARPS * WARP / 16;
1112    static int kqs(int tid) { return tid % 16; }
1113    struct W { int vl, vh; float d; const uint8_t* scales; int scale_offset, bq8_offset; };
1114    static W load(const Block* __restrict__ w, int iqs) {
1115        W r;
1116        r.bq8_offset = 4 * (iqs / 8);
1117        r.scale_offset = iqs - iqs % 8 + (iqs % 8) / 4;
1118        r.d = w->d;
1119        r.vl = load_int_b2(w->qs, iqs);
1120        r.vh = ~load_int_b2(w->hmask, iqs % 8) >> r.bq8_offset;
1121        r.scales = w->scales;
1122        return r;
1123    }
1124    static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1125        int u[4];
1126        float d8[4];
1127#pragma unroll
1128        for (int i = 0; i < 4; ++i) {
1129            u[i] = reinterpret_cast<const int*>(x[r.bq8_offset + i].qs)[iqs % 8];
1130            d8[i] = x[r.bq8_offset + i].ds[0];
1131        }
1132        return q3_q8_dot_impl(r.vl, r.vh, u, r.scales, r.scale_offset, r.d, d8);
1133    }
1134};
1135struct Q6KTraits {
1136    using Block = Q6KBlock;
1137    static constexpr int DIV = 256, T = 32, KBY = 8, BPI = WARPS * WARP / 32;
1138    static int kqs(int tid) { return tid % 32; }
1139    // SYCL port: the weight unpack (shifts, masks, the saturating byte subtract) is column-independent, so it is
1140    // done once in load(); apply() is two dp4a and two fmas per column.
1141    struct W { int vi[2]; float dsc[2]; int bq8_offset; };
1142    static W load(const Block* __restrict__ w, int iqs) {
1143        W r;
1144        r.bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8;
1145        const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4;
1146        const int vh_shift = 2 * ((iqs % 16) / 8);
1147        const int vl = load_int_b2(w->ql, iqs);
1148        const int vh = load_int_b2(w->qh, 8 * (iqs / 16) + iqs % 8) >> vh_shift;
1149        const float d = w->d;
1150#pragma unroll
1151        for (int i = 0; i < 2; ++i) {
1152            const int vil = (vl >> (4 * i)) & 0x0f0f0f0f;
1153            const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;
1154            r.vi[i] = dpct::vectorized_binary<sycl::char4>(vil | vih, 0x20202020, dpct::sub_sat());
1155            r.dsc[i] = d * (float) w->scales[scale_offset + 4 * i];
1156        }
1157        return r;
1158    }
1159    static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1160        float sumf = 0.0f;
1161#pragma unroll
1162        for (int i = 0; i < 2; ++i) {
1163            const int u = reinterpret_cast<const int*>(x[r.bq8_offset + 2 * i].qs)[iqs % 8];
1164            sumf += x[r.bq8_offset + 2 * i].ds[0] * r.dsc[i] * (float) strata::dp4a(r.vi[i], u, 0);
1165        }
1166        return sumf;
1167    }
1168    // SYCL port, row-blocked kernel: the activation's part for this (block, lane), loaded once per column and
1169    // reused across the warp's rows.
1170    struct A { int u[2]; float ds[2]; };
1171    static A acts(const Q81Block* __restrict__ x, int iqs) {
1172        A a;
1173        const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8;
1174#pragma unroll
1175        for (int i = 0; i < 2; ++i) {
1176            a.u[i] = reinterpret_cast<const int*>(x[bq8_offset + 2 * i].qs)[iqs % 8];
1177            a.ds[i] = x[bq8_offset + 2 * i].ds[0];
1178        }
1179        return a;
1180    }
1181    static float dot(const W& r, const A& a) {
1182        return a.ds[0] * r.dsc[0] * (float) strata::dp4a(r.vi[0], a.u[0], 0) +
1183               a.ds[1] * r.dsc[1] * (float) strata::dp4a(r.vi[1], a.u[1], 0);
1184    }
1185};
1186struct IQ4XSTraits {
1187    using Block = IQ4XSBlock;
1188    static constexpr int DIV = 256, T = 8, KBY = 8, BPI = 4 * WARPS * WARP / 32;
1189    static int kqs(int tid) { return 4 * (tid % 8); }
1190    struct W { sycl::int2 v[4]; int ls; float dw; };
1191    static W load(const Block* __restrict__ w, int iqs) { return load(w, iqs, const_cast<int8_t*>(kIq4nlTable)); }
1192    static W load(const Block* __restrict__ w, int iqs, int8_t *iq4nl_values) {
1193        W r;
1194#pragma unroll
1195        for (int j = 0; j < 4; ++j) r.v[j] = iq4_table_lookup(
1196            reinterpret_cast<const int *>(w->qs)[iqs + j], iq4nl_values);
1197        r.ls = ((w->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0f) | (((w->scales_h >> (iqs / 2)) & 0x03) << 4);
1198        r.dw = sycl::vec<sycl::half, 1>(w->d)
1199                   .convert<float, sycl::rounding_mode::automatic>()[0];
1200        return r;
1201    }
1202    static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1203        int sumi = 0;
1204#pragma unroll
1205        for (int j = 0; j < 4; ++j) {
1206            const int u0 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j];
1207            const int u1 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j + 4];
1208            sumi = STRATA_DP4A(r.v[j].x(), u0, sumi);
1209            sumi = STRATA_DP4A(r.v[j].y(), u1, sumi);
1210        }
1211        sumi *= r.ls - 32;
1212        const float d = r.dw * x[iqs / 4].ds[0];
1213        return d * sumi;
1214    }
1215};
1216// The four 32-element formats: `load` decodes the two 32-bit weight chunks and block scale once per (row, block),
1217// and `apply` runs the exact same STRATA_DP4A and scale arithmetic per activation column as `small_q8_dot`.
1218template<typename Weight, int Qi>
1219struct SmallTraits;
1220
1221template<>
1222struct SmallTraits<Q40Block, 4> {
1223    using Block = Q40Block;
1224    static constexpr int DIV = 32, T = 2, KBY = 1, BPI = 2 * WARPS * WARP / 4;
1225    static int kqs(int tid) { return 2 * (tid % 2); }
1226    struct W { int vi0[2], vi1[2]; float d; };
1227    static W load(const Block* __restrict__ w, int iqs) {
1228        W r;
1229#pragma unroll
1230        for (int i = 0; i < 2; ++i) {
1231            const int v = load_int_b2(w->qs, iqs + i);
1232            r.vi0[i] = (v >> 0) & 0x0f0f0f0f;
1233            r.vi1[i] = (v >> 4) & 0x0f0f0f0f;
1234        }
1235        r.d = w->d;
1236        return r;
1237    }
1238    static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1239        int sumi = 0;
1240#pragma unroll
1241        for (int i = 0; i < 2; ++i) {
1242            sumi = STRATA_DP4A(r.vi0[i], reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
1243            sumi = STRATA_DP4A(r.vi1[i], reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
1244        }
1245        const sycl::float2 ds =
1246            (x->ds).template convert<float, sycl::rounding_mode::automatic>();
1247        return r.d * (sumi * ds.x() - 4 * ds.y());
1248    }
1249};
1250
1251template<>
1252struct SmallTraits<Q50Block, 4> {
1253    using Block = Q50Block;
1254    static constexpr int DIV = 32, T = 2, KBY = 1, BPI = 2 * WARPS * WARP / 4;
1255    static int kqs(int tid) { return 2 * (tid % 2); }
1256    struct W { int vi0[2], vi1[2]; float d; };
1257    static W load(const Block* __restrict__ w, int iqs) {
1258        W r;
1259        const int qh = load_int_b2(w->qh, 0);
1260#pragma unroll
1261        for (int i = 0; i < 2; ++i) {
1262            const int vl = load_int_b2(w->qs, iqs + i);
1263            const int vh = qh >> (4 * (iqs + i));
1264            int vi0 = (vl >> 0) & 0x0f0f0f0f;
1265            vi0 |= (vh << 4) & 0x00000010;
1266            vi0 |= (vh << 11) & 0x00001000;
1267            vi0 |= (vh << 18) & 0x00100000;
1268            vi0 |= (vh << 25) & 0x10000000;
1269            r.vi0[i] = vi0;
1270            int vi1 = (vl >> 4) & 0x0f0f0f0f;
1271            vi1 |= (vh >> 12) & 0x00000010;
1272            vi1 |= (vh >> 5) & 0x00001000;
1273            vi1 |= (vh << 2) & 0x00100000;
1274            vi1 |= (vh << 9) & 0x10000000;
1275            r.vi1[i] = vi1;
1276        }
1277        r.d = w->d;
1278        return r;
1279    }
1280    static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1281        int sumi = 0;
1282#pragma unroll
1283        for (int i = 0; i < 2; ++i) {
1284            sumi = STRATA_DP4A(r.vi0[i], reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
1285            sumi = STRATA_DP4A(r.vi1[i], reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
1286        }
1287        const sycl::float2 ds =
1288            (x->ds).template convert<float, sycl::rounding_mode::automatic>();
1289        return r.d * (sumi * ds.x() - 8 * ds.y());
1290    }
1291};
1292
1293template<>
1294struct SmallTraits<Q80Block, 8> {
1295    using Block = Q80Block;
1296    static constexpr int DIV = 32, T = 4, KBY = 1, BPI = 2 * WARPS * WARP / 8;
1297    static int kqs(int tid) { return 2 * (tid % 4); }
1298    struct W { int v[2]; float d0; };
1299    static W load(const Block* __restrict__ w, int iqs) {
1300        W r;
1301#pragma unroll
1302        for (int i = 0; i < 2; ++i) r.v[i] = load_int_b2(w->qs, iqs + i);
1303        r.d0 = w->d;
1304        return r;
1305    }
1306    static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1307        int sumi = 0;
1308#pragma unroll
1309        for (int i = 0; i < 2; ++i) {
1310            const int u = reinterpret_cast<const int*>(x->qs)[iqs + i];
1311            sumi = STRATA_DP4A(r.v[i], u, sumi);
1312        }
1313        const float d1 = x->ds[0];
1314        return r.d0 * d1 * float(sumi);
1315    }
1316};
1317
1318template<>
1319struct SmallTraits<IQ4NLBlock, 4> {
1320    using Block = IQ4NLBlock;
1321    static constexpr int DIV = 32, T = 2, KBY = 1, BPI = 2 * WARPS * WARP / 4;
1322    static int kqs(int tid) { return 2 * (tid % 2); }
1323    struct W { sycl::int2 v[2]; float dw; };
1324    static W load(const Block* __restrict__ w, int iqs) { return load(w, iqs, const_cast<int8_t*>(kIq4nlTable)); }
1325    static W load(const Block* __restrict__ w, int iqs, int8_t *iq4nl_values) {
1326        W r;
1327#pragma unroll
1328        for (int i = 0; i < 2; ++i) r.v[i] =
1329            iq4_table_lookup(load_int_b2(w->qs, iqs + i), iq4nl_values);
1330        r.dw = sycl::vec<sycl::half, 1>(w->d)
1331                   .convert<float, sycl::rounding_mode::automatic>()[0];
1332        return r;
1333    }
1334    static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1335        const int* q8 = reinterpret_cast<const int*>(x->qs) + iqs;
1336        int sumi = 0;
1337#pragma unroll
1338        for (int i = 0; i < 2; ++i) {
1339            sumi = STRATA_DP4A(r.v[i].x(), q8[i], sumi);
1340            sumi = STRATA_DP4A(r.v[i].y(), q8[i + 4], sumi);
1341        }
1342        const float d = r.dw * x->ds[0];
1343        return d * sumi;
1344    }
1345};
1346
1347// NW warps per block and ROWS rows per block. The EXACT layout (NW = 4, ROWS = 1, or 4 for small K) is the
1348// ncols = 1 layout and keeps every column bitwise equal to a single-column call. The UPSTREAM layout is
1349// llama.cpp's generic multi-column table (ncols 2-4: 4 warps; 5-8: 2 warps; always 2 rows per block): faster,
1350// equal to ncols = 1 only to float rounding (the cross-warp reduction groups partial sums differently).
1351bool g_multi_exact = true;   // until the upstream layout is timed on an idle GPU (plan rule: default only what is measured)
1352
1353// S26 STRATA_TSUM=1 (TS): warp 0's NCOLS x ROWS sums as one transposed butterfly (s26_tsum.cuh), bitwise the same
1354static bool s26_tsum_on() {
1355    static const bool on = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();
1356    return on;
1357}
1358
1359// S26 STRATA_LFUSE (PAIR): blocks n_out.. compute the same rows of w2 into y2 (two matrices of one shape on one
1360// input in one launch; each output's code is the single matrix's)
1361template <typename F, int NCOLS, int NW, int ROWS, bool TS = false,
1362          bool PAIR = false, int SG = WARP>
1363/*
1364DPCT1110: The total declared local variable size in device function
1365native_mmvq_multi_kernel exceeds 128 bytes and may cause high register pressure.
1366Consult with your hardware vendor to find the total register size available and
1367adjust the code, or use smaller sub-group size to avoid high register pressure.
1368*/
1369__dpct_inline__ void
1370native_mmvq_multi_kernel(const typename F::Block *__restrict__ w,
1371                         const Q81Block *__restrict__ x, float *__restrict__ y,
1372                         int n_in, int n_out,
1373                         const typename F::Block *__restrict__ w2 = nullptr,
1374                         float *__restrict__ y2 = nullptr) {
1375    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1376    constexpr int BPI =
1377        F::BPI * NW * SG / (WARPS * WARP); // blocks per iteration scale with the thread count
1378    const int tid =
1379        SG * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
1380    int bxi = int(item_ct1.get_group(2));
1381    if constexpr (PAIR) {
1382        if (bxi >= n_out / ROWS) { bxi -= n_out / ROWS; w = w2; y = y2; }
1383    }
1384    const int row0 = ROWS * bxi;
1385    const int blocks_per_row = n_in / F::DIV;
1386    const int x_stride = n_in / Q8K;                   // Q8_1 blocks per activation column
1387    float tmp[NCOLS][ROWS] = {};
1388#pragma unroll STRATA_MMVQ_UNROLL   // SYCL port: several 256-blocks' loads in flight per warp (bytes in flight, not ALU)
1389    for (int kbx = tid / F::T; kbx < blocks_per_row; kbx += BPI) {
1390        const int kby = kbx * F::KBY;
1391        const int kqs = F::kqs(tid);
1392#pragma unroll
1393        for (int i = 0; i < ROWS; ++i) {
1394            if (row0 + i < n_out) {
1395                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
1396                /*
1397                DPCT1084: The function call "Q5KTraits::load" has multiple
1398                migration results in different template instantiations that
1399                could not be unified. You may need to adjust the code.
1400                */
1401                const typename F::W wv =
1402                    F::load(w + block, kqs); // once per (row, block)
1403#pragma unroll
1404                for (int j = 0; j < NCOLS; ++j)                         // then per column
1405                    tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);
1406            }
1407        }
1408    }
1409    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
1410        float[NW - 1 > 0 ? NW - 1 : 1][NCOLS][ROWS][SG]>(
1411        sycl::ext::oneapi::this_work_item::get_work_group<3>());
1412    if (item_ct1.get_local_id(1) > 0) {
1413#pragma unroll
1414        for (int j = 0; j < NCOLS; ++j)
1415#pragma unroll
1416            for (int i = 0; i < ROWS; ++i)
1417                partial[item_ct1.get_local_id(1) - 1][j][i]
1418                       [item_ct1.get_local_id(2)] = tmp[j][i];
1419    }
1420    /*
1421    DPCT1065: Consider replacing sycl::nd_item::barrier() with
1422    sycl::nd_item::barrier(sycl::access::fence_space::local_space) for better
1423    performance if there is no access to global memory.
1424    */
1425    item_ct1.barrier();
1426    if (item_ct1.get_local_id(1) > 0) return;
1427    if constexpr (TS) {
1428        constexpr int V = NCOLS * ROWS, P = s26ts::pow2_ceil(V);
1429        float v[P];
1430#pragma unroll
1431        for (int j = 0; j < NCOLS; ++j)
1432#pragma unroll
1433            for (int i = 0; i < ROWS; ++i) {
1434#pragma unroll
1435                for (int l = 0; l < NW - 1; ++l) tmp[j][i] +=
1436                    partial[l][j][i][item_ct1.get_local_id(2)];
1437                v[j * ROWS + i] = tmp[j][i];
1438            }
1439#pragma unroll
1440        for (int k = V; k < P; ++k) v[k] = 0.0f;
1441        const float sum = s26ts::tsum<P>(v, int(item_ct1.get_local_id(2)));
1442        const int k = s26ts::tsum_token<P>(int(item_ct1.get_local_id(2)));
1443        const int j = k / ROWS, i = k % ROWS;
1444        if (int(item_ct1.get_local_id(2)) == s26ts::tsum_lane<P>(k) && k < V &&
1445            row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = sum;
1446        return;
1447    }
1448#pragma unroll
1449    for (int j = 0; j < NCOLS; ++j) {
1450#pragma unroll
1451        for (int i = 0; i < ROWS; ++i) {
1452#pragma unroll
1453            for (int l = 0; l < NW - 1; ++l) tmp[j][i] +=
1454                partial[l][j][i][item_ct1.get_local_id(2)];
1455            tmp[j][i] = sg_sum<SG>(tmp[j][i]);
1456            if (item_ct1.get_local_id(2) == i && row0 + i < n_out)
1457                y[std::size_t(j) * n_out + row0 + i] = tmp[j][i];
1458        }
1459    }
1460}
1461
1462// ---------------------------------------------------------------- SYCL port: row-blocked mmvq
1463//
1464// Measured on the B70 (mmvq_bench): the shared kernel above spends its time re-reading the activation - every
1465// row's work-group loads all NCOLS columns of it again, and a 4-warp work-group per row ends in a barrier and an
1466// SLM reduction for ten blocks of work. Here each warp owns RPW rows outright: per 256-block it loads the
1467// activation parts once for all columns and the RPW weight parts once, does RPW x NCOLS dots, and reduces its
1468// own lanes at the end. No barrier, no SLM. Only for traits with acts()/dot() (Q6_K so far).
1469template <typename F, int NCOLS, int RPW>
1470void native_mmvq_rowwarp_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
1471                                float* __restrict__ y, int n_in, int n_out) {
1472    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1473    const int lane = int(item.get_local_id(2)), warp = int(item.get_local_id(1));
1474    const int row0 = (int(item.get_group(2)) * WARPS + warp) * RPW;
1475    const int blocks_per_row = n_in / F::DIV, x_stride = n_in / Q8K;
1476    const int kqs = F::kqs(lane);
1477    float tmp[RPW][NCOLS] = {};
1478    for (int kbx = lane / F::T; kbx < blocks_per_row; kbx += WARP / F::T) {
1479        const int kby = kbx * F::KBY;
1480        typename F::A a[NCOLS];
1481#pragma unroll
1482        for (int j = 0; j < NCOLS; ++j) a[j] = F::acts(x + std::size_t(j) * x_stride + kby, kqs);
1483#pragma unroll
1484        for (int r = 0; r < RPW; ++r) {
1485            if (row0 + r >= n_out) break;
1486            const typename F::W wv = F::load(w + std::size_t(row0 + r) * blocks_per_row + kbx, kqs);
1487#pragma unroll
1488            for (int j = 0; j < NCOLS; ++j) tmp[r][j] += F::dot(wv, a[j]);
1489        }
1490    }
1491    auto sg = item.get_sub_group();
1492#pragma unroll
1493    for (int r = 0; r < RPW; ++r)
1494#pragma unroll
1495        for (int j = 0; j < NCOLS; ++j) {
1496            float v = tmp[r][j];
1497#pragma unroll
1498            for (int o = WARP / 2; o > 0; o >>= 1) v += dpct::experimental::permute_sub_group_by_xor(0xffffffffu, sg, v, o);
1499            if (lane == 0 && row0 + r < n_out) y[std::size_t(j) * n_out + row0 + r] = v;
1500        }
1501}
1502
1503// ---------------------------------------------------------------- SYCL port: Q6_K with 16-byte loads
1504//
1505// bw probe on the B70: 4-byte loads per lane stream at 395 GB/s, 16-byte at 596; the shared kernel above does
1506// 4-byte loads and measures 130-140 GB/s on the 8192-wide Q6_K projections. Here 8 lanes share a 256-block:
1507// lane g takes positions iqs = 4g..4g+3, so its ql (16 B), qh (16 B) and each column's q8 ints (16 B) are one
1508// vector load each; a 32-lane sub-group has four blocks in flight. One row per warp, WARPS rows per group.
1509// SYCL port: a 16-byte load from a 2-byte aligned address as two aligned 16-byte loads and a shift. A Q6_K block
1510// is 210 bytes, so its ql/qh runs start 2-byte aligned, and the B70 splits a misaligned vector load into pieces:
1511// the wide kernel streamed 145 GB/s that way against 640 GB/s for the same blocks repacked at a 16-byte stride.
1512// Both aligned loads stay inside the 210-byte block for the ql and qh runs (last byte read <= block + 207).
1513// SYCL port: a 4-int vector load from a 4-byte aligned address (a Q8_1 block is 36 bytes, its qs sit at offset 4): one dword-vector
1514// message instead of four scalar loads - the decode kernels issue 8 of these per column and 4-byte step.
1515__dpct_inline__ sycl::int4 ld_i4_a4(const int* p) {
1516    sycl::int4 v;
1517    v.load(0, sycl::address_space_cast<sycl::access::address_space::global_space, sycl::access::decorated::no>(p));
1518    return v;
1519}
1520// Q6_K: per-byte (v - 32) of four 6-bit values (bytes 0..63): no byte can saturate, so this is the saturating char4 subtract's
1521// result exactly, in four integer ops (SWAR: no borrow crosses a byte) instead of the per-byte vector builtin.
1522__dpct_inline__ int q6_sub32(int x) {
1523    const uint32_t u = (uint32_t) x;
1524    return (int) (((u | 0x80808080u) - 0x20202020u) ^ (~u & 0x80808080u));
1525}
1526__dpct_inline__ sycl::int4 load16_a2(const void* p) {
1527    const uintptr_t a = reinterpret_cast<uintptr_t>(p);
1528    const sycl::int4* q = reinterpret_cast<const sycl::int4*>(a & ~uintptr_t(15));
1529    const int k = int(a >> 2) & 3;          // dword offset within the first aligned chunk
1530    const bool half = (a & 2) != 0;          // and a 2-byte shift (the address is always 2-byte aligned)
1531    // the second chunk only when the address is unaligned: then it holds needed bytes, so (16-byte chunks never
1532    // straddle a page) it cannot fault even at the very end of an allocation
1533    const sycl::int4 lo = q[0], hi = (a & 15) ? q[1] : lo;
1534    const uint32_t d[8] = {(uint32_t) lo.x(), (uint32_t) lo.y(), (uint32_t) lo.z(), (uint32_t) lo.w(),
1535                           (uint32_t) hi.x(), (uint32_t) hi.y(), (uint32_t) hi.z(), (uint32_t) hi.w()};
1536    uint32_t w[5];
1537#pragma unroll
1538    for (int i = 0; i < 5; ++i)              // w = d[k .. k+4] by selects (no indexed register access)
1539        w[i] = k == 0 ? d[i] : k == 1 ? d[i + 1] : k == 2 ? d[i + 2] : d[(i + 3) & 7];
1540    uint32_t o[4];
1541#pragma unroll
1542    for (int i = 0; i < 4; ++i) o[i] = half ? (w[i] >> 16) | (w[i + 1] << 16) : w[i];
1543    return sycl::int4((int) o[0], (int) o[1], (int) o[2], (int) o[3]);
1544}
1545inline bool q6k_a2() {   // STRATA_MMVQ_A2=0 turns the aligned-load path off
1546    static const bool v = std::getenv("STRATA_MMVQ_A2") == nullptr || std::atoi(std::getenv("STRATA_MMVQ_A2")) != 0;
1547    return v;
1548}
1549
1550template <int NCOLS, int RPW, int SG = WARP, int BS = (int) sizeof(Q6KBlock), bool A2 = false>   // BS: block stride
1551void native_mmvq_q6k_wide_kernel(const Q6KBlock* __restrict__ w, const Q81Block* __restrict__ x,
1552                                 float* __restrict__ y, int n_in, int n_out) {
1553    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1554    const int lane = int(item.get_local_id(2)), warp = int(item.get_local_id(1));
1555    constexpr int NWG = WARPS * WARP / SG;              // sub-groups per work-group
1556    const int row0 = (int(item.get_group(2)) * NWG + warp) * RPW;
1557    if (row0 >= n_out) return;
1558    const int blocks_per_row = n_in / QK, x_stride = n_in / Q8K;
1559    const int g = lane & 7, sub = lane >> 3;            // position group within the block, block within the iteration
1560    const int vh_shift = 2 * ((g & 3) >> 1);
1561    const int qh4_idx = 2 * (g >> 2) + (g & 1);
1562    const int scale_offset = 8 * (g >> 2) + (g & 3);
1563    const int bq8_offset = 4 * (g >> 2) + ((g & 3) >> 1);
1564    const int u_int4 = g & 1;                           // ints 4(g%2)..+3 of the q8 block = one int4
1565    float acc[RPW][NCOLS] = {};
1566    for (int kbx = sub; kbx < blocks_per_row; kbx += SG / 8) {
1567        const int kby = kbx * (QK / Q8K);
1568        sycl::int4 ql4[RPW], qh4[RPW]; float dsc0[RPW], dsc1[RPW];
1569#pragma unroll
1570        for (int r = 0; r < RPW; ++r) {
1571            const Q6KBlock* b = reinterpret_cast<const Q6KBlock*>(reinterpret_cast<const uint8_t*>(w) +
1572                (std::size_t(row0 + (row0 + r < n_out ? r : 0)) * blocks_per_row + kbx) * BS);
1573            if constexpr (A2) {
1574                ql4[r] = load16_a2(b->ql + 16 * g);
1575                qh4[r] = load16_a2(b->qh + 16 * qh4_idx);
1576            } else {
1577                ql4[r] = reinterpret_cast<const sycl::int4*>(b->ql)[g];
1578                qh4[r] = reinterpret_cast<const sycl::int4*>(b->qh)[qh4_idx];
1579            }
1580            const float d = b->d;
1581            dsc0[r] = d * (float) b->scales[scale_offset]; dsc1[r] = d * (float) b->scales[scale_offset + 4];
1582        }
1583        // the activations once per column, shared by the RPW rows
1584        sycl::int4 u0[NCOLS], u1[NCOLS];
1585        float ds0[NCOLS], ds1[NCOLS];
1586#pragma unroll
1587        for (int j = 0; j < NCOLS; ++j) {
1588            const Q81Block* xb = x + std::size_t(j) * x_stride + kby + bq8_offset;
1589            if constexpr (A2) {   // Q8_1 qs sits at offset 4 of a 36-byte block: 4-byte aligned, so four int loads
1590                u0[j] = ld_i4_a4(reinterpret_cast<const int*>(xb[0].qs) + 4 * u_int4);
1591                u1[j] = ld_i4_a4(reinterpret_cast<const int*>(xb[2].qs) + 4 * u_int4);
1592            } else {
1593                u0[j] = reinterpret_cast<const sycl::int4*>(xb[0].qs)[u_int4];
1594                u1[j] = reinterpret_cast<const sycl::int4*>(xb[2].qs)[u_int4];
1595            }
1596            ds0[j] = xb[0].ds[0]; ds1[j] = xb[2].ds[0];
1597        }
1598#pragma unroll
1599        for (int r = 0; r < RPW; ++r) {
1600            const int vl[4] = {ql4[r].x(), ql4[r].y(), ql4[r].z(), ql4[r].w()};
1601            const int vh[4] = {qh4[r].x() >> vh_shift, qh4[r].y() >> vh_shift, qh4[r].z() >> vh_shift, qh4[r].w() >> vh_shift};
1602            int vi0[4], vi1[4];
1603#pragma unroll
1604            for (int p = 0; p < 4; ++p) {
1605                vi0[p] = q6_sub32((vl[p] & 0x0f0f0f0f) | ((vh[p] << 4) & 0x30303030));
1606                vi1[p] = q6_sub32(((vl[p] >> 4) & 0x0f0f0f0f) | (((vh[p] >> 4) << 4) & 0x30303030));
1607            }
1608#pragma unroll
1609            for (int j = 0; j < NCOLS; ++j) {
1610                int s0 = 0, s1 = 0;
1611                s0 = strata::dp4a(vi0[0], u0[j].x(), s0); s0 = strata::dp4a(vi0[1], u0[j].y(), s0);
1612                s0 = strata::dp4a(vi0[2], u0[j].z(), s0); s0 = strata::dp4a(vi0[3], u0[j].w(), s0);
1613                s1 = strata::dp4a(vi1[0], u1[j].x(), s1); s1 = strata::dp4a(vi1[1], u1[j].y(), s1);
1614                s1 = strata::dp4a(vi1[2], u1[j].z(), s1); s1 = strata::dp4a(vi1[3], u1[j].w(), s1);
1615                acc[r][j] += ds0[j] * dsc0[r] * (float) s0 + ds1[j] * dsc1[r] * (float) s1;
1616            }
1617        }
1618    }
1619    auto sg = item.get_sub_group();
1620#pragma unroll
1621    for (int r = 0; r < RPW; ++r)
1622#pragma unroll
1623        for (int j = 0; j < NCOLS; ++j) {
1624            float v = acc[r][j];
1625#pragma unroll
1626            for (int o = SG / 2; o > 0; o >>= 1) v += sycl::permute_group_by_xor(sg, v, o);
1627            if (lane == 0 && row0 + r < n_out) y[std::size_t(j) * n_out + row0 + r] = v;
1628        }
1629}
1630// (STRATA_MMVQ_PF, a prefetching wide Q6_K kernel, and STRATA_MMVQ_SG, SIMD16 sub-group variants of the decode mmvq, were removed in 0.2.13: no gain in the engine.)
1631inline int q6k_wide_rpw() {
1632    static const int v = std::getenv("STRATA_MMVQ_WIDE_RPW") ? std::atoi(std::getenv("STRATA_MMVQ_WIDE_RPW")) : 1;
1633    return v;
1634}
1635// Large-GRF mode (256 registers per thread instead of 128) for the wide kernels (Q6_K a2 and the generic one) at 2-8
1636// columns: on the A770 they spill at 128, and mmvq_bench Q6_K 4 columns goes 70-80 -> 150-237 GB/s with the same
1637// checksum. Large GRF halves the threads an Xe core keeps resident, so it is the default on Arc A-series (Alchemist)
1638// only, where it was measured; Battlemage and anything else, and 1 column everywhere, launch the same kernels as before.
1639// STRATA_MMVQ_LARGE_GRF=1 forces it on, =0 off.
1640inline bool mmvq_large_grf(dpct::queue_ptr s) {
1641    static const bool v = [s] {
1642        const char* e = std::getenv("STRATA_MMVQ_LARGE_GRF");
1643        if (e != nullptr) return std::atoi(e) != 0;
1644        return strata::intel_gpu_gen(s->get_device()) == strata::IntelGpuGen::Alchemist;
1645    }();
1646    return v;
1647}
1648template <int NCOLS>
1649void launch_q6k_wide(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, dpct::queue_ptr s) {
1650    const auto* w = static_cast<const Q6KBlock*>(weights);
1651    const auto* x = static_cast<const Q81Block*>(x_q8_1);
1652    const int rpw = q6k_wide_rpw();
1653    if (rpw == 1 && q6k_a2()) {
1654        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
1655        if constexpr (NCOLS > 1) {
1656            static const bool shape_grf = strata::bm_default_on("STRATA_Q6_SHAPE_GRF", s->get_device(), false);
1657            const bool eligible = (n_in == 6144 && n_out == 2560) ||
1658                (n_in == 2560 && (n_out == 512 || n_out == 640)) ||
1659                (NCOLS >= 3 && n_in == 2560 && n_out == 6144) ||
1660                (NCOLS >= 4 && n_in == 2560 && (n_out == 10240 || n_out == 12288));
1661            const bool bounded_grf = shape_grf && eligible &&
1662                std::getenv("STRATA_MMVQ_LARGE_GRF") == nullptr &&
1663                strata::intel_gpu_gen(s->get_device()) == strata::IntelGpuGen::Battlemage;
1664            if (bounded_grf) {
1665                static const bool note = [] {
1666                    std::fprintf(stderr, "strata: shape-guarded Q6_K large-GRF dispatch enabled\n");
1667                    return true;
1668                }();
1669                (void) note;
1670            }
1671            if (mmvq_large_grf(s) || bounded_grf) {
1672                strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_q6k_wide_a2_grf256, dpct_kernel_scalar<NCOLS>>>(
1673                    sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
1674                    sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>},
1675                    [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
1676                        native_mmvq_q6k_wide_kernel<NCOLS, 1, WARP, (int) sizeof(Q6KBlock), true>(w, x, y, n_in, n_out);
1677                    });
1678                return;
1679            }
1680        }
1681        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_q6k_wide_a2, dpct_kernel_scalar<NCOLS>>>(
1682            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
1683            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
1684                native_mmvq_q6k_wide_kernel<NCOLS, 1, WARP, (int) sizeof(Q6KBlock), true>(w, x, y, n_in, n_out);
1685            });
1686        return;
1687    }
1688    // RP rows per sub-group share each column's activation loads (the rows' own lanes, k order and butterfly: every
1689    // output the same bits); with the aligned loads (A2) unless STRATA_MMVQ_A2=0
1690#define STRATA_Q6W(RP) if (rpw == RP) { \
1691        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS * RP - 1) / (WARPS * RP)); \
1692        if (q6k_a2()) { \
1693            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_q6k_wide_a2r, dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<RP>>>( \
1694                sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)), \
1695                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { \
1696                    native_mmvq_q6k_wide_kernel<NCOLS, RP, WARP, (int) sizeof(Q6KBlock), true>(w, x, y, n_in, n_out); }); \
1697            return; } \
1698        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_q6k_wide, dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<RP>>>( \
1699            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)), \
1700            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_q6k_wide_kernel<NCOLS, RP>(w, x, y, n_in, n_out); }); \
1701        return; }
1702    STRATA_Q6W(1) STRATA_Q6W(2) STRATA_Q6W(4)
1703#undef STRATA_Q6W
1704    const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
1705    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_q6k_wide1, dpct_kernel_scalar<NCOLS>>>(
1706        sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
1707        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_q6k_wide_kernel<NCOLS, 1>(w, x, y, n_in, n_out); });
1708}
1709// ---------------------------------------------------------------- SYCL port: wide kernels for Q4_K, Q5_K, IQ4_XS
1710//
1711// The Q6_K wide kernel's shape for the other 256-element formats: 8 lanes share a block, each lane's weights are one
1712// or two 16-byte loads, a 32-lane sub-group has four blocks in flight, one row per sub-group. The multi kernel these
1713// replace does 4-byte loads (Q4_K/Q5_K, 230-280 GB/s) or global-memory codebook lookups (IQ4_XS, ~100 GB/s).
1714// Lane g of a block: Q4_K/Q5_K take qs bytes [16g, 16g+16) = sub-blocks 2(g/2) (low nibbles) and 2(g/2)+1 (high
1715// nibbles) at positions 16(g%2)..+15; IQ4_XS takes sub-block g (16 bytes, low nibbles = positions 0-15).
1716__dpct_inline__ sycl::int4 ld_q8_16(const Q81Block* b, int half) {   // Q8_1 qs is 4-byte aligned: one dword-vector load
1717    return ld_i4_a4(reinterpret_cast<const int*>(b->qs) + 4 * half);
1718}
1719__dpct_inline__ int dp4a4(const sycl::int4 a, const sycl::int4 b, int acc) {
1720    acc = strata::dp4a(a.x(), b.x(), acc); acc = strata::dp4a(a.y(), b.y(), acc);
1721    acc = strata::dp4a(a.z(), b.z(), acc); return strata::dp4a(a.w(), b.w(), acc);
1722}
1723__dpct_inline__ void k4_scale_min(const uint8_t* sc, int j, float& s, float& m) {   // ggml get_scale_min_k4
1724    if (j < 4) { s = (float) (sc[j] & 63); m = (float) (sc[j + 4] & 63); }
1725    else { s = (float) ((sc[j + 4] & 0xF) | ((sc[j - 4] >> 6) << 4)); m = (float) ((sc[j + 4] >> 4) | ((sc[j] >> 6) << 4)); }
1726}
1727struct WideQ4K {
1728    using Block = Q4KBlock;
1729    struct W { sycl::int4 lo, hi; float dl, dh, ml, mh; int sb, half; };
1730    static W load(const Block* b, int g) {
1731        W r; r.sb = 2 * (g >> 1); r.half = g & 1;
1732        const sycl::int4 q = reinterpret_cast<const sycl::int4*>(b->qs)[g];          // 16-byte aligned (144 = 9 x 16)
1733        r.lo = sycl::int4(q.x() & 0x0f0f0f0f, q.y() & 0x0f0f0f0f, q.z() & 0x0f0f0f0f, q.w() & 0x0f0f0f0f);
1734        r.hi = sycl::int4((q.x() >> 4) & 0x0f0f0f0f, (q.y() >> 4) & 0x0f0f0f0f, (q.z() >> 4) & 0x0f0f0f0f, (q.w() >> 4) & 0x0f0f0f0f);
1735        const sycl::float2 dm = b->dm.convert<float, sycl::rounding_mode::automatic>();
1736        float s0, m0, s1, m1; k4_scale_min(b->scales, r.sb, s0, m0); k4_scale_min(b->scales, r.sb + 1, s1, m1);
1737        r.dl = dm.x() * s0; r.ml = dm.y() * m0; r.dh = dm.x() * s1; r.mh = dm.y() * m1;
1738        return r;
1739    }
1740    static float apply(const W& r, const Q81Block* xb) {   // xb = this column's Q8_1 blocks of the 256-block
1741        const Q81Block* a = xb + r.sb; const Q81Block* c = xb + r.sb + 1;
1742        const sycl::int4 ua = ld_q8_16(a, r.half), uc = ld_q8_16(c, r.half);
1743        const sycl::int4 ones(0x01010101, 0x01010101, 0x01010101, 0x01010101);
1744        const float da = (float) a->ds[0], dc = (float) c->ds[0];
1745        return da * (r.dl * (float) dp4a4(r.lo, ua, 0) - r.ml * (float) dp4a4(ones, ua, 0)) +
1746               dc * (r.dh * (float) dp4a4(r.hi, uc, 0) - r.mh * (float) dp4a4(ones, uc, 0));
1747    }
1748    // apply() in two parts for several rows of one sub-group: the activations depend on the lane alone (sb, half from g)
1749    struct A { sycl::int4 ua, uc; float da, dc; };
1750    static A act(const Q81Block* xb, int g) {
1751        const int sb = 2 * (g >> 1), half = g & 1;
1752        const Q81Block* a = xb + sb; const Q81Block* c = xb + sb + 1;
1753        A v; v.ua = ld_q8_16(a, half); v.uc = ld_q8_16(c, half); v.da = (float) a->ds[0]; v.dc = (float) c->ds[0];
1754        return v;
1755    }
1756    static float dot(const W& r, const A& v) {   // apply's expression, the same operations in the same order
1757        const sycl::int4 ones(0x01010101, 0x01010101, 0x01010101, 0x01010101);
1758        return v.da * (r.dl * (float) dp4a4(r.lo, v.ua, 0) - r.ml * (float) dp4a4(ones, v.ua, 0)) +
1759               v.dc * (r.dh * (float) dp4a4(r.hi, v.uc, 0) - r.mh * (float) dp4a4(ones, v.uc, 0));
1760    }
1761};
1762struct WideQ5K {
1763    using Block = Q5KBlock;
1764    using W = WideQ4K::W;
1765    static W load(const Block* b, int g) {
1766        W r; r.sb = 2 * (g >> 1); r.half = g & 1;
1767        const sycl::int4 q = reinterpret_cast<const sycl::int4*>(b->qs)[g];          // qs at 48, 176 = 11 x 16
1768        const sycl::int4 h = reinterpret_cast<const sycl::int4*>(b->qh)[r.half];     // qh bytes of positions 16h..+15
1769        const int sl = r.sb, sh = r.sb + 1;
1770        auto hb = [](int v, int bit) { return ((v >> bit) & 0x01010101) << 4; };
1771        r.lo = sycl::int4((q.x() & 0x0f0f0f0f) | hb(h.x(), sl), (q.y() & 0x0f0f0f0f) | hb(h.y(), sl),
1772                          (q.z() & 0x0f0f0f0f) | hb(h.z(), sl), (q.w() & 0x0f0f0f0f) | hb(h.w(), sl));
1773        r.hi = sycl::int4(((q.x() >> 4) & 0x0f0f0f0f) | hb(h.x(), sh), ((q.y() >> 4) & 0x0f0f0f0f) | hb(h.y(), sh),
1774                          ((q.z() >> 4) & 0x0f0f0f0f) | hb(h.z(), sh), ((q.w() >> 4) & 0x0f0f0f0f) | hb(h.w(), sh));
1775        const sycl::float2 dm = b->dm.convert<float, sycl::rounding_mode::automatic>();
1776        float s0, m0, s1, m1; k4_scale_min(b->scales, r.sb, s0, m0); k4_scale_min(b->scales, r.sb + 1, s1, m1);
1777        r.dl = dm.x() * s0; r.ml = dm.y() * m0; r.dh = dm.x() * s1; r.mh = dm.y() * m1;
1778        return r;
1779    }
1780    static float apply(const W& r, const Q81Block* xb) { return WideQ4K::apply(r, xb); }
1781    using A = WideQ4K::A;
1782    static A act(const Q81Block* xb, int g) { return WideQ4K::act(xb, g); }
1783    static float dot(const W& r, const A& v) { return WideQ4K::dot(r, v); }
1784};
1785#ifndef STRATA_IQ4_LUT_SWAR
1786#define STRATA_IQ4_LUT_SWAR 0
1787#endif
1788__dpct_inline__ uint32_t iq4_lut4(uint32_t q4) {   // four nibbles -> four codebook bytes, codebook in registers
1789#if STRATA_IQ4_LUT_SWAR
1790    return iq4_lut4_swar(q4);
1791#else
1792    constexpr uint32_t t0 = 0xBFAD9881u, t1 = 0xF6EADDCFu, t2 = 0x26190D01u, t3 = 0x71594535u;
1793    uint32_t r = 0;
1794#pragma unroll
1795    for (int i = 0; i < 4; ++i) {
1796        const uint32_t n = (q4 >> (8 * i)) & 0xF;
1797        const uint32_t t = n < 4 ? t0 : n < 8 ? t1 : n < 12 ? t2 : t3;
1798        r |= ((t >> (8 * (n & 3))) & 0xFF) << (8 * i);
1799    }
1800    return r;
1801#endif
1802}
1803struct WideIQ4XS {
1804    using Block = IQ4XSBlock;
1805    struct W { sycl::int4 lo, hi; float d; int sb; };
1806    static W load(const Block* b, int g) {
1807        W r; r.sb = g;
1808        const sycl::int2* q2 = reinterpret_cast<const sycl::int2*>(b->qs + 16 * g);   // 8-byte aligned (136 = 17 x 8)
1809        const sycl::int2 qa = q2[0], qb = q2[1];
1810        const uint32_t v[4] = {(uint32_t) qa.x(), (uint32_t) qa.y(), (uint32_t) qb.x(), (uint32_t) qb.y()};
1811        int lo[4], hi[4];
1812#pragma unroll
1813        for (int i = 0; i < 4; ++i) { lo[i] = (int) iq4_lut4(v[i] & 0x0f0f0f0f); hi[i] = (int) iq4_lut4((v[i] >> 4) & 0x0f0f0f0f); }
1814        r.lo = sycl::int4(lo[0], lo[1], lo[2], lo[3]); r.hi = sycl::int4(hi[0], hi[1], hi[2], hi[3]);
1815        const int ls = ((b->scales_l[g / 2] >> (4 * (g & 1))) & 0x0f) | (((b->scales_h >> (2 * g)) & 0x03) << 4);
1816        r.d = (float) b->d * (float) (ls - 32);
1817        return r;
1818    }
1819    static float apply(const W& r, const Q81Block* xb) {
1820        const Q81Block* a = xb + r.sb;
1821        return r.d * (float) a->ds[0] * (float) dp4a4(r.hi, ld_q8_16(a, 1), dp4a4(r.lo, ld_q8_16(a, 0), 0));
1822    }
1823    struct A { sycl::int4 u0, u1; float ds; };
1824    static A act(const Q81Block* xb, int g) {
1825        const Q81Block* a = xb + g;
1826        A v; v.u0 = ld_q8_16(a, 0); v.u1 = ld_q8_16(a, 1); v.ds = (float) a->ds[0];
1827        return v;
1828    }
1829    static float dot(const W& r, const A& v) { return r.d * v.ds * (float) dp4a4(r.hi, v.u1, dp4a4(r.lo, v.u0, 0)); }
1830};
1831template<bool NoCodebook, bool AddXorMask = false> struct WideIQ4LookupProbe : WideIQ4XS {
1832    static W load(const Block* b, int g) {
1833        W r; r.sb = g;
1834        const auto* q2 = reinterpret_cast<const sycl::int2*>(b->qs + 16 * g);
1835        const sycl::int2 qa = q2[0], qb = q2[1];
1836        const uint32_t v[4] = {(uint32_t)qa.x(), (uint32_t)qa.y(), (uint32_t)qb.x(), (uint32_t)qb.y()};
1837        int lo[4], hi[4];
1838#pragma unroll
1839        for (int i = 0; i < 4; ++i) {
1840            const uint32_t lower = v[i] & 0x0f0f0f0f, upper = (v[i] >> 4) & 0x0f0f0f0f;
1841            if constexpr (NoCodebook) { lo[i] = (int)lower; hi[i] = (int)upper; }
1842            else { lo[i] = (int)iq4_decode::bit_select_impl<AddXorMask>(lower); hi[i] = (int)iq4_decode::bit_select_impl<AddXorMask>(upper); }
1843        }
1844        r.lo = {lo[0], lo[1], lo[2], lo[3]}; r.hi = {hi[0], hi[1], hi[2], hi[3]};
1845        const int ls = ((b->scales_l[g / 2] >> (4 * (g & 1))) & 15) | (((b->scales_h >> (2 * g)) & 3) << 4);
1846        r.d = (float)b->d * (float)(ls - 32);
1847        return r;
1848    }
1849    // apply is inherited verbatim, retaining the original float expression.
1850};
1851struct WideIQ4GroupLookup : WideIQ4XS {
1852    __dpct_inline__ static uint32_t lookup(uint32_t word, uint32_t lane_value) {
1853        const auto sg = sycl::ext::oneapi::this_work_item::get_sub_group();
1854        uint32_t result = 0;
1855#pragma unroll
1856        for (int b = 0; b < 4; ++b) {
1857            const uint32_t index = (word >> (8 * b)) & 15;
1858            result |= sycl::select_from_group(sg, lane_value, index) << (8 * b);
1859        }
1860        return result;
1861    }
1862    static W load(const Block* b, int g, uint32_t lane_value) {
1863        W r; r.sb = g;
1864        const auto* q = reinterpret_cast<const sycl::int2*>(b->qs + 16 * g);
1865        const auto a = q[0], c = q[1];
1866        const uint32_t v[] = {(uint32_t)a.x(), (uint32_t)a.y(), (uint32_t)c.x(), (uint32_t)c.y()};
1867        int lo[4], hi[4];
1868#pragma unroll
1869        for (int i = 0; i < 4; ++i) {
1870            lo[i] = (int)lookup(v[i] & 0x0f0f0f0f, lane_value);
1871            hi[i] = (int)lookup((v[i] >> 4) & 0x0f0f0f0f, lane_value);
1872        }
1873        r.lo = {lo[0],lo[1],lo[2],lo[3]}; r.hi = {hi[0],hi[1],hi[2],hi[3]};
1874        const int ls = ((b->scales_l[g / 2] >> (4 * (g & 1))) & 15) | (((b->scales_h >> (2 * g)) & 3) << 4);
1875        r.d = (float)b->d * (float)(ls - 32); return r;
1876    }
1877};
1878using WideIQ4Lookup = WideIQ4LookupProbe<false>;
1879// SYCL port: native_mmvq_wide_kernel with RPW rows per sub-group (STRATA_MMVQ_WIDE_K_RPW): each column's activations
1880// are loaded once (act) and used by the RPW rows (dot); a row's lanes, its k order and its butterfly are the
1881// one-row kernel's, so every output is the same bits. At 2-4 columns the one-row kernel reads ~5x its weight bytes
1882// in activations (each row re-reads the whole vector per column).
1883template <typename F, int NCOLS, int RPW>
1884void native_mmvq_wide_rpw_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
1885                                 float* __restrict__ y, int n_in, int n_out) {
1886    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1887    const int lane = int(item.get_local_id(2)), warp = int(item.get_local_id(1));
1888    const int row0 = (int(item.get_group(2)) * WARPS + warp) * RPW;
1889    if (row0 >= n_out) return;
1890    const int blocks_per_row = n_in / QK, x_stride = n_in / Q8K;
1891    const int g = lane & 7, sub = lane >> 3;
1892    const typename F::Block* wr[RPW];
1893#pragma unroll
1894    for (int r = 0; r < RPW; ++r) wr[r] = w + std::size_t(row0 + (row0 + r < n_out ? r : 0)) * blocks_per_row;
1895    float acc[RPW][NCOLS] = {};
1896    for (int kbx = sub; kbx < blocks_per_row; kbx += 4) {
1897        typename F::W wv[RPW];
1898#pragma unroll
1899        for (int r = 0; r < RPW; ++r) wv[r] = F::load(wr[r] + kbx, g);
1900#pragma unroll
1901        for (int j = 0; j < NCOLS; ++j) {
1902            const typename F::A a = F::act(x + std::size_t(j) * x_stride + kbx * (QK / Q8K), g);
1903#pragma unroll
1904            for (int r = 0; r < RPW; ++r) acc[r][j] += F::dot(wv[r], a);
1905        }
1906    }
1907    auto sg = item.get_sub_group();
1908#pragma unroll
1909    for (int r = 0; r < RPW; ++r)
1910#pragma unroll
1911        for (int j = 0; j < NCOLS; ++j) {
1912            float v = acc[r][j];
1913#pragma unroll
1914            for (int o = WARP / 2; o > 0; o >>= 1) v += sycl::permute_group_by_xor(sg, v, o);
1915            if (lane == 0 && row0 + r < n_out) y[std::size_t(j) * n_out + row0 + r] = v;
1916        }
1917}
1918inline int wide_k_rpw() {   // STRATA_MMVQ_WIDE_K_RPW: rows per sub-group of the Q4_K / Q5_K / IQ4_XS wide kernel (1, 2, 4)
1919    static const int v = std::getenv("STRATA_MMVQ_WIDE_K_RPW") ? std::atoi(std::getenv("STRATA_MMVQ_WIDE_K_RPW")) : 1;
1920    return v;
1921}
1922template <typename F, int NCOLS>
1923void native_mmvq_wide_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
1924                             float* __restrict__ y, int n_in, int n_out) {
1925    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
1926    const int lane = int(item.get_local_id(2)), warp = int(item.get_local_id(1));
1927    const int row = int(item.get_group(2)) * WARPS + warp;
1928    if (row >= n_out) return;
1929    const int blocks_per_row = n_in / QK, x_stride = n_in / Q8K;
1930    const int g = lane & 7, sub = lane >> 3;
1931    const typename F::Block* wr = w + std::size_t(row) * blocks_per_row;
1932    float acc[NCOLS] = {};
1933    if constexpr (std::is_same_v<F, WideIQ4GroupLookup>) {
1934        const uint32_t lane_value = iq4_lut4((uint32_t)(lane & 15)) & 255;
1935        // All subgroup members execute every integer shuffle, including the
1936        // incomplete final group. Invalid virtual lanes skip the FP update.
1937        for (int k0 = 0; k0 < blocks_per_row; k0 += 4) {
1938            const int kbx = k0 + sub;
1939            const typename F::W wv = F::load(wr + (kbx < blocks_per_row ? kbx : 0), g, lane_value);
1940            if (kbx < blocks_per_row) {
1941#pragma unroll
1942                for (int j = 0; j < NCOLS; ++j) acc[j] += F::apply(wv, x + std::size_t(j) * x_stride + kbx * (QK / Q8K));
1943            }
1944        }
1945    } else {
1946        for (int kbx = sub; kbx < blocks_per_row; kbx += 4) {
1947            const typename F::W wv = F::load(wr + kbx, g);
1948#pragma unroll
1949            for (int j = 0; j < NCOLS; ++j) acc[j] += F::apply(wv, x + std::size_t(j) * x_stride + kbx * (QK / Q8K));
1950        }
1951    }
1952    auto sg = item.get_sub_group();
1953#pragma unroll
1954    for (int j = 0; j < NCOLS; ++j) {
1955        float v = acc[j];
1956#pragma unroll
1957        for (int o = WARP / 2; o > 0; o >>= 1) v += sycl::permute_group_by_xor(sg, v, o);
1958        if (lane == 0) y[std::size_t(j) * n_out + row] = v;
1959    }
1960}
1961template <typename F, int NCOLS>
1962void launch_wide(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, dpct::queue_ptr s) {
1963    const auto* w = static_cast<const typename F::Block*>(weights);
1964    const auto* x = static_cast<const Q81Block*>(x_q8_1);
1965    int rpw = wide_k_rpw();
1966    static const bool shape_reuse = strata::bm_default_on("STRATA_MMVQ_SHAPE_RPW", s->get_device());
1967    if (shape_reuse && std::getenv("STRATA_MMVQ_WIDE_K_RPW") == nullptr &&
1968        strata::intel_gpu_gen(s->get_device()) == strata::IntelGpuGen::Battlemage) {
1969        bool eligible = false;
1970        if constexpr (std::is_same_v<F, WideQ4K>)
1971            eligible = (n_in == 2560 && (n_out == 6144 || n_out == 10240 || n_out == 12288)) ||
1972                       (n_in == 6144 && n_out == 2560);
1973        if constexpr (std::is_same_v<F, WideQ5K>)
1974            eligible = (n_in == 2560 && n_out == 12288) || (n_in == 6144 && n_out == 2560);
1975        if (eligible && NCOLS <= 4) {
1976            rpw = 2;
1977            static const bool note = [] {
1978                std::fprintf(stderr, "strata: shape-guarded Q4_K/Q5_K dense row reuse enabled\n");
1979                return true;
1980            }();
1981            (void) note;
1982        }
1983    }
1984#define STRATA_WKR(RP) if (rpw == RP) { \
1985        const unsigned b = unsigned((std::size_t(n_out) + WARPS * RP - 1) / (WARPS * RP)); \
1986        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_wide_rpw, F, dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<RP>>>( \
1987            sycl::nd_range<3>(sycl::range(1, 1, b) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)), \
1988            [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_wide_rpw_kernel<F, NCOLS, RP>(w, x, y, n_in, n_out); }); \
1989        return; }
1990    STRATA_WKR(2) STRATA_WKR(4)
1991#undef STRATA_WKR
1992    const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
1993    if constexpr (NCOLS > 1) {
1994        if (mmvq_large_grf(s)) {
1995            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_wide_grf256, F, dpct_kernel_scalar<NCOLS>>>(
1996                sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
1997                sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>},
1998                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_wide_kernel<F, NCOLS>(w, x, y, n_in, n_out); });
1999            return;
2000        }
2001    }
2002    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_wide, F, dpct_kernel_scalar<NCOLS>>>(
2003        sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
2004        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_wide_kernel<F, NCOLS>(w, x, y, n_in, n_out); });
2005}
2006namespace iq4jm=sycl::ext::oneapi::experimental::matrix;
2007inline float iq4_xmx_float_finish(const WideIQ4XS::W& pw,const Q81Block* activation,int sumi){
2008    return pw.d*(float)activation->ds[0]*(float)sumi;
2009}
2010template<int NT,int KB>class IQ4XmxVirtualKernel;
2011template<int NT,int KB>
2012void iq4_xmx_virtual_launch(const uint8_t* w,const Q81Block* x,float* y,int N,sycl::queue* q){
2013    using F=WideIQ4LookupProbe<false>;constexpr int NR=16,NS=16,XB=KB*8,RB=KB*sizeof(F::Block);
2014    q->parallel_for<IQ4XmxVirtualKernel<NT,KB>>(sycl::nd_range<1>((N+NR-1)/NR*256,256),
2015      [=](sycl::nd_item<1> it)[[sycl::reqd_sub_group_size(16)]]{
2016        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;
2017        auto& partial=*sycl::ext::oneapi::group_local_memory_for_overwrite<float[32*NT*NR]>(group);
2018        for(int virtual_id=sid;virtual_id<32;virtual_id+=NS){
2019        float acc[NT]={};
2020        for(int seg=virtual_id;seg<XB;seg+=32){
2021            F::W pw{};if(row<N)pw=F::load(reinterpret_cast<const F::Block*>(w+uint32_t(row)*uint32_t(RB))+seg/8,seg%8);
2022            iq4jm::joint_matrix<sycl::sub_group,int8_t,iq4jm::use::a,NT,32,iq4jm::layout::row_major> A;
2023            iq4jm::joint_matrix<sycl::sub_group,int8_t,iq4jm::use::b,32,NR,iq4jm::layout::ext_intel_packed> B;
2024            iq4jm::joint_matrix<sycl::sub_group,int32_t,iq4jm::use::accumulator,NT,NR> C;
2025
2026                auto pa=sycl::address_space_cast<sycl::access::address_space::global_space,sycl::access::decorated::no>(x[seg].qs);
2027                iq4jm::joint_matrix_load(sg,A,pa,XB*sizeof(Q81Block));
2028                iq4jm::joint_matrix_fill(sg,B,0);
2029
2030                    int kr=0;
2031                    iq4jm::joint_matrix_apply(sg,B,[&](auto& element){
2032                        const int word=kr<4?pw.lo[0]:kr<8?pw.lo[1]:kr<12?pw.lo[2]:kr<16?pw.lo[3]:kr<20?pw.hi[0]:kr<24?pw.hi[1]:kr<28?pw.hi[2]:pw.hi[3];
2033                        element=int8_t(uint32_t(word)>>(8*(kr%4)));++kr;
2034                    });
2035
2036
2037            iq4jm::joint_matrix_fill(sg,C,0);iq4jm::joint_matrix_mad(sg,C,A,B,C);
2038
2039                int mr=0;
2040                iq4jm::joint_matrix_apply(sg,C,[&](auto& element){
2041                    acc[mr]+=iq4_xmx_float_finish(pw,x+mr*XB+seg,int(element));++mr;
2042                });
2043
2044
2045        }
2046#pragma unroll
2047        for(int j=0;j<NT;++j)partial[virtual_id*NT*NR+j*NR+lane]=acc[j];
2048        }
2049        it.barrier(sycl::access::fence_space::local_space);
2050        const int vl=lid%32;
2051        for(int rr=lid/32;rr<NR;rr+=8){
2052#pragma unroll
2053        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];
2054#pragma unroll
2055            for(int off=8;off;off>>=1)v+=sycl::permute_group_by_xor(sg,v,off);
2056            if(vl==0&&base+rr<N)y[uint32_t(j)*uint32_t(N)+uint32_t(base+rr)]=v;
2057        }
2058        }
2059    });
2060}
2061template<int KB>void iq4_xmx_virtual_T(int T,const uint8_t* w,const Q81Block* x,float* y,int N,sycl::queue* q){
2062#define IQ4_XMX_T(t) case t:iq4_xmx_virtual_launch<t,KB>(w,x,y,N,q);break
2063    switch(T){IQ4_XMX_T(1);IQ4_XMX_T(2);IQ4_XMX_T(3);IQ4_XMX_T(4);IQ4_XMX_T(5);IQ4_XMX_T(6);IQ4_XMX_T(7);IQ4_XMX_T(8);}
2064#undef IQ4_XMX_T
2065}
2066inline bool wide_k() {   // STRATA_MMVQ_WIDE_K=0: Q4_K/Q5_K/IQ4_XS through the multi kernel (the old path)
2067    static const bool v = std::getenv("STRATA_MMVQ_WIDE_K") == nullptr || std::atoi(std::getenv("STRATA_MMVQ_WIDE_K")) != 0;
2068    return v;
2069}
2070template <typename F>
2071bool try_wide(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
2072    if (!wide_k() || ncols < 1 || ncols > 8 || n_in % QK != 0) return false;
2073    const auto s = strata::q_of(stream);
2074    switch (ncols) {
2075        case 1: launch_wide<F, 1>(weights, x_q8_1, y, n_in, n_out, s); return true;
2076        case 2: launch_wide<F, 2>(weights, x_q8_1, y, n_in, n_out, s); return true;
2077        case 3: launch_wide<F, 3>(weights, x_q8_1, y, n_in, n_out, s); return true;
2078        case 4: launch_wide<F, 4>(weights, x_q8_1, y, n_in, n_out, s); return true;
2079        case 5: launch_wide<F, 5>(weights, x_q8_1, y, n_in, n_out, s); return true;
2080        case 6: launch_wide<F, 6>(weights, x_q8_1, y, n_in, n_out, s); return true;
2081        case 7: launch_wide<F, 7>(weights, x_q8_1, y, n_in, n_out, s); return true;
2082        default: launch_wide<F, 8>(weights, x_q8_1, y, n_in, n_out, s); return true;
2083    }
2084}
2085
2086// SYCL port: wide kernels for the 32-element formats Q8_0 (34-byte blocks) and IQ4_NL (18). Both are only 2-byte
2087// aligned, so the weights come through load16_a2 (page-safe). Q8_0: 2 lanes per block (16 quants each), 16 blocks
2088// per sub-group step; IQ4_NL: 1 lane per block (its 16 bytes = 32 nibbles), 32 blocks per step. One row per
2089// sub-group. The multi/small kernels these replace measured 26 GB/s (IQ4_NL 640 -> 2560) to ~300 GB/s.
2090struct Wide32Q8 {
2091    using Block = Q80Block;
2092    static constexpr int LPB = 2;
2093    struct W { sycl::int4 q; float d; int half; };
2094    static W load(const Block* b, int l) {
2095        W r; r.half = l; r.q = load16_a2(b->qs + 16 * l); r.d = (float) b->d; return r;
2096    }
2097    static float apply(const W& r, const Q81Block* xb) {
2098        return r.d * (float) xb->ds[0] * (float) dp4a4(r.q, ld_q8_16(xb, r.half), 0);
2099    }
2100};
2101struct Wide32IQ4NL {
2102    using Block = IQ4NLBlock;
2103    static constexpr int LPB = 1;
2104    struct W { sycl::int4 lo, hi; float d; };
2105    static W load(const Block* b, int) {
2106        W r;
2107        const sycl::int4 q = load16_a2(b->qs);
2108        const uint32_t v[4] = {(uint32_t) q.x(), (uint32_t) q.y(), (uint32_t) q.z(), (uint32_t) q.w()};
2109        int lo[4], hi[4];
2110#pragma unroll
2111        for (int i = 0; i < 4; ++i) { lo[i] = (int) iq4_lut4(v[i] & 0x0f0f0f0f); hi[i] = (int) iq4_lut4((v[i] >> 4) & 0x0f0f0f0f); }
2112        r.lo = sycl::int4(lo[0], lo[1], lo[2], lo[3]); r.hi = sycl::int4(hi[0], hi[1], hi[2], hi[3]);
2113        r.d = (float) b->d;
2114        return r;
2115    }
2116    static float apply(const W& r, const Q81Block* xb) {
2117        return r.d * (float) xb->ds[0] * (float) dp4a4(r.hi, ld_q8_16(xb, 1), dp4a4(r.lo, ld_q8_16(xb, 0), 0));
2118    }
2119};
2120template <typename F, int NCOLS>
2121void native_mmvq_wide32_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
2122                               float* __restrict__ y, int n_in, int n_out) {
2123    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2124    const int lane = int(item.get_local_id(2)), warp = int(item.get_local_id(1));
2125    const int row = int(item.get_group(2)) * WARPS + warp;
2126    if (row >= n_out) return;
2127    constexpr int BPS = WARP / F::LPB;                  // blocks per sub-group step
2128    const int blocks_per_row = n_in / 32;
2129    const int l = lane % F::LPB, sub = lane / F::LPB;
2130    const typename F::Block* wr = w + std::size_t(row) * blocks_per_row;
2131    float acc[NCOLS] = {};
2132    for (int kb = sub; kb < blocks_per_row; kb += BPS) {
2133        const typename F::W wv = F::load(wr + kb, l);
2134#pragma unroll
2135        for (int j = 0; j < NCOLS; ++j) acc[j] += F::apply(wv, x + std::size_t(j) * blocks_per_row + kb);
2136    }
2137    auto sg = item.get_sub_group();
2138#pragma unroll
2139    for (int j = 0; j < NCOLS; ++j) {
2140        float v = acc[j];
2141#pragma unroll
2142        for (int o = WARP / 2; o > 0; o >>= 1) v += sycl::permute_group_by_xor(sg, v, o);
2143        if (lane == 0) y[std::size_t(j) * n_out + row] = v;
2144    }
2145}
2146template <typename F, int NCOLS>
2147void launch_wide32(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, dpct::queue_ptr s) {
2148    const auto* w = static_cast<const typename F::Block*>(weights);
2149    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2150    const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
2151    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_wide32, F, dpct_kernel_scalar<NCOLS>>>(
2152        sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
2153        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_wide32_kernel<F, NCOLS>(w, x, y, n_in, n_out); });
2154}
2155inline bool wide_32() {   // STRATA_MMVQ_WIDE_32=0: Q8_0/IQ4_NL through the small/multi kernels (the old path)
2156    static const bool v = std::getenv("STRATA_MMVQ_WIDE_32") == nullptr || std::atoi(std::getenv("STRATA_MMVQ_WIDE_32")) != 0;
2157    return v;
2158}
2159template <typename F>
2160bool try_wide32(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
2161    if (!wide_32() || ncols < 1 || ncols > 8 || n_in % 32 != 0) return false;
2162    const auto s = strata::q_of(stream);
2163    switch (ncols) {
2164        case 1: launch_wide32<F, 1>(weights, x_q8_1, y, n_in, n_out, s); return true;
2165        case 2: launch_wide32<F, 2>(weights, x_q8_1, y, n_in, n_out, s); return true;
2166        case 3: launch_wide32<F, 3>(weights, x_q8_1, y, n_in, n_out, s); return true;
2167        case 4: launch_wide32<F, 4>(weights, x_q8_1, y, n_in, n_out, s); return true;
2168        case 5: launch_wide32<F, 5>(weights, x_q8_1, y, n_in, n_out, s); return true;
2169        case 6: launch_wide32<F, 6>(weights, x_q8_1, y, n_in, n_out, s); return true;
2170        case 7: launch_wide32<F, 7>(weights, x_q8_1, y, n_in, n_out, s); return true;
2171        default: launch_wide32<F, 8>(weights, x_q8_1, y, n_in, n_out, s); return true;
2172    }
2173}
2174
2175// SYCL port: alignment experiment - Q6_K blocks repacked at a 224-byte stride (every block 16-byte aligned).
2176template <int NCOLS>
2177void launch_q6k_wide224(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, dpct::queue_ptr s) {
2178    const auto* w = static_cast<const Q6KBlock*>(weights);
2179    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2180    const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
2181    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_q6k_wide224, dpct_kernel_scalar<NCOLS>>>(
2182        sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
2183        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_q6k_wide_kernel<NCOLS, 1, WARP, 224>(w, x, y, n_in, n_out); });
2184}
2185bool g_q6k_wide = std::getenv("STRATA_MMVQ_WIDE") == nullptr || std::atoi(std::getenv("STRATA_MMVQ_WIDE")) != 0;
2186
2187template <typename F, int NCOLS, int RPW>
2188void launch_rowwarp(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, dpct::queue_ptr s) {
2189    const auto* w = static_cast<const typename F::Block*>(weights);
2190    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2191    const unsigned blocks = unsigned((std::size_t(n_out) + WARPS * RPW - 1) / (WARPS * RPW));
2192    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_rowwarp, F, dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<RPW>>>(
2193        sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
2194        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] { native_mmvq_rowwarp_kernel<F, NCOLS, RPW>(w, x, y, n_in, n_out); });
2195}
2196inline int rowwarp_rpw() {   // STRATA_MMVQ_RPW: 0 = the shared kernel, 1/2/4 = rows per warp (bench knob)
2197    static const int v = std::getenv("STRATA_MMVQ_RPW") ? std::atoi(std::getenv("STRATA_MMVQ_RPW")) : 0;   // default: the shared kernel (measured equal at warm clocks)
2198    return v;
2199}
2200
2201template <typename F, int NCOLS>
2202void launch_multi_n(const void *weights, const void *x_q8_1, float *y, int n_in,
2203                    int n_out, dpct::queue_ptr s) {
2204    const auto* w = static_cast<const typename F::Block*>(weights);
2205    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2206    auto exp_props = sycl::ext::oneapi::experimental::properties{
2207        sycl::ext::oneapi::experimental::use_root_sync};
2208    dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
2209    if (!g_multi_exact) {
2210        constexpr int NW = NCOLS <= 4 ? 4 : 2;
2211        constexpr int ROWS = 1;   // SYCL port: one row per work-group (more groups: the kernel is latency-bound here)
2212        const unsigned blocks = unsigned((std::size_t(n_out) + ROWS - 1) / ROWS);
2213        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
2214            class native_mmvq_multi_kernel_646c3d, F,
2215            dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<NW>,
2216            dpct_kernel_scalar<2>>>(
2217            sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, NW, WARP),
2218                              sycl::range(1, NW, WARP)),
2219            exp_props,
2220            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2221                native_mmvq_multi_kernel<F, NCOLS, NW, ROWS>(w, x, y, n_in, n_out);
2222            });
2223        return;
2224    }
2225    const dpct::dim3 threads(WARP, WARPS);
2226    // #783 PR-h (stuchapin909): two rows per block for every K, not only small K - each row keeps its own partial sums and
2227    // reduction, so a row's result does not depend on its neighbour; STRATA_NO_MMVQ_ROWS2=1 keeps one row for large K
2228    static const bool rows1 = [] {
2229        const char* v = std::getenv("STRATA_NO_MMVQ_ROWS2");
2230        return v != nullptr && v[0] != '\0' && v[0] != '0';
2231    }();
2232    if (rows1 && n_in / F::DIV >= F::BPI) {
2233        if (s26_tsum_on()) {
2234            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
2235                class native_mmvq_multi_kernel_2a7dda, F,
2236                dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<WARPS>,
2237                dpct_kernel_scalar<1>, dpct_kernel_scalar<true>>>(
2238                sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads, threads),
2239                exp_props,
2240                [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2241                    native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, true>(w, x, y, n_in, n_out);
2242                });
2243        } else {
2244            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
2245                class native_mmvq_multi_kernel_23124e, F,
2246                dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<WARPS>,
2247                dpct_kernel_scalar<1>, dpct_kernel_scalar<false>>>(
2248                sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads, threads),
2249                exp_props,
2250                [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2251                    native_mmvq_multi_kernel<F, NCOLS, WARPS, 1>(w, x, y, n_in, n_out);
2252                });
2253        }
2254        return;
2255    }
2256    constexpr int ROWS = 2;
2257    const unsigned blocks = unsigned((std::size_t(n_out) + ROWS - 1) / ROWS);
2258    if (s26_tsum_on()) {
2259        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
2260            class native_mmvq_multi_kernel_279861, F,
2261            dpct_kernel_scalar<NCOLS>, dpct_kernel_scalar<WARPS>,
2262            dpct_kernel_scalar<ROWS>, dpct_kernel_scalar<true>>>(
2263            sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),
2264            exp_props,
2265            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2266                native_mmvq_multi_kernel<F, NCOLS, WARPS, ROWS, true>(w, x, y, n_in, n_out);
2267            });
2268    } else {
2269        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
2270            class native_mmvq_multi_kernel_75e8ad, F, dpct_kernel_scalar<NCOLS>,
2271            dpct_kernel_scalar<WARPS>, dpct_kernel_scalar<ROWS>,
2272            dpct_kernel_scalar<false>>>(
2273            sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),
2274            exp_props,
2275            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2276                native_mmvq_multi_kernel<F, NCOLS, WARPS, ROWS>(w, x, y, n_in, n_out);
2277            });
2278    }
2279}
2280
2281template<typename F>
2282void launch_multi(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols,
2283                  void* stream) {
2284    const auto s = strata::q_of(stream);
2285    switch (ncols) {
2286        case 2: launch_multi_n<F, 2>(weights, x_q8_1, y, n_in, n_out, s); break;
2287        case 3: launch_multi_n<F, 3>(weights, x_q8_1, y, n_in, n_out, s); break;
2288        case 4: launch_multi_n<F, 4>(weights, x_q8_1, y, n_in, n_out, s); break;
2289        case 5: launch_multi_n<F, 5>(weights, x_q8_1, y, n_in, n_out, s); break;
2290        case 6: launch_multi_n<F, 6>(weights, x_q8_1, y, n_in, n_out, s); break;
2291        case 7: launch_multi_n<F, 7>(weights, x_q8_1, y, n_in, n_out, s); break;
2292        case 8: launch_multi_n<F, 8>(weights, x_q8_1, y, n_in, n_out, s); break;
2293        default: throw std::invalid_argument("native MMVQ multi-column launch requires 2 <= ncols <= 8");
2294    }
2295}
2296
2297void validate_shape(int n_in, int ncols, int block_elems = Q8K) {
2298    if (n_in <= 0 || n_in % block_elems != 0) {
2299        throw std::invalid_argument("native MMVQ requires n_in > 0 and divisible by its block element count");
2300    }
2301    if (ncols < 1 || ncols > MAX_NCOLS) throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8");
2302}
2303void validate_pointer(const void* p) {
2304    if (!p || reinterpret_cast<std::uintptr_t>(p) % 4 != 0) {
2305        throw std::invalid_argument("native MMVQ requires non-null 4-byte aligned device pointers");
2306    }
2307}
2308void validate_stream(void* stream) {
2309    if (!stream) throw std::invalid_argument("native MMVQ requires an explicit non-null CUDA stream");
2310}
2311void launch_check() {
2312    /*
2313    DPCT1010: SYCL uses exceptions to report errors and does not use the
2314    error codes. The cudaGetLastError function call was replaced with 0. You
2315    need to rewrite this code.
2316    */
2317    const auto error = 0;
2318    /*
2319    DPCT1000: Error handling if-stmt was detected but could not be
2320    rewritten.
2321    */
2322    if (error != 0) {
2323        /*
2324        DPCT1009: SYCL reports errors using exceptions and does not use
2325        error codes. Please replace the "get_error_string_dummy(...)" with a
2326        real error-handling function.
2327        */
2328        /*
2329        DPCT1001: The statement could not be removed.
2330        */
2331        throw std::runtime_error(std::string("native MMVQ launch: ") +
2332                                 dpct::get_error_string_dummy(error));
2333    }
2334}
2335
2336
2337#if defined(STRATA_HIP_GFX906)
2338// ---- AMD (wave64) layout: one wavefront per R rows, four wavefronts per block, the row's blocks strided over the
2339// 64 lanes exactly as the CUDA kernels stride them over a block (kbx = lane / T, stride 64 / T), and a 64-lane
2340// butterfly instead of the LDS partials and __syncthreads of the one-block-per-row layout: on gfx906 a block per
2341// 2 KB row spent most of its time being launched and joined.  The SAME kernel serves every column count 1..8, so a
2342// column's sums do not depend on how many columns (verify tokens) ride along.  STRATA_MMVQ_WAVE=0: the CUDA layout.
2343bool g_wave_off = std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0";
2344template<typename F, int NCOLS, int R>
2345__launch_bounds__(256)
2346__global__ void native_mmvq_wave_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
2347                                        float* __restrict__ y, int n_in, int n_out) {
2348    constexpr int BPIW = 64 / F::T;
2349    static_assert(64 % F::T == 0, "a block's threads must tile the wavefront");
2350    const int lane = int(threadIdx.x) & 63;
2351    const int row0 = (int(blockIdx.x) * 4 + (int(threadIdx.x) >> 6)) * R;
2352    if (row0 >= n_out) return;
2353    const int blocks_per_row = n_in / F::DIV;
2354    const int x_stride = n_in / Q8K;
2355    const int kqs = F::kqs(lane);
2356    float tmp[NCOLS][R] = {};
2357    for (int kbx = lane / F::T; kbx < blocks_per_row; kbx += BPIW) {
2358        const int kby = kbx * F::KBY;
2359#pragma unroll
2360        for (int i = 0; i < R; ++i) {
2361            if (row0 + i < n_out) {
2362                const typename F::W wv = F::load(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs);
2363#pragma unroll
2364                for (int j = 0; j < NCOLS; ++j) tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);
2365            }
2366        }
2367    }
2368#pragma unroll
2369    for (int j = 0; j < NCOLS; ++j)
2370#pragma unroll
2371        for (int i = 0; i < R; ++i) {
2372            float v = tmp[j][i];
2373#pragma unroll
2374            for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64);
2375            if (lane == 0 && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = v;
2376        }
2377}
2378template<typename F, int NCOLS>
2379void wave_launch_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) {
2380    const auto* w = static_cast<const typename F::Block*>(weights);
2381    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2382    constexpr int R = 1;
2383    const unsigned blocks = unsigned((std::size_t(n_out) + 4 * R - 1) / (4 * R));
2384    native_mmvq_wave_kernel<F, NCOLS, R><<<blocks, 256, 0, s>>>(w, x, y, n_in, n_out);
2385}
2386template<typename F>
2387void wave_launch(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
2388    const auto s = static_cast<cudaStream_t>(stream);
2389    switch (ncols) {
2390        case 1: wave_launch_n<F, 1>(weights, x_q8_1, y, n_in, n_out, s); break;
2391        case 2: wave_launch_n<F, 2>(weights, x_q8_1, y, n_in, n_out, s); break;
2392        case 3: wave_launch_n<F, 3>(weights, x_q8_1, y, n_in, n_out, s); break;
2393        case 4: wave_launch_n<F, 4>(weights, x_q8_1, y, n_in, n_out, s); break;
2394        case 5: wave_launch_n<F, 5>(weights, x_q8_1, y, n_in, n_out, s); break;
2395        case 6: wave_launch_n<F, 6>(weights, x_q8_1, y, n_in, n_out, s); break;
2396        case 7: wave_launch_n<F, 7>(weights, x_q8_1, y, n_in, n_out, s); break;
2397        case 8: wave_launch_n<F, 8>(weights, x_q8_1, y, n_in, n_out, s); break;
2398        default: throw std::invalid_argument("native MMVQ (wave) requires 1 <= ncols <= 8");
2399    }
2400}
2401#define STRATA_WAVE_MMVQ(...) \
2402    if (!g_wave_off) { wave_launch<__VA_ARGS__>(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); return; }
2403#else
2404#define STRATA_WAVE_MMVQ(...)
2405#endif
2406
2407template<typename Weight, int Qi>
2408void small_mmvq(const void* weights, const void* x_q8_1, float* y,
2409                int n_in, int n_out, int ncols, void* stream) {
2410    validate_shape(n_in, ncols, 32);
2411    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
2412    validate_pointer(weights);
2413    validate_pointer(x_q8_1);
2414    validate_pointer(y);
2415    validate_stream(stream);
2416    STRATA_WAVE_MMVQ(SmallTraits<Weight, Qi>)
2417    if (ncols > 1) {
2418        launch_multi<SmallTraits<Weight, Qi>>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
2419        launch_check();
2420        return;
2421    }
2422    const auto* w = static_cast<const Weight*>(weights);
2423    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2424    const auto s = strata::q_of(stream);
2425    const dpct::dim3 threads(WARP, WARPS);
2426    if (n_in / 32 < 2 * WARPS * WARP / Qi) {
2427        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
2428        /*
2429        DPCT1049: The work-group size passed to the SYCL kernel may exceed
2430        the limit. To get the device limit, query
2431        info::device::max_work_group_size. Adjust the work-group size if needed.
2432        */
2433        {
2434            iq4nl_values.init(*s);
2435
2436            auto exp_props = sycl::ext::oneapi::experimental::properties{
2437                sycl::ext::oneapi::experimental::use_root_sync};
2438
2439            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
2440                auto iq4nl_values_ptr_ct1 = iq4nl_values.get_ptr();
2441
2442                cgh.parallel_for<dpct_kernel_name<
2443                    class native_small_mmvq_kernel_95f41f, Weight,
2444                    dpct_kernel_scalar<Qi>, dpct_kernel_scalar<true>>>(
2445                    sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads,
2446                                      threads),
2447                    exp_props,
2448                    [=](sycl::nd_item<3> item_ct1)
2449                        [[sycl::reqd_sub_group_size(32)]] {
2450                            native_small_mmvq_kernel<Weight, Qi, true>(
2451                                w, x, y, n_in, n_out, iq4nl_values_ptr_ct1);
2452                        });
2453            });
2454        }
2455    } else {
2456        /*
2457        DPCT1049: The work-group size passed to the SYCL kernel may exceed
2458        the limit. To get the device limit, query
2459        info::device::max_work_group_size. Adjust the work-group size if needed.
2460        */
2461        iq4nl_values.init(*s);
2462
2463        auto exp_props = sycl::ext::oneapi::experimental::properties{
2464            sycl::ext::oneapi::experimental::use_root_sync};
2465
2466        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
2467            auto iq4nl_values_ptr_ct1 = iq4nl_values.get_ptr();
2468
2469            cgh.parallel_for<dpct_kernel_name<
2470                class native_small_mmvq_kernel_d00fb9, Weight,
2471                dpct_kernel_scalar<Qi>, dpct_kernel_scalar<false>>>(
2472                sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,
2473                                  threads),
2474                exp_props,
2475                [=](sycl::nd_item<3> item_ct1)
2476                    [[sycl::reqd_sub_group_size(32)]] {
2477                        native_small_mmvq_kernel<Weight, Qi, false>(
2478                            w, x, y, n_in, n_out, iq4nl_values_ptr_ct1);
2479                    });
2480        });
2481    }
2482    launch_check();
2483}
2484
2485template<typename Weight, int Qi>
2486void small_f32(const void* weights, const float* x, void* scratch_q8_1,
2487               float* y, int n_in, int n_out, int ncols, void* stream) {
2488    validate_shape(n_in, ncols, 32);
2489    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
2490    validate_pointer(weights);
2491    validate_pointer(x);
2492    validate_pointer(scratch_q8_1);
2493    validate_pointer(y);
2494    validate_stream(stream);
2495    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
2496    small_mmvq<Weight, Qi>(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
2497}
2498
2499// ============================ STRATA_Q8_PACKED=1: the packed Q8_0 decode layout (opt-in) ============================
2500//
2501// A lossless load-time repack of a Q8_0 matrix: the SAME int8 values in a qs plane (row-major, n_in bytes per row)
2502// followed by the SAME fp16 scales in a d plane (row-major, n_in / 32 per row) - no requantization, same bytes.
2503// The GGUF's 34-byte blocks leave every int 2-byte aligned (load_int_b2 = two 16-bit loads); the planes give each
2504// thread one aligned 8-byte run, read with streaming (non-temporal) loads. Every thread owns exactly the bytes of
2505// the ncols = 1 / multi-column EXACT layout (block kbx = tid / 4 + 32 i, ints 2 (tid % 4) and +1), accumulates them
2506// in the same order with the same expression, and the cross-warp sum and XOR tree are the same: every output is
2507// BITWISE equal to native_small_mmvq_kernel / native_mmvq_multi_kernel<SmallTraits<Q80Block, 8>, NC, 4, 1>.
2508// Eligible: 1024 <= n_in <= 4096 and n_out >= 2048, run as 640 persistent workgroups (a grid-stride over rows, two
2509// partial buffers). Measured on gfx1151 (S26, 8 real UD-IQ4_XS layers per shape, paired, 1-5 columns): 2560 ->
2510// 6144/10240/12288 +10-12% per call (engine trace: -10.7% on those calls). 6144 -> 2560 (one workgroup per row)
2511// was +2-4% standalone but -3% in the engine, and rows < 2048 lose: neither is packed.
2512#if defined(__HIPCC__)
2513#define STRATA_Q8P_LOAD(p) __builtin_nontemporal_load(p)
2514#else
2515/*
2516DPCT1098: The '*' expression is used instead of the __ldcs call. These two
2517expressions do not provide the exact same functionality. Check the generated
2518code for potential precision and/or performance issues.
2519*/
2520/*
2521DPCT1064: Migrated __ldcs call is used in a macro/template definition and
2522may not be valid for all macro/template uses. Adjust the code.
2523*/
2524#define STRATA_Q8P_LOAD(p) (*(p))
2525#endif
2526constexpr int Q8P_PERSIST_GRID = 640;
2527constexpr int Q8P_PERSIST_MAX_IN = 4096;
2528
2529template <int NCOLS, bool TS = false>
2530/*
2531DPCT1110: The total declared local variable size in device function
2532native_q8_0_packed_kernel exceeds 128 bytes and may cause high register
2533pressure. Consult with your hardware vendor to find the total register size
2534available and adjust the code, or use smaller sub-group size to avoid high
2535register pressure.
2536*/
2537__dpct_inline__ void
2538native_q8_0_packed_kernel(const int8_t *__restrict__ qs,
2539                          const sycl::half *__restrict__ dpl,
2540                          const Q81Block *__restrict__ x, float *__restrict__ y,
2541                          int n_in, int n_out, int row_step) {
2542    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2543    const int tid =
2544        WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
2545    const int nb = n_in / 32;
2546    const int kqs = 2 * (tid % 4);
2547    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2548        float[2][WARPS - 1][NCOLS][WARP]>(
2549        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2550    int buf = 0;
2551    for (int row = int(item_ct1.get_group(2)); row < n_out;
2552         row += row_step, buf ^= 1) {
2553        float tmp[NCOLS] = {};
2554        for (int kbx = tid / 4; kbx < nb; kbx += 2 * WARPS * WARP / 8) {
2555            const std::size_t block = std::size_t(row) * nb + kbx;
2556            const int* p = reinterpret_cast<const int*>(qs + block * 32) + kqs;
2557            const int v0 = STRATA_Q8P_LOAD(p);
2558            const int v1 = STRATA_Q8P_LOAD(p + 1);
2559            const float d0 = dpl[block];
2560#pragma unroll
2561            for (int j = 0; j < NCOLS; ++j) {
2562                const Q81Block* xb = x + std::size_t(j) * nb + kbx;
2563                const int* u = reinterpret_cast<const int*>(xb->qs);
2564                int sumi = 0;
2565                sumi = STRATA_DP4A(v0, u[kqs], sumi);
2566                sumi = STRATA_DP4A(v1, u[kqs + 1], sumi);
2567                const float d1 = xb->ds[0];
2568                tmp[j] += d0 * d1 * float(sumi);
2569            }
2570        }
2571        if (item_ct1.get_local_id(1) > 0) {
2572#pragma unroll
2573            for (int j = 0; j < NCOLS; ++j)
2574                partial[buf][item_ct1.get_local_id(1) - 1][j]
2575                       [item_ct1.get_local_id(2)] = tmp[j];
2576        }
2577        /*
2578        DPCT1118: SYCL group functions and algorithms must be encountered in
2579        converged control flow. You may need to adjust the code.
2580        */
2581        /*
2582        DPCT1065: Consider replacing sycl::nd_item::barrier() with
2583        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
2584        better performance if there is no access to global memory.
2585        */
2586        item_ct1.barrier();
2587        if (TS && item_ct1.get_local_id(1) ==
2588                      0) { // S26 STRATA_TSUM=1: one transposed butterfly,
2589                           // bitwise the same sums
2590            constexpr int P = s26ts::pow2_ceil(NCOLS);
2591            float v[P];
2592#pragma unroll
2593            for (int j = 0; j < NCOLS; ++j) {
2594#pragma unroll
2595                for (int l = 0; l < WARPS - 1; ++l) tmp[j] +=
2596                    partial[buf][l][j][item_ct1.get_local_id(2)];
2597                v[j] = tmp[j];
2598            }
2599#pragma unroll
2600            for (int j = NCOLS; j < P; ++j) v[j] = 0.0f;
2601            const float sum = s26ts::tsum<P>(v, int(item_ct1.get_local_id(2)));
2602            const int j = s26ts::tsum_token<P>(int(item_ct1.get_local_id(2)));
2603            if (int(item_ct1.get_local_id(2)) == s26ts::tsum_lane<P>(j) &&
2604                j < NCOLS) y[std::size_t(j) * n_out + row] = sum;
2605        } else if (item_ct1.get_local_id(1) == 0) {
2606#pragma unroll
2607            for (int j = 0; j < NCOLS; ++j) {
2608#pragma unroll
2609                for (int l = 0; l < WARPS - 1; ++l) tmp[j] +=
2610                    partial[buf][l][j][item_ct1.get_local_id(2)];
2611                tmp[j] = warp_sum(tmp[j]);
2612                if (item_ct1.get_local_id(2) == 0)
2613                    y[std::size_t(j) * n_out + row] = tmp[j];
2614            }
2615        }
2616    }
2617}
2618
2619struct Q8Packed { const int8_t *qs; const sycl::half * d; int n_in, n_out; };
2620std::unordered_map<const void*, Q8Packed>& q8_packed_registry() {
2621    static std::unordered_map<const void*, Q8Packed> registry;
2622    return registry;
2623}
2624
2625template <int NCOLS>
2626void q8_packed_launch(const Q8Packed &w, const Q81Block *x, float *y,
2627                      dpct::queue_ptr s) {
2628    const bool persist = w.n_in <= Q8P_PERSIST_MAX_IN;
2629    const int grid = persist ? (std::min)(w.n_out, Q8P_PERSIST_GRID) : w.n_out;
2630    if (s26_tsum_on())
2631    {
2632        auto exp_props = sycl::ext::oneapi::experimental::properties{
2633            sycl::ext::oneapi::experimental::use_root_sync};
2634        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
2635
2636        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_q8_0_packed_kernel_851f07,
2637                                         dpct_kernel_scalar<NCOLS>,
2638                                         dpct_kernel_scalar<true>>>(
2639            sycl::nd_range<3>(sycl::range(1, 1, unsigned(grid)) *
2640                                  sycl::range(1, WARPS, WARP),
2641                              sycl::range(1, WARPS, WARP)),
2642            exp_props,
2643            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2644                native_q8_0_packed_kernel<NCOLS, true>(
2645                    w.qs, w.d, x, y, w.n_in, w.n_out, persist ? grid : w.n_out);
2646            });
2647    } else {
2648        auto exp_props = sycl::ext::oneapi::experimental::properties{
2649            sycl::ext::oneapi::experimental::use_root_sync};
2650        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
2651
2652        s->/*
2653DPCT1050: The template argument of the dpct_kernel_name could not be
2654deduced. You need to update this code.
2655*/
2656            parallel_for<
2657                dpct_kernel_name<class native_q8_0_packed_kernel_56c826,
2658                                 dpct_kernel_scalar<NCOLS>,
2659                                 dpct_kernel_scalar<false>>>(
2660                sycl::nd_range<3>(sycl::range(1, 1, unsigned(grid)) *
2661                                      sycl::range(1, WARPS, WARP),
2662                                  sycl::range(1, WARPS, WARP)),
2663                exp_props,
2664                [=](sycl::nd_item<3> item_ct1)
2665                    [[sycl::reqd_sub_group_size(32)]] {
2666                        native_q8_0_packed_kernel<NCOLS>(
2667                            w.qs, w.d, x, y, w.n_in, w.n_out,
2668                            persist ? grid : w.n_out);
2669                    });
2670    }
2671}
2672
2673bool q8_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
2674    auto& registry = q8_packed_registry();
2675    if (registry.empty() || (ncols > 1 && !g_multi_exact)) return false;   // packed = the EXACT layout only
2676    const auto found = registry.find(weights);
2677    if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false;
2678    validate_shape(n_in, ncols, 32);
2679    validate_pointer(x_q8_1);
2680    validate_pointer(y);
2681    validate_stream(stream);
2682    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2683    const auto s = strata::q_of(stream);
2684    switch (ncols) {
2685        case 1: q8_packed_launch<1>(found->second, x, y, s); break;
2686        case 2: q8_packed_launch<2>(found->second, x, y, s); break;
2687        case 3: q8_packed_launch<3>(found->second, x, y, s); break;
2688        case 4: q8_packed_launch<4>(found->second, x, y, s); break;
2689        case 5: q8_packed_launch<5>(found->second, x, y, s); break;
2690        case 6: q8_packed_launch<6>(found->second, x, y, s); break;
2691        case 7: q8_packed_launch<7>(found->second, x, y, s); break;
2692        case 8: q8_packed_launch<8>(found->second, x, y, s); break;
2693        default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8");
2694    }
2695    launch_check();
2696    return true;
2697}
2698
2699
2700// ============================ STRATA_Q6_PACKED=1: the packed Q6_K head layout (opt-in) ============================
2701//
2702// The output heads (the main head, 248320 rows, and the MTP draft head's row subset) are Q6_K matrices of 2560-wide
2703// rows: 10 blocks of 210 bytes each, so every int load is 2-byte aligned and a row is 2100 bytes. The packed copy
2704// holds the SAME bytes as four planes - ql (128 B per block), qh (64 B), scales (16 B), d (2 B) - so a thread's
2705// two words are aligned dword loads (non-temporal). Thread ownership (block tid / 32 + 4 i, word tid % 32), the
2706// q6_q8_dot_impl expression, the per-thread order and the reduction are those of native_q6_k_mmvq_kernel<false> /
2707// native_mmvq_multi_kernel<Q6KTraits, NC, 4, 1>: every output is bitwise equal. Persistent workgroups.
2708int g_q6p_grid_override = 0;   // the self-test's grid sweep (STRATA_Q6P_SELFTEST=2)
2709int q6p_grid() {
2710    if (g_q6p_grid_override > 0) return g_q6p_grid_override;
2711    static const int grid = [] {
2712        const char* v = std::getenv("STRATA_Q6P_GRID");
2713        const int g = v ? std::atoi(v) : 0;
2714        return g > 0 ? g : 640;
2715    }();
2716    return grid;
2717}
2718
2719template <int NCOLS, bool TS = false>
2720/*
2721DPCT1110: The total declared local variable size in device function
2722native_q6_k_packed_kernel exceeds 128 bytes and may cause high register
2723pressure. Consult with your hardware vendor to find the total register size
2724available and adjust the code, or use smaller sub-group size to avoid high
2725register pressure.
2726*/
2727__dpct_inline__ void native_q6_k_packed_kernel(
2728    const int *__restrict__ ql, const int *__restrict__ qh,
2729    const int8_t *__restrict__ sc, const sycl::half *__restrict__ dpl,
2730    const Q81Block *__restrict__ x, float *__restrict__ y, int n_in, int n_out,
2731    int row_step) {
2732    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2733    const int tid =
2734        WARP * int(item_ct1.get_local_id(1)) + int(item_ct1.get_local_id(2));
2735    const int nb = n_in / 256;
2736    const int x_stride = n_in / Q8K;
2737    const int iqs = tid % 32;
2738    const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8;
2739    const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4;
2740    const int vh_shift = 2 * ((iqs % 16) / 8);
2741    const int qh_word = 8 * (iqs / 16) + iqs % 8;
2742    auto &partial = *sycl::ext::oneapi::group_local_memory_for_overwrite<
2743        float[2][WARPS - 1][NCOLS][WARP]>(
2744        sycl::ext::oneapi::this_work_item::get_work_group<3>());
2745    int buf = 0;
2746    for (int row = int(item_ct1.get_group(2)); row < n_out;
2747         row += row_step, buf ^= 1) {
2748        float tmp[NCOLS] = {};
2749        for (int kbx = tid / 32; kbx < nb; kbx += WARPS * WARP / 32) {
2750            const std::size_t block = std::size_t(row) * nb + kbx;
2751            const int vl = STRATA_Q8P_LOAD(ql + block * 32 + iqs);
2752            const int vh = STRATA_Q8P_LOAD(qh + block * 16 + qh_word) >> vh_shift;
2753            const int8_t* scales = sc + block * 16 + scale_offset;
2754            const float d = dpl[block];
2755            const int kby = kbx * 8;
2756#pragma unroll
2757            for (int j = 0; j < NCOLS; ++j) {
2758                const Q81Block* xb = x + std::size_t(j) * x_stride + kby;
2759                int u[2];
2760                float d8[2];
2761#pragma unroll
2762                for (int i = 0; i < 2; ++i) {
2763                    u[i] = reinterpret_cast<const int*>(xb[bq8_offset + 2 * i].qs)[iqs % 8];
2764                    d8[i] = xb[bq8_offset + 2 * i].ds[0];
2765                }
2766                tmp[j] += q6_q8_dot_impl(vl, vh, u, scales, d, d8);
2767            }
2768        }
2769        if (item_ct1.get_local_id(1) > 0) {
2770#pragma unroll
2771            for (int j = 0; j < NCOLS; ++j)
2772                partial[buf][item_ct1.get_local_id(1) - 1][j]
2773                       [item_ct1.get_local_id(2)] = tmp[j];
2774        }
2775        /*
2776        DPCT1118: SYCL group functions and algorithms must be encountered in
2777        converged control flow. You may need to adjust the code.
2778        */
2779        /*
2780        DPCT1065: Consider replacing sycl::nd_item::barrier() with
2781        sycl::nd_item::barrier(sycl::access::fence_space::local_space) for
2782        better performance if there is no access to global memory.
2783        */
2784        item_ct1.barrier();
2785        if (TS && item_ct1.get_local_id(1) ==
2786                      0) { // S26 STRATA_TSUM=1: one transposed butterfly,
2787                           // bitwise the same sums
2788            constexpr int P = s26ts::pow2_ceil(NCOLS);
2789            float v[P];
2790#pragma unroll
2791            for (int j = 0; j < NCOLS; ++j) {
2792#pragma unroll
2793                for (int l = 0; l < WARPS - 1; ++l) tmp[j] +=
2794                    partial[buf][l][j][item_ct1.get_local_id(2)];
2795                v[j] = tmp[j];
2796            }
2797#pragma unroll
2798            for (int j = NCOLS; j < P; ++j) v[j] = 0.0f;
2799            const float sum = s26ts::tsum<P>(v, int(item_ct1.get_local_id(2)));
2800            const int j = s26ts::tsum_token<P>(int(item_ct1.get_local_id(2)));
2801            if (int(item_ct1.get_local_id(2)) == s26ts::tsum_lane<P>(j) &&
2802                j < NCOLS) y[std::size_t(j) * n_out + row] = sum;
2803        } else if (item_ct1.get_local_id(1) == 0) {
2804#pragma unroll
2805            for (int j = 0; j < NCOLS; ++j) {
2806#pragma unroll
2807                for (int l = 0; l < WARPS - 1; ++l) tmp[j] +=
2808                    partial[buf][l][j][item_ct1.get_local_id(2)];
2809                tmp[j] = warp_sum(tmp[j]);
2810                if (item_ct1.get_local_id(2) == 0)
2811                    y[std::size_t(j) * n_out + row] = tmp[j];
2812            }
2813        }
2814    }
2815}
2816
2817bool g_q6_bypass = false;   // the load-time self-test times the GGUF-layout kernels with the copy registered
2818
2819// the packed planes of one Q6_K matrix (owned: allocated by native_q6_k_pack, freed by native_q6_k_unpack)
2820struct Q6Packed {
2821    void *base; const int * ql; const int * qh; const int8_t * sc;
2822    const sycl::half * d;
2823    int n_in, n_out;
2824};
2825std::unordered_map<const void*, Q6Packed>& q6_packed_registry() {
2826    static std::unordered_map<const void*, Q6Packed> registry;
2827    return registry;
2828}
2829
2830template <int NCOLS>
2831void q6_packed_launch(const Q6Packed &w, const Q81Block *x, float *y,
2832                      dpct::queue_ptr s) {
2833    const int grid = (std::min)(w.n_out, q6p_grid());
2834    if (s26_tsum_on())
2835    {
2836        auto exp_props = sycl::ext::oneapi::experimental::properties{
2837            sycl::ext::oneapi::experimental::use_root_sync};
2838        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
2839
2840        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_q6_k_packed_kernel_ee650b,
2841                                         dpct_kernel_scalar<NCOLS>,
2842                                         dpct_kernel_scalar<true>>>(
2843            sycl::nd_range<3>(sycl::range(1, 1, unsigned(grid)) *
2844                                  sycl::range(1, WARPS, WARP),
2845                              sycl::range(1, WARPS, WARP)),
2846            exp_props,
2847            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
2848                native_q6_k_packed_kernel<NCOLS, true>(
2849                    w.ql, w.qh, w.sc, w.d, x, y, w.n_in, w.n_out, grid);
2850            });
2851    } else {
2852        auto exp_props = sycl::ext::oneapi::experimental::properties{
2853            sycl::ext::oneapi::experimental::use_root_sync};
2854        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
2855
2856        s->/*
2857DPCT1050: The template argument of the dpct_kernel_name could not be
2858deduced. You need to update this code.
2859*/
2860            parallel_for<
2861                dpct_kernel_name<class native_q6_k_packed_kernel_ca2554,
2862                                 dpct_kernel_scalar<NCOLS>,
2863                                 dpct_kernel_scalar<false>>>(
2864                sycl::nd_range<3>(sycl::range(1, 1, unsigned(grid)) *
2865                                      sycl::range(1, WARPS, WARP),
2866                                  sycl::range(1, WARPS, WARP)),
2867                exp_props,
2868                [=](sycl::nd_item<3> item_ct1)
2869                    [[sycl::reqd_sub_group_size(32)]] {
2870                        native_q6_k_packed_kernel<NCOLS>(
2871                            w.ql, w.qh, w.sc, w.d, x, y, w.n_in, w.n_out, grid);
2872                    });
2873    }
2874}
2875
2876bool q6_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
2877    auto& registry = q6_packed_registry();
2878    if (registry.empty() || g_q6_bypass || (ncols > 1 && !g_multi_exact)) return false;
2879    const auto found = registry.find(weights);
2880    if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false;
2881    validate_shape(n_in, ncols, 256);
2882    validate_pointer(x_q8_1);
2883    validate_pointer(y);
2884    validate_stream(stream);
2885    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2886    const auto s = strata::q_of(stream);
2887    switch (ncols) {
2888        case 1: q6_packed_launch<1>(found->second, x, y, s); break;
2889        case 2: q6_packed_launch<2>(found->second, x, y, s); break;
2890        case 3: q6_packed_launch<3>(found->second, x, y, s); break;
2891        case 4: q6_packed_launch<4>(found->second, x, y, s); break;
2892        case 5: q6_packed_launch<5>(found->second, x, y, s); break;
2893        case 6: q6_packed_launch<6>(found->second, x, y, s); break;
2894        case 7: q6_packed_launch<7>(found->second, x, y, s); break;
2895        case 8: q6_packed_launch<8>(found->second, x, y, s); break;
2896        default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= 8");
2897    }
2898    launch_check();
2899    return true;
2900}
2901
2902// ============================ STRATA_Q6_PLANAR: the Q6_K heads as 16-byte-aligned planes (SYCL port) ============================
2903//
2904// native_mmvq_q6k_wide_kernel<..., A2 = true> reads each lane's ql / qh run as two aligned 16-byte loads and a funnel shift
2905// because a 210-byte block is only 2-byte aligned. The planar layout holds the same bytes as four planes (ql 128 B, qh 64 B,
2906// scales 16 B, d 2 B per block): a lane's runs are single aligned int4 loads, its two scales one 16-bit load (the pair
2907// scales[so], scales[so + 4] stored adjacent, at byte 2g). The kernel is the A2 kernel's, line for line, from the loads on:
2908// every output is bitwise equal, ~14% faster on the 521 MB LM head and the draft head. Same bytes, so a matrix is CONVERTED
2909// (planar allocation made, GGUF-layout one freed): no VRAM is spent. Only the output heads are converted - the prompt path
2910// reads the other projections in the GGUF layout.
2911struct Q6Planar {
2912    void* base;
2913    const uint8_t* ql; const uint8_t* qh; const uint8_t* sc; const sycl::half* d;
2914    int n_in, n_out;
2915};
2916std::unordered_map<const void*, Q6Planar>& q6_planar_registry() {
2917    static std::unordered_map<const void*, Q6Planar> registry;
2918    return registry;
2919}
2920
2921template <int NCOLS>
2922void native_mmvq_q6k_planar_kernel(const uint8_t* __restrict__ qlp, const uint8_t* __restrict__ qhp,
2923                                   const uint8_t* __restrict__ scp, const sycl::half* __restrict__ dp,
2924                                   const Q81Block* __restrict__ x, float* __restrict__ y, int n_in, int n_out) {
2925    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
2926    const int lane = int(item.get_local_id(2)), warp = int(item.get_local_id(1));
2927    const int row = int(item.get_group(2)) * WARPS + warp;
2928    if (row >= n_out) return;
2929    const int blocks_per_row = n_in / QK, x_stride = n_in / Q8K;
2930    const int g = lane & 7, sub = lane >> 3;
2931    const int vh_shift = 2 * ((g & 3) >> 1);
2932    const int qh4_idx = 2 * (g >> 2) + (g & 1);
2933    const int bq8_offset = 4 * (g >> 2) + ((g & 3) >> 1);
2934    const int u_int4 = g & 1;
2935    float acc[NCOLS] = {};
2936    for (int kbx = sub; kbx < blocks_per_row; kbx += WARP / 8) {
2937        const int kby = kbx * (QK / Q8K);
2938        const std::size_t bi = std::size_t(row) * blocks_per_row + kbx;
2939        const sycl::int4 ql4 = reinterpret_cast<const sycl::int4*>(qlp + bi * 128)[g];
2940        const sycl::int4 qh4 = reinterpret_cast<const sycl::int4*>(qhp + bi * 64)[qh4_idx];
2941        const uint16_t s2 = reinterpret_cast<const uint16_t*>(scp + bi * 16)[g];
2942        const float d = dp[bi];
2943        const float dsc0 = d * (float) (int8_t) (s2 & 0xff), dsc1 = d * (float) (int8_t) (s2 >> 8);
2944        sycl::int4 u0[NCOLS], u1[NCOLS];
2945        float ds0[NCOLS], ds1[NCOLS];
2946#pragma unroll
2947        for (int j = 0; j < NCOLS; ++j) {
2948            const Q81Block* xb = x + std::size_t(j) * x_stride + kby + bq8_offset;
2949            u0[j] = ld_i4_a4(reinterpret_cast<const int*>(xb[0].qs) + 4 * u_int4);
2950            u1[j] = ld_i4_a4(reinterpret_cast<const int*>(xb[2].qs) + 4 * u_int4);
2951            ds0[j] = xb[0].ds[0]; ds1[j] = xb[2].ds[0];
2952        }
2953        const int vl[4] = {ql4.x(), ql4.y(), ql4.z(), ql4.w()};
2954        const int vh[4] = {qh4.x() >> vh_shift, qh4.y() >> vh_shift, qh4.z() >> vh_shift, qh4.w() >> vh_shift};
2955        int vi0[4], vi1[4];
2956#pragma unroll
2957        for (int p = 0; p < 4; ++p) {
2958            vi0[p] = q6_sub32((vl[p] & 0x0f0f0f0f) | ((vh[p] << 4) & 0x30303030));
2959            vi1[p] = q6_sub32(((vl[p] >> 4) & 0x0f0f0f0f) | (((vh[p] >> 4) << 4) & 0x30303030));
2960        }
2961#pragma unroll
2962        for (int j = 0; j < NCOLS; ++j) {
2963            int s0 = 0, s1 = 0;
2964            s0 = strata::dp4a(vi0[0], u0[j].x(), s0); s0 = strata::dp4a(vi0[1], u0[j].y(), s0);
2965            s0 = strata::dp4a(vi0[2], u0[j].z(), s0); s0 = strata::dp4a(vi0[3], u0[j].w(), s0);
2966            s1 = strata::dp4a(vi1[0], u1[j].x(), s1); s1 = strata::dp4a(vi1[1], u1[j].y(), s1);
2967            s1 = strata::dp4a(vi1[2], u1[j].z(), s1); s1 = strata::dp4a(vi1[3], u1[j].w(), s1);
2968            acc[j] += ds0[j] * dsc0 * (float) s0 + ds1[j] * dsc1 * (float) s1;
2969        }
2970    }
2971    auto sg = item.get_sub_group();
2972#pragma unroll
2973    for (int j = 0; j < NCOLS; ++j) {
2974        float v = acc[j];
2975#pragma unroll
2976        for (int o = WARP / 2; o > 0; o >>= 1) v += sycl::permute_group_by_xor(sg, v, o);
2977        if (lane == 0) y[std::size_t(j) * n_out + row] = v;
2978    }
2979}
2980
2981template <int NCOLS>
2982void q6_planar_launch(const Q6Planar& w, const Q81Block* x, float* y, dpct::queue_ptr s) {
2983    const unsigned blocks = unsigned((std::size_t(w.n_out) + WARPS - 1) / WARPS);
2984    const uint8_t *ql = w.ql, *qh = w.qh, *sc = w.sc;
2985    const sycl::half* d = w.d;
2986    const int n_in = w.n_in, n_out = w.n_out;
2987    if constexpr (NCOLS > 1) {   // same rule as the GGUF-layout wide kernel (#2207): the multi-column kernel spills at 128 GRF on Alchemist
2988        if (mmvq_large_grf(s)) {
2989            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_q6k_planar_grf256, dpct_kernel_scalar<NCOLS>>>(
2990                sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
2991                sycl::ext::oneapi::experimental::properties{sycl::ext::intel::experimental::grf_size<256>},
2992                [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
2993                    native_mmvq_q6k_planar_kernel<NCOLS>(ql, qh, sc, d, x, y, n_in, n_out);
2994                });
2995            return;
2996        }
2997    }
2998    strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_mmvq_q6k_planar, dpct_kernel_scalar<NCOLS>>>(
2999        sycl::nd_range<3>(sycl::range(1, 1, blocks) * sycl::range(1, WARPS, WARP), sycl::range(1, WARPS, WARP)),
3000        [=](sycl::nd_item<3>) [[sycl::reqd_sub_group_size(32)]] {
3001            native_mmvq_q6k_planar_kernel<NCOLS>(ql, qh, sc, d, x, y, n_in, n_out);
3002        });
3003}
3004
3005// every registered matrix is served here whatever the column count (more than 8: in chunks of 8), so a converted matrix is
3006// never read through a GGUF-layout kernel
3007bool q6_planar_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
3008    auto& registry = q6_planar_registry();
3009    if (registry.empty() || ncols < 1) return false;
3010    const auto found = registry.find(weights);
3011    if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false;
3012    validate_shape(n_in, std::min(ncols, 8), 256);
3013    validate_pointer(x_q8_1);
3014    validate_pointer(y);
3015    validate_stream(stream);
3016    const auto s = strata::q_of(stream);
3017    const std::size_t x_col = std::size_t(n_in / Q8K);   // Q8_1 blocks per column
3018    for (int c0 = 0; c0 < ncols; c0 += 8) {
3019        const int nc = std::min(8, ncols - c0);
3020        const auto* x = static_cast<const Q81Block*>(x_q8_1) + std::size_t(c0) * x_col;
3021        float* yy = y + std::size_t(c0) * n_out;
3022        switch (nc) {
3023            case 1: q6_planar_launch<1>(found->second, x, yy, s); break;
3024            case 2: q6_planar_launch<2>(found->second, x, yy, s); break;
3025            case 3: q6_planar_launch<3>(found->second, x, yy, s); break;
3026            case 4: q6_planar_launch<4>(found->second, x, yy, s); break;
3027            case 5: q6_planar_launch<5>(found->second, x, yy, s); break;
3028            case 6: q6_planar_launch<6>(found->second, x, yy, s); break;
3029            case 7: q6_planar_launch<7>(found->second, x, yy, s); break;
3030            default: q6_planar_launch<8>(found->second, x, yy, s); break;
3031        }
3032    }
3033    launch_check();
3034    return true;
3035}
3036
3037// plane offsets of a matrix of nb blocks in one allocation: ql | qh | scales | d, each 256-byte aligned
3038struct Q6PlanarLayout { std::size_t o_qh, o_sc, o_d, total; };
3039Q6PlanarLayout q6_planar_layout(std::size_t nb) {
3040    Q6PlanarLayout l;
3041    l.o_qh = (nb * 128 + 255) & ~std::size_t(255);
3042    l.o_sc = (l.o_qh + nb * 64 + 255) & ~std::size_t(255);
3043    l.o_d = (l.o_sc + nb * 16 + 255) & ~std::size_t(255);
3044    l.total = l.o_d + nb * 2;
3045    return l;
3046}
3047Q6Planar q6_planar_make(void* dev, std::size_t nb, int n_in, int n_out) {
3048    const Q6PlanarLayout l = q6_planar_layout(nb);
3049    auto* base = static_cast<uint8_t*>(dev);
3050    return Q6Planar{dev, base, base + l.o_qh, base + l.o_sc, reinterpret_cast<const sycl::half*>(base + l.o_d), n_in, n_out};
3051}
3052} // namespace
3053
3054bool native_q8_0_packed_enabled() {
3055    static const bool enabled = [] {
3056        const char* v = std::getenv("STRATA_Q8_PACKED");
3057        return v && v[0] == '1' && v[1] == '\0';
3058    }();
3059    return enabled;
3060}
3061
3062bool native_q8_0_packed_eligible(int n_in, int n_out) {
3063    return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN &&
3064           n_out >= 2048;
3065}
3066
3067void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out) {
3068    const auto* blocks = static_cast<const Q80Block*>(gguf_blocks);
3069    auto* qs = static_cast<int8_t*>(out);
3070    auto *d = reinterpret_cast<sycl::half *>(qs + std::size_t(n_in) * n_out);
3071    const std::size_t count = std::size_t(n_in / 32) * n_out;
3072    for (std::size_t b = 0; b < count; ++b) {
3073        std::memcpy(qs + b * 32, blocks[b].qs, 32);
3074        std::memcpy(d + b, &blocks[b].d, sizeof(sycl::half));
3075    }
3076}
3077
3078void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out) {
3079    validate_pointer(gguf_weights);
3080    validate_pointer(packed);
3081    if (!native_q8_0_packed_eligible(n_in, n_out)) throw std::invalid_argument("Q8_0 packed: ineligible shape");
3082    const auto* qs = static_cast<const int8_t*>(packed);
3083    q8_packed_registry()[gguf_weights] = Q8Packed{
3084        qs,
3085        reinterpret_cast<const sycl::half *>(qs + std::size_t(n_in) * n_out),
3086        n_in, n_out};
3087}
3088
3089void native_q8_0_packed_unregister(const void* gguf_weights) { q8_packed_registry().erase(gguf_weights); }
3090
3091bool native_q6_k_packed_enabled() {
3092    static const bool enabled = [] {
3093        const char* v = std::getenv("STRATA_Q6_PACKED");
3094        return v && v[0] == '1' && v[1] == '\0';
3095    }();
3096    return enabled;
3097}
3098
3099bool native_q6_k_planar_enabled() {
3100    static const bool enabled = [] {
3101        const char* v = std::getenv("STRATA_Q6_PLANAR");
3102        return !(v && v[0] == '0' && v[1] == '\0');
3103    }();
3104    return enabled;
3105}
3106
3107bool native_q6_k_is_planar(const void* weights) { return q6_planar_registry().count(weights) != 0; }
3108
3109// Converts a GGUF-layout Q6_K matrix (a device allocation of the caller's) to the planar layout: a new allocation holds the
3110// planes, the old one is freed, the returned pointer (the new allocation's, to be freed with sycl::free as the old one would
3111// have been, after native_q6_k_unpack) is the key native_q6_k_mmvq serves it under. Not eligible or no room: `weights` back.
3112void* native_q6_k_planar_adopt(void* weights, int n_in, int n_out, const char* what) try {
3113    if (!weights || n_in <= 0 || n_in % 256 || n_out <= 0 || !native_q6_k_planar_enabled()) return weights;
3114    if (q6_planar_registry().count(weights)) return weights;
3115    auto& q = dpct::get_in_order_queue();
3116    const std::size_t nb = std::size_t(n_in / 256) * std::size_t(n_out);
3117    const Q6PlanarLayout l = q6_planar_layout(nb);
3118    void* dev = nullptr;
3119    try { dev = strata::malloc_device_guarded(l.total, q, what); } catch (...) { dev = nullptr; }
3120    if (dev == nullptr) {
3121        std::fprintf(stderr, "strata: STRATA_Q6_PLANAR: no VRAM for the %s's planar copy (+%.1f MiB), keeping the GGUF layout\n", what,
3122                     l.total / 1048576.0);
3123        return weights;
3124    }
3125    const uint8_t* src = static_cast<const uint8_t*>(weights);
3126    uint8_t* base = static_cast<uint8_t*>(dev);
3127    const std::size_t o_qh = l.o_qh, o_sc = l.o_sc, o_d = l.o_d;
3128    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->parallel_for(sycl::range<1>(nb), [=](sycl::id<1> id) {
3129        const std::size_t b = id[0];
3130        const uint16_t* s16 = reinterpret_cast<const uint16_t*>(src + b * 210);
3131        uint16_t* qlo = reinterpret_cast<uint16_t*>(base + b * 128);
3132        for (int i = 0; i < 64; ++i) qlo[i] = s16[i];
3133        uint16_t* qho = reinterpret_cast<uint16_t*>(base + o_qh + b * 64);
3134        for (int i = 0; i < 32; ++i) qho[i] = s16[64 + i];
3135        const int8_t* sc = reinterpret_cast<const int8_t*>(src + b * 210 + 192);
3136        uint8_t* sco = base + o_sc + b * 16;
3137        for (int g = 0; g < 8; ++g) {
3138            const int so = 8 * (g >> 2) + (g & 3);
3139            sco[2 * g] = (uint8_t) sc[so]; sco[2 * g + 1] = (uint8_t) sc[so + 4];
3140        }
3141        reinterpret_cast<uint16_t*>(base + o_d)[b] = s16[104];
3142    });
3143    q.wait();
3144    sycl::free(weights, q);
3145    q6_planar_registry()[dev] = q6_planar_make(dev, nb, n_in, n_out);
3146    std::fprintf(stderr, "strata: STRATA_Q6_PLANAR: the %s (%d x %d) is stored as 16-byte-aligned planes (same bytes)\n", what, n_out, n_in);
3147    return dev;
3148}
3149catch (sycl::exception const& exc) {
3150    std::fprintf(stderr, "strata: STRATA_Q6_PLANAR conversion failed: %s\n", exc.what());
3151    return weights;
3152}
3153
3154// A planar matrix's rows `rows_dev[0 .. n_sel)` as a new planar matrix (the draft head's token subset of the LM head).
3155void* native_q6_k_planar_gather(const void* planar, int n_in, const int32_t* rows_dev, int64_t n_sel, const char* what) try {
3156    const auto found = q6_planar_registry().find(planar);
3157    if (found == q6_planar_registry().end() || found->second.n_in != n_in || n_sel <= 0) return nullptr;
3158    auto& q = dpct::get_in_order_queue();
3159    const int nbr = n_in / 256;
3160    const std::size_t nb = std::size_t(nbr) * std::size_t(n_sel);
3161    const Q6PlanarLayout l = q6_planar_layout(nb);
3162    void* dev = nullptr;
3163    try { dev = strata::malloc_device_guarded(l.total, q, what); } catch (...) { dev = nullptr; }
3164    if (dev == nullptr) return nullptr;
3165    const Q6Planar src = found->second;
3166    uint8_t* base = static_cast<uint8_t*>(dev);
3167    const std::size_t o_qh = l.o_qh, o_sc = l.o_sc, o_d = l.o_d;
3168    strata::kprof::kp(&q, __FILE__, __func__, __LINE__)->parallel_for(sycl::range<1>(nb), [=](sycl::id<1> id) {
3169        const std::size_t b = id[0];
3170        const std::size_t i = b / nbr, j = b - i * nbr;
3171        const std::size_t sb = std::size_t(rows_dev[i]) * nbr + j;
3172        const sycl::int4* sq = reinterpret_cast<const sycl::int4*>(src.ql + sb * 128);
3173        sycl::int4* dq = reinterpret_cast<sycl::int4*>(base + b * 128);
3174        for (int k = 0; k < 8; ++k) dq[k] = sq[k];
3175        const sycl::int4* sh = reinterpret_cast<const sycl::int4*>(src.qh + sb * 64);
3176        sycl::int4* dh = reinterpret_cast<sycl::int4*>(base + o_qh + b * 64);
3177        for (int k = 0; k < 4; ++k) dh[k] = sh[k];
3178        *reinterpret_cast<sycl::int4*>(base + o_sc + b * 16) = *reinterpret_cast<const sycl::int4*>(src.sc + sb * 16);
3179        reinterpret_cast<uint16_t*>(base + o_d)[b] = reinterpret_cast<const uint16_t*>(src.d)[sb];
3180    });
3181    q.wait();
3182    q6_planar_registry()[dev] = q6_planar_make(dev, nb, n_in, (int) n_sel);
3183    std::fprintf(stderr, "strata: STRATA_Q6_PLANAR: the %s (%lld x %d) is gathered from the planar head\n", what, (long long) n_sel, n_in);
3184    return dev;
3185}
3186catch (sycl::exception const& exc) {
3187    std::fprintf(stderr, "strata: STRATA_Q6_PLANAR gather failed: %s\n", exc.what());
3188    return nullptr;
3189}
3190
3191bool native_q6_k_pack(const void *weights, int n_in, int n_out,
3192                      const char *what) try {
3193    if (!weights || n_in <= 0 || n_in % 256 || n_in / 256 < WARPS * WARP / 32 || n_out < 2048) return false;
3194    if (q6_packed_registry().count(weights)) return true;
3195    const std::size_t nb = std::size_t(n_in / 256) * std::size_t(n_out);
3196    const std::size_t bytes = nb * sizeof(Q6KBlock);
3197    std::vector<Q6KBlock> host(nb);
3198    /*
3199    DPCT1026: The call to cudaGetLastError was removed because this
3200    functionality is redundant in SYCL.
3201    */
3202    if (DPCT_CHECK_ERROR(dpct::get_in_order_queue()
3203                             .memcpy(host.data(), weights, bytes)
3204                             .wait()) != 0) {
3205        ; return false;
3206    }
3207    // planes: ql | qh | scales | d, each 256-byte aligned
3208    const std::size_t o_qh = (nb * 128 + 255) & ~std::size_t(255);
3209    const std::size_t o_sc = (o_qh + nb * 64 + 255) & ~std::size_t(255);
3210    const std::size_t o_d = (o_sc + nb * 16 + 255) & ~std::size_t(255);
3211    const std::size_t total = o_d + nb * 2;
3212    std::vector<uint8_t> packed(total, 0);
3213    for (std::size_t b = 0; b < nb; ++b) {
3214        std::memcpy(packed.data() + b * 128, host[b].ql, 128);
3215        std::memcpy(packed.data() + o_qh + b * 64, host[b].qh, 64);
3216        std::memcpy(packed.data() + o_sc + b * 16, host[b].scales, 16);
3217        std::memcpy(packed.data() + o_d + b * 2, &host[b].d, 2);
3218    }
3219    void* dev = nullptr;
3220    /*
3221    DPCT1026: The call to cudaGetLastError was removed because this
3222    functionality is redundant in SYCL.
3223    */
3224    if (DPCT_CHECK_ERROR(dev = (void *)sycl::malloc_device(
3225                             total, dpct::get_in_order_queue())) != 0) {
3226        ; return false;
3227    }
3228    /*
3229    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
3230    the original code the source host memory is pageable memory. If the memory
3231    is not pageable, call wait() on event return by memcpy API to ensure
3232    synchronization behavior.
3233    */
3234    if (DPCT_CHECK_ERROR(dpct::get_in_order_queue().memcpy(dev, packed.data(),
3235                                                           total).wait()) != 0) {
3236        /*
3237        DPCT1026: The call to cudaGetLastError was removed because this
3238        functionality is redundant in SYCL.
3239        */
3240        sycl::free(dev, dpct::get_in_order_queue());; return false;
3241    }
3242    auto* base = static_cast<uint8_t*>(dev);
3243    q6_packed_registry()[weights] =
3244        Q6Packed{dev,
3245                 reinterpret_cast<const int *>(base),
3246                 reinterpret_cast<const int *>(base + o_qh),
3247                 reinterpret_cast<const int8_t *>(base + o_sc),
3248                 reinterpret_cast<const sycl::half *>(base + o_d),
3249                 n_in,
3250                 n_out};
3251    std::fprintf(stderr, "strata: STRATA_Q6_PACKED=1 packed the %s (%d x %d, +%.1f MiB)\n", what, n_out, n_in,
3252                 total / 1048576.0);
3253    // STRATA_Q6P_SELFTEST=1: bitwise check against the GGUF-layout kernels (1..4 columns) and paired timings
3254    if (const char* v = std::getenv("STRATA_Q6P_SELFTEST"); v && (v[0] == '1' || v[0] == '2')) {
3255        dpct::queue_ptr s = &dpct::get_in_order_queue();
3256        /*
3257        DPCT1025: The SYCL queue is created ignoring the flag and priority
3258        options.
3259        */
3260        s = dpct::get_current_device().create_queue(true);
3261        const int nq = n_in / Q8K;
3262        std::vector<Q81Block> hx(std::size_t(4) * nq);
3263        uint32_t r = 12345u;
3264        for (auto& blk : hx) {
3265            for (auto& q : blk.qs) { r = r * 1664525u + 1013904223u; q = int8_t(int((r >> 24) & 255u) - 128); }
3266            r = r * 1664525u + 1013904223u;
3267            blk.ds = sycl::float2(0.001f + float(r >> 8) * 1e-9f, 0.0f)
3268                         .convert<sycl::half, sycl::rounding_mode::rte>();
3269        }
3270        void *dx = nullptr, *ya = nullptr, *yb = nullptr;
3271        dx = (void *)sycl::malloc_device(hx.size() * sizeof(Q81Block),
3272                                         dpct::get_in_order_queue());
3273        ya = (void *)sycl::malloc_device(std::size_t(4) * n_out * 4,
3274                                         dpct::get_in_order_queue());
3275        yb = (void *)sycl::malloc_device(std::size_t(4) * n_out * 4,
3276                                         dpct::get_in_order_queue());
3277        dpct::get_in_order_queue()
3278            .memcpy(dx, hx.data(), hx.size() * sizeof(Q81Block))
3279            .wait();
3280        std::vector<float> a(std::size_t(4) * n_out), c(std::size_t(4) * n_out);
3281        bool same = true;
3282        for (int nc = 1; nc <= 4; ++nc) {
3283            g_q6_bypass = true;
3284            native_q6_k_mmvq(weights, dx, (float*) ya, n_in, n_out, nc, s);
3285            g_q6_bypass = false;
3286            native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s);
3287            s->wait();
3288            dpct::get_in_order_queue()
3289                .memcpy(a.data(), ya, std::size_t(nc) * n_out * 4)
3290                .wait();
3291            dpct::get_in_order_queue()
3292                .memcpy(c.data(), yb, std::size_t(nc) * n_out * 4)
3293                .wait();
3294            same = same && std::memcmp(a.data(), c.data(), std::size_t(nc) * n_out * 4) == 0;
3295        }
3296        dpct::event_ptr e0, e1;
3297        e0 = new sycl::event(); e1 = new sycl::event();
3298        for (int nc : {1, 2, 4}) {
3299            std::vector<float> tb, tc;
3300            for (int k = 0; k < 11; ++k) {
3301                for (int pass = 0; pass < 2; ++pass) {
3302                    const bool cand = (pass == 0) == (k % 2 == 1);
3303                    g_q6_bypass = !cand;
3304                    dpct::sync_barrier(e0, s);
3305                    for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) (cand ? yb : ya), n_in, n_out, nc, s);
3306                    dpct::sync_barrier(e1, s);
3307                    e1->wait_and_throw();
3308                    float ms = 0;
3309                        ms = (e1->get_profiling_info<
3310                                  sycl::info::event_profiling::command_end>() -
3311                              e0->get_profiling_info<
3312                                  sycl::info::event_profiling::
3313                                      command_start>()) /
3314                             1000000.0f;
3315                    (cand ? tc : tb).push_back(ms * 1000.0f / 5);
3316                }
3317            }
3318            g_q6_bypass = false;
3319            std::sort(tb.begin(), tb.end()); std::sort(tc.begin(), tc.end());
3320            std::fprintf(stderr, "strata: Q6_K packed self-test %s ncols %d: GGUF %.1f us (%.1f-%.1f), packed %.1f us "
3321                         "(%.1f-%.1f), 11 paired samples\n", what, nc, tb[5], tb[0], tb[10], tc[5], tc[0], tc[10]);
3322        }
3323        std::fprintf(stderr, "strata: Q6_K packed self-test %s: outputs %s (1-4 columns)\n", what,
3324                     same ? "BITWISE EQUAL" : "DIFFER");
3325        if (v[0] == '2') {   // grid sweep of the packed kernel
3326            for (int grid : {160, 320, 640, 1280, 2560, 5120, 20480}) {
3327                g_q6p_grid_override = grid;
3328                for (int nc : {1, 2, 4}) {
3329                    std::vector<float> tc;
3330                    for (int k = 0; k < 7; ++k) {
3331                        dpct::sync_barrier(e0, s);
3332                        for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s);
3333                        dpct::sync_barrier(e1, s);
3334                        e1->wait_and_throw();
3335                        float ms = 0; ms = (e1->get_profiling_info<
3336                                                sycl::info::event_profiling::
3337                                                    command_end>() -
3338                                            e0->get_profiling_info<
3339                                                sycl::info::event_profiling::
3340                                                    command_start>()) /
3341                                           1000000.0f;
3342                        tc.push_back(ms * 1000.0f / 5);
3343                    }
3344                    std::sort(tc.begin(), tc.end());
3345                    std::fprintf(stderr, "strata: Q6_K packed grid sweep %s grid %d ncols %d: %.1f us (%.1f-%.1f)\n",
3346                                 what, grid, nc, tc[3], tc[0], tc[6]);
3347                }
3348            }
3349            g_q6p_grid_override = 0;
3350        }
3351        dpct::destroy_event(e0); dpct::destroy_event(e1);
3352        sycl::free(dx, dpct::get_in_order_queue());
3353            sycl::free(ya, dpct::get_in_order_queue());
3354            sycl::free(yb, dpct::get_in_order_queue());
3355        dpct::get_current_device().destroy_queue(s);
3356        if (!same) { native_q6_k_unpack(weights); return false; }
3357    }
3358    return true;
3359}
3360catch (sycl::exception const &exc) {
3361  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
3362            << ", line:" << __LINE__ << std::endl;
3363  std::exit(1);
3364}
3365
3366void native_q6_k_unpack(const void* weights) {
3367    q6_planar_registry().erase(weights);   // planar matrices are the caller's allocation (native_q6_k_planar_adopt): the caller frees it
3368    auto& registry = q6_packed_registry();
3369    const auto found = registry.find(weights);
3370    if (found == registry.end()) return;
3371    sycl::free(found->second.base, dpct::get_in_order_queue());
3372    registry.erase(found);
3373}
3374
3375void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; }
3376void native_mmvq_set_q6k_wide(bool on) { g_q6k_wide = on; }
3377void native_q6_k_mmvq_stride224(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols,
3378                                void* stream) {
3379    const auto s = strata::q_of(stream);
3380    switch (ncols) {
3381        case 1: launch_q6k_wide224<1>(weights, x_q8_1, y, n_in, n_out, s); return;
3382        case 2: launch_q6k_wide224<2>(weights, x_q8_1, y, n_in, n_out, s); return;
3383        case 3: launch_q6k_wide224<3>(weights, x_q8_1, y, n_in, n_out, s); return;
3384        case 4: launch_q6k_wide224<4>(weights, x_q8_1, y, n_in, n_out, s); return;
3385        default: launch_q6k_wide224<6>(weights, x_q8_1, y, n_in, n_out, s); return;
3386    }
3387}
3388bool native_mmvq_multi_exact() { return g_multi_exact; }
3389
3390std::size_t native_q8_1_bytes(int n_in, int ncols) {
3391    validate_shape(n_in, ncols);
3392    return std::size_t(ncols) * std::size_t(n_in / Q8K) * sizeof(Q81Block);
3393}
3394
3395void native_quantize_q8_1(const float* x, void* x_q8_1, int n_in, int ncols, void* stream) {
3396    validate_shape(n_in, ncols);
3397    validate_pointer(x);
3398    validate_pointer(x_q8_1);
3399    validate_stream(stream);
3400    // Columns are contiguous and n_in is a multiple of 32, so ncols columns quantize as one vector of
3401    // ncols * n_in elements: every 32-element block stays inside one column.
3402    const int n_total = n_in * ncols;
3403    const unsigned blocks = unsigned((std::size_t(n_total) + QUANT_THREADS - 1) / QUANT_THREADS);
3404    {
3405        auto exp_props = sycl::ext::oneapi::experimental::properties{
3406            sycl::ext::oneapi::experimental::use_root_sync};
3407
3408        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
3409            ->template parallel_for<
3410                dpct_kernel_name<class native_quantize_q8_1_kernel_b480d2>>(
3411                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
3412                                      sycl::range(1, 1, QUANT_THREADS),
3413                                  sycl::range(1, 1, QUANT_THREADS)),
3414                exp_props,
3415                [=](sycl::nd_item<3> item_ct1)
3416                    [[sycl::reqd_sub_group_size(32)]] {
3417                        native_quantize_q8_1_kernel(
3418                            x, static_cast<Q81Block *>(x_q8_1), n_total);
3419                    });
3420    }
3421    launch_check();
3422}
3423
3424void native_swiglu_quantize_q8_1(const float* gate, const float* up, void* x_q8_1,
3425                                 int n_in, int ncols, void* stream) {
3426    validate_shape(n_in, ncols);
3427    validate_pointer(gate);
3428    validate_pointer(up);
3429    validate_pointer(x_q8_1);
3430    validate_stream(stream);
3431    const int n_total = n_in * ncols;
3432    const unsigned blocks = unsigned((std::size_t(n_total) + QUANT_THREADS - 1) / QUANT_THREADS);
3433    {
3434        auto exp_props = sycl::ext::oneapi::experimental::properties{
3435            sycl::ext::oneapi::experimental::use_root_sync};
3436        dpct::has_capability_or_fail(
3437            ((sycl::queue *)(strata::q_of(stream)))
3438                ->get_device(),
3439            {sycl::aspect::fp16});
3440
3441        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
3442            ->template parallel_for<dpct_kernel_name<
3443                class native_swiglu_quantize_q8_1_kernel_85e13e>>(
3444                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
3445                                      sycl::range(1, 1, QUANT_THREADS),
3446                                  sycl::range(1, 1, QUANT_THREADS)),
3447                exp_props,
3448                [=](sycl::nd_item<3> item_ct1)
3449                    [[sycl::reqd_sub_group_size(32)]] {
3450                        native_swiglu_quantize_q8_1_kernel(
3451                            gate, up, static_cast<Q81Block *>(x_q8_1), n_total);
3452                    });
3453    }
3454    launch_check();
3455}
3456
3457void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y,
3458                      int n_in, int n_out, int ncols, void* stream) {
3459    validate_shape(n_in, ncols, QK);
3460    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3461    validate_pointer(weights);
3462    validate_pointer(x_q8_1);
3463    validate_pointer(y);
3464    validate_stream(stream);
3465    if (try_wide<WideQ5K>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) { launch_check(); return; }
3466    STRATA_WAVE_MMVQ(Q5KTraits)
3467    if (ncols > 1) {
3468        launch_multi<Q5KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3469        launch_check();
3470        return;
3471    }
3472    const auto* w = static_cast<const Q5KBlock*>(weights);
3473    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3474    const auto s = strata::q_of(stream);
3475    const dpct::dim3 threads(WARP, WARPS);
3476    if (n_in / QK < VDR * WARPS * WARP / QI) {
3477        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3478        /*
3479        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3480        the limit. To get the device limit, query
3481        info::device::max_work_group_size. Adjust the work-group size if needed.
3482        */
3483        {
3484            auto exp_props = sycl::ext::oneapi::experimental::properties{
3485                sycl::ext::oneapi::experimental::use_root_sync};
3486            dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
3487
3488            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
3489                dpct_kernel_name<class native_q5_k_mmvq_kernel_b1d5a2,
3490                                 dpct_kernel_scalar<true>>>(
3491                sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),
3492                exp_props,
3493                [=](sycl::nd_item<3> item_ct1)
3494                    [[sycl::reqd_sub_group_size(32)]] {
3495                        native_q5_k_mmvq_kernel<true>(w, x, y, n_in, n_out);
3496                    });
3497        }
3498    } else {
3499        /*
3500        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3501        the limit. To get the device limit, query
3502        info::device::max_work_group_size. Adjust the work-group size if needed.
3503        */
3504        auto exp_props = sycl::ext::oneapi::experimental::properties{
3505            sycl::ext::oneapi::experimental::use_root_sync};
3506        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
3507
3508        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_q5_k_mmvq_kernel_938b09,
3509                                         dpct_kernel_scalar<false>>>(
3510            sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,
3511                              threads),
3512            exp_props,
3513            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
3514                native_q5_k_mmvq_kernel<false>(w, x, y, n_in, n_out);
3515            });
3516    }
3517    launch_check();
3518}
3519
3520void native_q5_k_f32(const void* weights, const float* x, void* scratch_q8_1,
3521                     float* y, int n_in, int n_out, int ncols, void* stream) {
3522    // Validate all outputs before enqueueing the first operation.
3523    validate_shape(n_in, ncols, QK);
3524    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3525    validate_pointer(weights);
3526    validate_pointer(x);
3527    validate_pointer(scratch_q8_1);
3528    validate_pointer(y);
3529    validate_stream(stream);
3530    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3531    native_q5_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3532}
3533
3534void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y,
3535                      int n_in, int n_out, int ncols, void* stream) {
3536    validate_shape(n_in, ncols, 64);
3537    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3538    validate_pointer(weights);
3539    validate_pointer(x_q8_1);
3540    validate_pointer(y);
3541    validate_stream(stream);
3542    STRATA_WAVE_MMVQ(Q20Traits)
3543    if (ncols > 1) {
3544        launch_multi<Q20Traits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3545        launch_check();
3546        return;
3547    }
3548    const auto* w = static_cast<const Q20Block*>(weights);
3549    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3550    const auto s = strata::q_of(stream);
3551    const dpct::dim3 threads(WARP, WARPS);
3552    if (n_in / 64 < WARPS * WARP / 2) {
3553        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3554        /*
3555        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3556        the limit. To get the device limit, query
3557        info::device::max_work_group_size. Adjust the work-group size if needed.
3558        */
3559        {
3560            auto exp_props = sycl::ext::oneapi::experimental::properties{
3561                sycl::ext::oneapi::experimental::use_root_sync};
3562
3563            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
3564                dpct_kernel_name<class native_q2_0_mmvq_kernel_dec305,
3565                                 dpct_kernel_scalar<true>>>(
3566                sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),
3567                exp_props,
3568                [=](sycl::nd_item<3> item_ct1)
3569                    [[sycl::reqd_sub_group_size(32)]] {
3570                        native_q2_0_mmvq_kernel<true>(w, x, y, n_in, n_out);
3571                    });
3572        }
3573    } else {
3574        /*
3575        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3576        the limit. To get the device limit, query
3577        info::device::max_work_group_size. Adjust the work-group size if needed.
3578        */
3579        auto exp_props = sycl::ext::oneapi::experimental::properties{
3580            sycl::ext::oneapi::experimental::use_root_sync};
3581
3582        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_q2_0_mmvq_kernel_ef5f5c,
3583                                         dpct_kernel_scalar<false>>>(
3584            sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,
3585                              threads),
3586            exp_props,
3587            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
3588                native_q2_0_mmvq_kernel<false>(w, x, y, n_in, n_out);
3589            });
3590    }
3591    launch_check();
3592}
3593
3594void native_q2_0_f32(const void* weights, const float* x, void* scratch_q8_1,
3595                     float* y, int n_in, int n_out, int ncols, void* stream) {
3596    validate_shape(n_in, ncols, 64);
3597    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3598    validate_pointer(weights);
3599    validate_pointer(x);
3600    validate_pointer(scratch_q8_1);
3601    validate_pointer(y);
3602    validate_stream(stream);
3603    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3604    native_q2_0_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3605}
3606
3607void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y,
3608                      int n_in, int n_out, int ncols, void* stream) {
3609    validate_shape(n_in, ncols, 256);
3610    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3611    validate_pointer(weights);
3612    validate_pointer(x_q8_1);
3613    validate_pointer(y);
3614    validate_stream(stream);
3615    STRATA_WAVE_MMVQ(Q3KTraits)
3616    if (ncols > 1) {
3617        launch_multi<Q3KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3618        launch_check();
3619        return;
3620    }
3621    const auto* w = static_cast<const Q3KBlock*>(weights);
3622    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3623    const auto s = strata::q_of(stream);
3624    const dpct::dim3 threads(WARP, WARPS);
3625    if (n_in / 256 < WARPS * WARP / 16) {
3626        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3627        /*
3628        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3629        the limit. To get the device limit, query
3630        info::device::max_work_group_size. Adjust the work-group size if needed.
3631        */
3632        {
3633            auto exp_props = sycl::ext::oneapi::experimental::properties{
3634                sycl::ext::oneapi::experimental::use_root_sync};
3635
3636            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
3637                dpct_kernel_name<class native_q3_k_mmvq_kernel_208be9,
3638                                 dpct_kernel_scalar<true>>>(
3639                sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),
3640                exp_props,
3641                [=](sycl::nd_item<3> item_ct1)
3642                    [[sycl::reqd_sub_group_size(32)]] {
3643                        native_q3_k_mmvq_kernel<true>(w, x, y, n_in, n_out);
3644                    });
3645        }
3646    } else {
3647        /*
3648        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3649        the limit. To get the device limit, query
3650        info::device::max_work_group_size. Adjust the work-group size if needed.
3651        */
3652        auto exp_props = sycl::ext::oneapi::experimental::properties{
3653            sycl::ext::oneapi::experimental::use_root_sync};
3654
3655        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_q3_k_mmvq_kernel_926817,
3656                                         dpct_kernel_scalar<false>>>(
3657            sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,
3658                              threads),
3659            exp_props,
3660            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
3661                native_q3_k_mmvq_kernel<false>(w, x, y, n_in, n_out);
3662            });
3663    }
3664    launch_check();
3665}
3666
3667void native_q3_k_f32(const void* weights, const float* x, void* scratch_q8_1,
3668                     float* y, int n_in, int n_out, int ncols, void* stream) {
3669    validate_shape(n_in, ncols, 256);
3670    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3671    validate_pointer(weights);
3672    validate_pointer(x);
3673    validate_pointer(scratch_q8_1);
3674    validate_pointer(y);
3675    validate_stream(stream);
3676    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3677    native_q3_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3678}
3679
3680void b60_iq4_soa_probe(bool,const void*,const void*,float*,int,int,int,void*);
3681void b60_iq4_int4_probe(bool,const void*,const void*,float*,int,int,int,void*);
3682void b60_iq4_head_soa_probe(bool,const void*,const void*,float*,int,int,int,void*);
3683inline bool b60_next_mmvq_pool(){static const bool on=[] {const char*p=std::getenv("STRATA_PRIVATE_B60_NEXT_POOL");return p&&p[0]=='1';}();return on;}
3684void b60_iq4_leaf_pairs_probe(bool,const void*,const void*,float*,int,int,int,void*);
3685void b60_iq4_head_leaf_pairs_probe(bool,const void*,const void*,float*,int,int,int,void*);
3686void b60_iq4_head_leaf_quartets_probe(bool,const void*,const void*,float*,int,int,int,void*);
3687
3688void b60_iq4_ssm_soa_probe(bool,const void*,const void*,float*,int,int,int,void*);
3689void launch_iq4_pair_reuse(int,const void*,const void*,float*,int,int,int,void*);
3690void launch_iq4_q8_split(int,const void*,const void*,float*,int,int,int,void*);
3691static void launch_iq4_esimd_t4(int,const void*,const void*,float*,int,int,int,void*);
3692void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y,
3693                       int n_in, int n_out, int ncols, void* stream) {
3694    validate_shape(n_in, ncols, 256);
3695    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3696    validate_pointer(weights);
3697    validate_pointer(x_q8_1);
3698    validate_pointer(y);
3699    validate_stream(stream);
3700
3701    if(b60_cache_requested(23) && b60_main_actor() && b60_weights_packed() && n_in==2560 &&
3702       (n_out==6144||n_out==12288) && (ncols==1||ncols==2||ncols==4) &&
3703       strata::intel_gpu_gen(strata::q_of(stream)->get_device())==strata::IntelGpuGen::Battlemage){
3704        const void* cached=b60_cached_weight(weights,23);
3705        if(!cached)throw std::logic_error("B60 missing SSM IQ4 decode cache");
3706        b60_iq4_ssm_soa_probe(true,cached,x_q8_1,y,n_in,n_out,ncols,stream);return;
3707    }
3708    if(b60_cache_requested(24) && (b60_weights_packed()||(b60_single_actor_requested()&&!b60_main_actor())) && n_in==2560 &&
3709       ((b60_main_actor()&&n_out==248320&&ncols==4)||(!b60_main_actor()&&n_out==106299&&ncols==1)) &&
3710       strata::intel_gpu_gen(strata::q_of(stream)->get_device())==strata::IntelGpuGen::Battlemage){
3711        const void* cached=b60_cached_weight(weights,24);
3712        if(!cached)throw std::logic_error("B60 missing exact head decode cache");
3713        if(b60_next_mmvq_pool()&&n_out==106299&&ncols==1&&(b60_single_actor_requested()||(b60_single_actor_requested()||strata::q_of(stream)->get_device()==static_cast<const sycl::device&>(dpct::get_device(1)))))b60_iq4_head_leaf_pairs_probe(true,cached,x_q8_1,y,n_in,n_out,ncols,stream);
3714        else         if(b60_next_mmvq_pool()&&n_out==248320&&ncols==4&&(b60_single_actor_requested()||strata::q_of(stream)->get_device()==static_cast<const sycl::device&>(dpct::get_device(1))))b60_iq4_head_leaf_quartets_probe(true,cached,x_q8_1,y,n_in,n_out,ncols,stream);
3715        else b60_iq4_head_soa_probe(true,cached,x_q8_1,y,n_in,n_out,ncols,stream);return;
3716    }
3717    static const bool exact_int4=[] {const char*p=std::getenv("STRATA_PRIVATE_IQ4_INT4_DPAS");return p&&p[0]=='1';}();
3718    if(exact_int4 && b60_weights_packed() &&
3719       strata::intel_gpu_gen(strata::q_of(stream)->get_device())==strata::IntelGpuGen::Battlemage){
3720        const bool main=b60_main_actor();
3721        const bool dense=main && ((n_in==2560&&n_out==10240)||(n_in==6144&&n_out==2560)) && (ncols==1||ncols==2||ncols==4);
3722        const bool head=main && n_in==2560 && n_out==248320 && ncols==4;
3723        const bool draft=!main && n_in==2560 && n_out==106299 && ncols==1;
3724        if(dense||head||draft){
3725            if(dense&&ncols==4&&b60_next_mmvq_pool()&&((n_in==6144&&n_out==2560&&(!b60_single_actor_requested()&&strata::q_of(stream)->get_device()==static_cast<const sycl::device&>(dpct::get_device(0)))) || (n_in==6144&&n_out==2560&&(b60_single_actor_requested()||strata::q_of(stream)->get_device()==static_cast<const sycl::device&>(dpct::get_device(1)))) || (n_in==2560&&n_out==10240&&(!b60_single_actor_requested()&&strata::q_of(stream)->get_device()==static_cast<const sycl::device&>(dpct::get_device(0)))) || (n_in==2560&&n_out==10240&&(b60_single_actor_requested()||strata::q_of(stream)->get_device()==static_cast<const sycl::device&>(dpct::get_device(1)))))){
3726                b60_iq4_leaf_pairs_probe(true,weights,x_q8_1,y,n_in,n_out,ncols,stream);return;
3727            }
3728            b60_iq4_int4_probe(true,weights,x_q8_1,y,n_in,n_out,ncols,stream);return;
3729        }
3730    }
3731    if(b60_main_actor() && b60_weights_packed() &&
3732       ((n_in==2560&&n_out==10240)||(n_in==6144&&n_out==2560))){
3733        if(ncols<1||ncols>6)throw std::invalid_argument("B60 packed dense token count");
3734        b60_iq4_soa_probe(true,weights,x_q8_1,y,n_in,n_out,ncols,stream);return;
3735    }
3736    static const bool pair_reuse = [] {
3737        const char* v = std::getenv("STRATA_SYCL_IQ4_PAIR_REUSE");
3738        return !v || v[0] == '1';
3739    }();
3740    static const bool split = [] {
3741        const char* v = std::getenv("STRATA_SYCL_IQ4_Q8_SPLIT");
3742        return !v || v[0] == '1';
3743    }();
3744    static const bool use_bit_select = [] {
3745        const char* v = std::getenv("STRATA_SYCL_IQ4_LOOKUP");
3746        return !v || std::atoi(v) != 0;
3747    }();
3748    const bool bmg = ncols >= 1 && ncols <= 6 &&
3749        strata::intel_gpu_gen(strata::q_of(stream)->get_device()) == strata::IntelGpuGen::Battlemage;
3750    if(pair_reuse&&bmg&&ncols<=4&&(n_in==2560||n_in==6144)&&
3751       !(ncols==1&&n_in==2560&&n_out==640)&&
3752       !(reinterpret_cast<uintptr_t>(weights)&63)&&!(reinterpret_cast<uintptr_t>(x_q8_1)&63)){
3753        const bool selected=(n_in==2560&&n_out==10240&&ncols==4)||(n_in==6144&&n_out==2560&&ncols==4)||(n_in==2560&&n_out==106299&&ncols==1);
3754        if(split&&selected)launch_iq4_q8_split(1,weights,x_q8_1,y,n_in,n_out,ncols,stream);
3755        else launch_iq4_pair_reuse(1,weights,x_q8_1,y,n_in,n_out,ncols,stream);
3756        return;
3757    }
3758    static const bool esimd_t4=[](){const char* e=std::getenv("STRATA_SYCL_IQ4_T4_ESIMD");return e&&e[0]=='1';}();
3759    if(esimd_t4&&bmg&&ncols==4&&(n_in==2560||n_in==6144)&&
3760       !(reinterpret_cast<uintptr_t>(weights)&63)&&!(reinterpret_cast<uintptr_t>(x_q8_1)&63)){
3761        launch_iq4_esimd_t4(1,weights,x_q8_1,y,n_in,n_out,ncols,stream);
3762        launch_check();return;
3763    }
3764    static const bool selective = [] { const char* e=std::getenv("STRATA_SYCL_IQ4_T4_XMX");return e && e[0]=='1'; }();
3765    const bool supported=(n_in==2560 && (n_out==6144 || n_out==10240 || n_out==12288 || n_out==248320)) || (n_in==6144 && n_out==2560);
3766    if(selective && bmg && ncols==4 && supported){
3767        auto* bytes=static_cast<const uint8_t*>(weights);auto* activation=static_cast<const Q81Block*>(x_q8_1);auto* q=strata::q_of(stream);
3768        if(n_in==2560)iq4_xmx_virtual_T<10>(ncols,bytes,activation,y,n_out,q);
3769        else iq4_xmx_virtual_T<24>(ncols,bytes,activation,y,n_out,q);
3770        launch_check();return;
3771    }
3772    if (use_bit_select && bmg && (n_in == 2560 || n_in == 6144) &&
3773        try_wide<WideIQ4Lookup>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) {
3774        launch_check(); return;
3775    }
3776    if (try_wide<WideIQ4XS>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) { launch_check(); return; }
3777    STRATA_WAVE_MMVQ(IQ4XSTraits)
3778    if (ncols > 1) {
3779        launch_multi<IQ4XSTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3780        launch_check();
3781        return;
3782    }
3783    const auto* w = static_cast<const IQ4XSBlock*>(weights);
3784    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3785    const auto s = strata::q_of(stream);
3786    const dpct::dim3 threads(WARP, WARPS);
3787    if (n_in / 256 < 4 * WARPS * WARP / 32) {
3788        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3789        /*
3790        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3791        the limit. To get the device limit, query
3792        info::device::max_work_group_size. Adjust the work-group size if needed.
3793        */
3794        {
3795            iq4nl_values.init(*s);
3796
3797            auto exp_props = sycl::ext::oneapi::experimental::properties{
3798                sycl::ext::oneapi::experimental::use_root_sync};
3799
3800            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3801                auto iq4nl_values_ptr_ct1 = iq4nl_values.get_ptr();
3802
3803                cgh.parallel_for<
3804                    dpct_kernel_name<class native_iq4_xs_mmvq_kernel_22a688,
3805                                     dpct_kernel_scalar<true>>>(
3806                    sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads,
3807                                      threads),
3808                    exp_props,
3809                    [=](sycl::nd_item<3> item_ct1)
3810                        [[sycl::reqd_sub_group_size(32)]] {
3811                            native_iq4_xs_mmvq_kernel<true>(
3812                                w, x, y, n_in, n_out, iq4nl_values_ptr_ct1);
3813                        });
3814            });
3815        }
3816    } else {
3817        /*
3818        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3819        the limit. To get the device limit, query
3820        info::device::max_work_group_size. Adjust the work-group size if needed.
3821        */
3822        iq4nl_values.init(*s);
3823
3824        auto exp_props = sycl::ext::oneapi::experimental::properties{
3825            sycl::ext::oneapi::experimental::use_root_sync};
3826
3827        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
3828            auto iq4nl_values_ptr_ct1 = iq4nl_values.get_ptr();
3829
3830            cgh.parallel_for<
3831                dpct_kernel_name<class native_iq4_xs_mmvq_kernel_3ba00d,
3832                                 dpct_kernel_scalar<false>>>(
3833                sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,
3834                                  threads),
3835                exp_props,
3836                [=](sycl::nd_item<3> item_ct1)
3837                    [[sycl::reqd_sub_group_size(32)]] {
3838                        native_iq4_xs_mmvq_kernel<false>(w, x, y, n_in, n_out,
3839                                                         iq4nl_values_ptr_ct1);
3840                    });
3841        });
3842    }
3843    launch_check();
3844}
3845
3846void native_iq4_xs_f32(const void* weights, const float* x, void* scratch_q8_1,
3847                      float* y, int n_in, int n_out, int ncols, void* stream) {
3848    validate_shape(n_in, ncols, 256);
3849    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3850    validate_pointer(weights);
3851    validate_pointer(x);
3852    validate_pointer(scratch_q8_1);
3853    validate_pointer(y);
3854    validate_stream(stream);
3855    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3856    native_iq4_xs_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3857}
3858
3859void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y,
3860                      int n_in, int n_out, int ncols, void* stream) {
3861    validate_shape(n_in, ncols, 256);
3862    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3863    validate_pointer(weights);
3864    validate_pointer(x_q8_1);
3865    validate_pointer(y);
3866    validate_stream(stream);
3867    if (try_wide<WideQ4K>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) { launch_check(); return; }
3868    STRATA_WAVE_MMVQ(Q4KTraits)
3869    if (ncols > 1) {
3870        launch_multi<Q4KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3871        launch_check();
3872        return;
3873    }
3874    const auto* w = static_cast<const Q4KBlock*>(weights);
3875    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3876    const auto s = strata::q_of(stream);
3877    const dpct::dim3 threads(WARP, WARPS);
3878    if (n_in / 256 < WARPS * WARP / 16) {
3879        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3880        /*
3881        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3882        the limit. To get the device limit, query
3883        info::device::max_work_group_size. Adjust the work-group size if needed.
3884        */
3885        {
3886            auto exp_props = sycl::ext::oneapi::experimental::properties{
3887                sycl::ext::oneapi::experimental::use_root_sync};
3888            dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
3889
3890            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
3891                dpct_kernel_name<class native_q4_k_mmvq_kernel_da128d,
3892                                 dpct_kernel_scalar<true>>>(
3893                sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),
3894                exp_props,
3895                [=](sycl::nd_item<3> item_ct1)
3896                    [[sycl::reqd_sub_group_size(32)]] {
3897                        native_q4_k_mmvq_kernel<true>(w, x, y, n_in, n_out);
3898                    });
3899        }
3900    } else {
3901        /*
3902        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3903        the limit. To get the device limit, query
3904        info::device::max_work_group_size. Adjust the work-group size if needed.
3905        */
3906        auto exp_props = sycl::ext::oneapi::experimental::properties{
3907            sycl::ext::oneapi::experimental::use_root_sync};
3908        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
3909
3910        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_q4_k_mmvq_kernel_b29f4f,
3911                                         dpct_kernel_scalar<false>>>(
3912            sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,
3913                              threads),
3914            exp_props,
3915            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
3916                native_q4_k_mmvq_kernel<false>(w, x, y, n_in, n_out);
3917            });
3918    }
3919    launch_check();
3920}
3921
3922void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1,
3923                     float* y, int n_in, int n_out, int ncols, void* stream) {
3924    validate_shape(n_in, ncols, 256);
3925    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3926    validate_pointer(weights);
3927    validate_pointer(x);
3928    validate_pointer(scratch_q8_1);
3929    validate_pointer(y);
3930    validate_stream(stream);
3931    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3932    native_q4_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3933}
3934
3935void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y,
3936                      int n_in, int n_out, int ncols, void* stream) {
3937    if (q6_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return;   // STRATA_Q6_PACKED=1 heads
3938    if (q6_planar_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return;   // STRATA_Q6_PLANAR copies
3939    // SYCL port: 16-byte-load kernel for the decode shapes (ncols <= 4)
3940    // With the aligned loads (load16_a2) the wide kernel wins on every Q6_K shape and window width: 2.6-3.4x the
3941    // misaligned-load kernels in q6k_align_bench, decode 44.9 -> 54 tok/s on the Coder, output tokens identical.
3942    // Without them (STRATA_MMVQ_A2=0) it won only on n_out >= 4096 at 1-4 columns, the old gate.
3943    static const int wide_min = std::getenv("STRATA_MMVQ_WIDE_MIN") ? std::atoi(std::getenv("STRATA_MMVQ_WIDE_MIN")) : q6k_a2() ? 0 : 4096;
3944    static const int wide_maxc = std::getenv("STRATA_MMVQ_WIDE_MAXC") ? std::atoi(std::getenv("STRATA_MMVQ_WIDE_MAXC")) : q6k_a2() ? 8 : 4;
3945    if (g_q6k_wide && ncols >= 1 && ncols <= wide_maxc && n_in % 256 == 0 && n_out >= wide_min) {
3946        const auto s = strata::q_of(stream);
3947        switch (ncols) {
3948            case 1: launch_q6k_wide<1>(weights, x_q8_1, y, n_in, n_out, s); return;
3949            case 2: launch_q6k_wide<2>(weights, x_q8_1, y, n_in, n_out, s); return;
3950            case 3: launch_q6k_wide<3>(weights, x_q8_1, y, n_in, n_out, s); return;
3951            case 4: launch_q6k_wide<4>(weights, x_q8_1, y, n_in, n_out, s); return;
3952            case 5: launch_q6k_wide<5>(weights, x_q8_1, y, n_in, n_out, s); return;
3953            case 6: launch_q6k_wide<6>(weights, x_q8_1, y, n_in, n_out, s); return;
3954            case 7: launch_q6k_wide<7>(weights, x_q8_1, y, n_in, n_out, s); return;
3955            default: launch_q6k_wide<8>(weights, x_q8_1, y, n_in, n_out, s); return;
3956        }
3957    }
3958    // SYCL port: the row-blocked kernel for the decode shapes (ncols <= 4)
3959    if (ncols >= 1 && ncols <= 4 && rowwarp_rpw() > 0 && n_in % 256 == 0) {
3960        dpct::queue_ptr s = strata::q_of(stream);
3961        const int rpw = rowwarp_rpw();
3962#define STRATA_RW(NC, RP) if (ncols == NC && rpw == RP) { launch_rowwarp<Q6KTraits, NC, RP>(weights, x_q8_1, y, n_in, n_out, s); return; }
3963        STRATA_RW(1, 1) STRATA_RW(1, 2) STRATA_RW(1, 4) STRATA_RW(2, 1) STRATA_RW(2, 2) STRATA_RW(2, 4)
3964        STRATA_RW(3, 1) STRATA_RW(3, 2) STRATA_RW(3, 4) STRATA_RW(4, 1) STRATA_RW(4, 2) STRATA_RW(4, 4)
3965#undef STRATA_RW
3966    }
3967
3968    validate_shape(n_in, ncols, 256);
3969    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3970    validate_pointer(weights);
3971    validate_pointer(x_q8_1);
3972    validate_pointer(y);
3973    validate_stream(stream);
3974    STRATA_WAVE_MMVQ(Q6KTraits)
3975    if (ncols > 1) {
3976        launch_multi<Q6KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3977        launch_check();
3978        return;
3979    }
3980    const auto* w = static_cast<const Q6KBlock*>(weights);
3981    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3982    const auto s = strata::q_of(stream);
3983    const dpct::dim3 threads(WARP, WARPS);
3984    if (n_in / 256 < WARPS * WARP / 32) {
3985        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3986        /*
3987        DPCT1049: The work-group size passed to the SYCL kernel may exceed
3988        the limit. To get the device limit, query
3989        info::device::max_work_group_size. Adjust the work-group size if needed.
3990        */
3991        {
3992            auto exp_props = sycl::ext::oneapi::experimental::properties{
3993                sycl::ext::oneapi::experimental::use_root_sync};
3994
3995            strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<
3996                dpct_kernel_name<class native_q6_k_mmvq_kernel_4d887f,
3997                                 dpct_kernel_scalar<true>>>(
3998                sycl::nd_range<3>(sycl::range(1, 1, blocks) * threads, threads),
3999                exp_props,
4000                [=](sycl::nd_item<3> item_ct1)
4001                    [[sycl::reqd_sub_group_size(32)]] {
4002                        native_q6_k_mmvq_kernel<true>(w, x, y, n_in, n_out);
4003                    });
4004        }
4005    } else {
4006        /*
4007        DPCT1049: The work-group size passed to the SYCL kernel may exceed
4008        the limit. To get the device limit, query
4009        info::device::max_work_group_size. Adjust the work-group size if needed.
4010        */
4011        auto exp_props = sycl::ext::oneapi::experimental::properties{
4012            sycl::ext::oneapi::experimental::use_root_sync};
4013
4014        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<class native_q6_k_mmvq_kernel_19484e,
4015                                         dpct_kernel_scalar<false>>>(
4016            sycl::nd_range<3>(sycl::range(1, 1, unsigned(n_out)) * threads,
4017                              threads),
4018            exp_props,
4019            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
4020                native_q6_k_mmvq_kernel<false>(w, x, y, n_in, n_out);
4021            });
4022    }
4023    launch_check();
4024}
4025
4026void native_q6_k_f32(const void* weights, const float* x, void* scratch_q8_1,
4027                     float* y, int n_in, int n_out, int ncols, void* stream) {
4028    validate_shape(n_in, ncols, 256);
4029    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
4030    validate_pointer(weights);
4031    validate_pointer(x);
4032    validate_pointer(scratch_q8_1);
4033    validate_pointer(y);
4034    validate_stream(stream);
4035    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
4036    native_q6_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
4037}
4038
4039void native_q4_0_mmvq(const void* weights, const void* x_q8_1, float* y,
4040                       int n_in, int n_out, int ncols, void* stream) {
4041    small_mmvq<Q40Block, 4>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
4042}
4043
4044void native_q4_0_f32(const void* weights, const float* x, void* scratch_q8_1,
4045                      float* y, int n_in, int n_out, int ncols, void* stream) {
4046    small_f32<Q40Block, 4>(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream);
4047}
4048
4049void native_q5_0_mmvq(const void* weights, const void* x_q8_1, float* y,
4050                       int n_in, int n_out, int ncols, void* stream) {
4051    small_mmvq<Q50Block, 4>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
4052}
4053
4054void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1,
4055                      float* y, int n_in, int n_out, int ncols, void* stream) {
4056    small_f32<Q50Block, 4>(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream);
4057}
4058
4059template <int NCOLS>
4060void q8_0_pair_launch(const Q80Block *w1, const Q80Block *w2, const Q81Block *x,
4061                      float *y1, float *y2, int n_in, int n_out,
4062                      dpct::queue_ptr s) {
4063    using F = SmallTraits<Q80Block, 8>;
4064    const dpct::dim3 threads(WARP, WARPS);
4065    if (s26_tsum_on())
4066        /*
4067        DPCT1049: The work-group size passed to the SYCL kernel may exceed
4068        the limit. To get the device limit, query
4069        info::device::max_work_group_size. Adjust the work-group size if needed.
4070        */
4071    {
4072        auto exp_props = sycl::ext::oneapi::experimental::properties{
4073            sycl::ext::oneapi::experimental::use_root_sync};
4074        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
4075
4076        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
4077            class native_mmvq_multi_kernel_ab153b, F, dpct_kernel_scalar<NCOLS>,
4078            dpct_kernel_scalar<WARPS>, dpct_kernel_scalar<1>,
4079            dpct_kernel_scalar<true>, dpct_kernel_scalar<true>>>(
4080            sycl::nd_range<3>(sycl::range(1, 1, unsigned(2 * n_out)) * threads,
4081                              threads),
4082            exp_props,
4083            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
4084                native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, true, true>(
4085                    w1, x, y1, n_in, n_out, w2, y2);
4086            });
4087    } else
4088    /*
4089    DPCT1049: The work-group size passed to the SYCL kernel may exceed
4090    the limit. To get the device limit, query
4091    info::device::max_work_group_size. Adjust the work-group size if needed.
4092    */
4093    {
4094        auto exp_props = sycl::ext::oneapi::experimental::properties{
4095            sycl::ext::oneapi::experimental::use_root_sync};
4096        dpct::has_capability_or_fail(s->get_device(), {sycl::aspect::fp16});
4097
4098        strata::kprof::kp(s, __FILE__, __func__, __LINE__)->template parallel_for<dpct_kernel_name<
4099            class native_mmvq_multi_kernel_50d9c5, F, dpct_kernel_scalar<NCOLS>,
4100            dpct_kernel_scalar<WARPS>, dpct_kernel_scalar<1>,
4101            dpct_kernel_scalar<false>, dpct_kernel_scalar<true>>>(
4102            sycl::nd_range<3>(sycl::range(1, 1, unsigned(2 * n_out)) * threads,
4103                              threads),
4104            exp_props,
4105            [=](sycl::nd_item<3> item_ct1) [[sycl::reqd_sub_group_size(32)]] {
4106                native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, false, true>(
4107                    w1, x, y1, n_in, n_out, w2, y2);
4108            });
4109    }
4110}
4111
4112bool native_mmvq_pair(int ggml_type, const void* w1, const void* w2, const void* x_q8_1, float* y1, float* y2,
4113                      int n_in, int n_out, int ncols, void* stream) {
4114    using F = SmallTraits<Q80Block, 8>;
4115    // only where both calls would run native_mmvq_multi_kernel<F, ncols, WARPS, 1> (exact layout, not packed)
4116    if (ggml_type != 8 || !g_multi_exact || ncols < 2 || ncols > 8 || n_out <= 0 || n_in <= 0 || n_in % 32 != 0 ||
4117        n_in / F::DIV < F::BPI || !w1 || !w2 || !x_q8_1 || !y1 || !y2 || !stream)
4118        return false;
4119    const auto& reg = q8_packed_registry();
4120    if (reg.count(w1) || reg.count(w2)) return false;
4121    const auto* a = static_cast<const Q80Block*>(w1);
4122    const auto* b = static_cast<const Q80Block*>(w2);
4123    const auto* x = static_cast<const Q81Block*>(x_q8_1);
4124    const auto s = strata::q_of(stream);
4125    switch (ncols) {
4126        case 2: q8_0_pair_launch<2>(a, b, x, y1, y2, n_in, n_out, s); break;
4127        case 3: q8_0_pair_launch<3>(a, b, x, y1, y2, n_in, n_out, s); break;
4128        case 4: q8_0_pair_launch<4>(a, b, x, y1, y2, n_in, n_out, s); break;
4129        case 5: q8_0_pair_launch<5>(a, b, x, y1, y2, n_in, n_out, s); break;
4130        case 6: q8_0_pair_launch<6>(a, b, x, y1, y2, n_in, n_out, s); break;
4131        case 7: q8_0_pair_launch<7>(a, b, x, y1, y2, n_in, n_out, s); break;
4132        default: q8_0_pair_launch<8>(a, b, x, y1, y2, n_in, n_out, s); break;
4133    }
4134    launch_check();
4135    return true;
4136}
4137
4138void b60_mtp_q8_multi_soa_probe(const void*,const void*,float*,int,int,int,void*);
4139void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y,
4140                       int n_in, int n_out, int ncols, void* stream) {
4141    if(b60_mtp_q8_cache_requested()&&(b60_weights_packed()||b60_single_actor_requested())&&(ncols==1||ncols==4||ncols==8)){
4142        auto*q=strata::q_of(stream);
4143        const int device=int(dpct::get_device_id(q->get_device()));
4144        if(const void* cached=b60_cached_mtp_q8_weight(weights,n_out,n_in,ncols,device)){
4145            b60_mtp_q8_multi_soa_probe(cached,x_q8_1,y,n_in,n_out,ncols,stream);return;
4146        }
4147    }
4148    if (q8_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return;   // STRATA_Q8_PACKED=1 tensors
4149    if (try_wide32<Wide32Q8>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) { launch_check(); return; }
4150    small_mmvq<Q80Block, 8>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
4151}
4152
4153void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1,
4154                      float* y, int n_in, int n_out, int ncols, void* stream) {
4155    small_f32<Q80Block, 8>(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream);
4156}
4157
4158void native_iq4_nl_mmvq(const void* weights, const void* x_q8_1, float* y,
4159                       int n_in, int n_out, int ncols, void* stream) {
4160    if (try_wide32<Wide32IQ4NL>(weights, x_q8_1, y, n_in, n_out, ncols, stream)) { launch_check(); return; }
4161    small_mmvq<IQ4NLBlock, 4>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
4162}
4163
4164void native_iq4_nl_f32(const void* weights, const float* x, void* scratch_q8_1,
4165                      float* y, int n_in, int n_out, int ncols, void* stream) {
4166    small_f32<IQ4NLBlock, 4>(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream);
4167}
4168
4169bool native_mmvq_supported(int ggml_type) noexcept {
4170    return ggml_type == 2 || ggml_type == 6 || ggml_type == 7 || ggml_type == 8 || ggml_type == 11 ||
4171           ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 20 ||
4172           ggml_type == 23 || ggml_type == 42 || ggml_type == 16 || ggml_type == 17 || ggml_type == 18 ||
4173           ggml_type == 21 || ggml_type == 22 || ggml_type == 29;
4174}
4175
4176std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) {
4177    int block_elems, block_bytes;
4178    switch (ggml_type) {
4179    case 2: block_elems = 32; block_bytes = 18; break;
4180    case 6: block_elems = 32; block_bytes = 22; break;
4181    case 7: block_elems = 32; block_bytes = 24; break;
4182    case 8: block_elems = 32; block_bytes = 34; break;
4183    case 20: block_elems = 32; block_bytes = 18; break;
4184    case 11: block_elems = 256; block_bytes = 110; break;
4185    case 12: block_elems = 256; block_bytes = 144; break;
4186    case 13: block_elems = 256; block_bytes = 176; break;
4187    case 14: block_elems = 256; block_bytes = 210; break;
4188    case 23: block_elems = 256; block_bytes = 136; break;
4189    case 42: block_elems = 64; block_bytes = 18; break;
4190    case 16: case 17: case 18: case 21: case 22: case 29:
4191        block_elems = 256; block_bytes = (int) iq_row_bytes(ggml_type, 256); break;
4192    default: throw std::invalid_argument("unsupported native MMVQ GGML type");
4193    }
4194    validate_shape(n_in, 1, block_elems);
4195    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
4196    const std::size_t row_bytes = std::size_t(n_in / block_elems) * block_bytes;
4197    if (row_bytes > std::numeric_limits<std::size_t>::max() / std::size_t(n_out)) {
4198        throw std::length_error("native MMVQ weight byte count overflows size_t");
4199    }
4200    return row_bytes * std::size_t(n_out);
4201}
4202
4203void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* y,
4204                 int n_in, int n_out, int ncols, void* stream) {
4205    strata::workload_trace::Scope trace("decode.mmvq", stream, ncols, n_out, n_in, n_in, n_out, ggml_type);
4206    switch (ggml_type) {
4207    case 2: native_q4_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4208    case 6: native_q5_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4209    case 7: iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4210    case 8: native_q8_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4211    case 20: native_iq4_nl_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4212    case 11: native_q3_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4213    case 12: native_q4_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4214    case 13: native_q5_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4215    case 14: native_q6_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4216    case 23: native_iq4_xs_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4217    case 42: native_q2_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4218    case 16: case 17: case 18: case 21: case 22: case 29:
4219        iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
4220    default: throw std::invalid_argument("unsupported native MMVQ GGML type");
4221    }
4222}
4223
4224
4225namespace {
4226namespace i4e=sycl::ext::intel::esimd;
4227template<int L>SYCL_ESIMD_FUNCTION inline i4e::simd<uint32_t,L> iq4_e_lookup(i4e::simd<uint32_t,L> q){
4228    constexpr uint32_t table[]={0x81818181u,0x98989898u,0xadadadadu,0xbfbfbfbfu,
4229        0xcfcfcfcfu,0xddddddddu,0xeaeaeaeau,0xf6f6f6f6u,
4230        0x01010101u,0x0d0d0d0du,0x19191919u,0x26262626u,
4231        0x35353535u,0x45454545u,0x59595959u,0x71717171u};
4232    constexpr auto select=(i4e::bfn_t::x&~i4e::bfn_t::z)|(i4e::bfn_t::y&i4e::bfn_t::z);
4233    i4e::simd<uint32_t,L> mask[4],a[8],b[4],c[2];
4234#pragma unroll
4235    for(int i=0;i<4;++i){i4e::simd<uint32_t,L> bit=(q>>i)&0x01010101u;mask[i]=(bit<<8)-bit;}
4236#pragma unroll
4237    for(int i=0;i<8;++i)a[i]=i4e::bfn<select>(i4e::simd<uint32_t,L>(table[2*i]),i4e::simd<uint32_t,L>(table[2*i+1]),mask[0]);
4238#pragma unroll
4239    for(int i=0;i<4;++i)b[i]=i4e::bfn<select>(a[2*i],a[2*i+1],mask[1]);
4240#pragma unroll
4241    for(int i=0;i<2;++i)c[i]=i4e::bfn<select>(b[2*i],b[2*i+1],mask[2]);
4242    return i4e::bfn<select>(c[0],c[1],mask[3]);
4243}
4244template<int NT,int KB>class IQ4EsimdT4;
4245template<int NT,int KB>
4246void iq4_e_launch(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
4247    constexpr int NR=16,XB=KB*8,RB=KB*136;
4248    q->parallel_for<IQ4EsimdT4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
4249        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
4250            i4e::slm_init<32*NT*16*4>();
4251            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
4252            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
4253            for(int virtual_id=sid;virtual_id<32;virtual_id+=16){
4254            i4e::simd<float,16> acc[NT];
4255#pragma unroll
4256            for(int mr=0;mr<NT;++mr)acc[mr]=0.f;
4257            for(int seg=virtual_id;seg<XB;seg+=32){
4258                const int block=seg/8,part=seg%8;
4259                auto packed=i4e::load_2d<uint32_t,4,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4260                    RB-1,N-1,RB-1,block*34+2+part*4,base);
4261                auto header=i4e::load_2d<uint32_t,2,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4262                    RB-1,N-1,RB-1,block*34,base);
4263                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
4264                i4e::simd<uint16_t,16> bits=dh&0xffffu;
4265                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4266                i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
4267                i4e::simd<int32_t,16> scale=ls;scale-=32;
4268                i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
4269                const auto lo=iq4_e_lookup<64>(packed&0x0f0f0f0fu);
4270                const auto hi=iq4_e_lookup<64>((packed>>4)&0x0f0f0f0fu);
4271                i4e::simd<uint32_t,128> words;
4272                words.template select<64,1>(0)=lo;words.template select<64,1>(64)=hi;
4273                i4e::simd<int8_t,512> B=words.template bit_cast_view<int8_t>();
4274                auto a_words=i4e::load_2d<uint32_t,8,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4275                    XB*36-1,NT-1,XB*36-1,seg*9+1,0);
4276                i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
4277                i4e::simd<int32_t,NT*16> zero=0;
4278                auto C=i4e::xmx::dpas<8,NT,int32_t>(zero,B,A);
4279#pragma unroll
4280                for(int mr=0;mr<NT;++mr){
4281                    i4e::simd<uint16_t,1> dbits=reinterpret_cast<const uint16_t*>(acts)[(mr*XB+seg)*18];
4282                    i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
4283                    const float ds=dvalue[0];
4284                    i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
4285                    i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
4286                    i4e::simd<float,16> term=factor*dot;
4287                    // Keep the multiply rounded before the independent chain add.
4288                    term.merge(0.f,!valid);
4289                    const i4e::simd<float,16> next=acc[mr]+term;acc[mr].merge(next,valid);
4290                }
4291            }
4292#pragma unroll
4293            for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>(virtual_id*NT*64+mr*64,acc[mr]);
4294            }
4295            i4e::barrier();
4296            if(sid<NT){
4297                i4e::simd<float,16> p[16];
4298#pragma unroll
4299                for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
4300                                             i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
4301#pragma unroll
4302                for(int off=8;off;off/=2){
4303#pragma unroll
4304                    for(int v=0;v<off;++v)p[v]+=p[v+off];
4305                }
4306                i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
4307                i4e::scatter<float,16>(y,offsets,p[0],valid);
4308            }
4309        });
4310}
4311template<int KB>void iq4_e_T(int T,const uint8_t* w,const Q81Block* x,float* y,int N,sycl::queue* q){
4312    switch(T){
4313#define GO(t) case t:iq4_e_launch<t,KB>(w,x,y,N,q);break
4314        GO(1);GO(2);GO(3);GO(4);GO(5);GO(6);GO(7);GO(8);
4315#undef GO
4316    }
4317}
4318} // anonymous namespace
4319static void launch_iq4_esimd_t4(int mode,const void* w,const void* x,float* y,int K,int N,int T,void* stream){
4320    if(mode==0){native_mmvq(23,w,x,y,K,N,T,stream);return;}
4321    if(mode!=1||!w||!x||!y||!stream||N<1||T<1||T>8||(K!=2560&&K!=6144))
4322        throw std::invalid_argument("IQ4 ESIMD shape");
4323    if(T!=4){native_mmvq(23,w,x,y,K,N,T,stream);return;}
4324    if((reinterpret_cast<uintptr_t>(w)&63)||(reinterpret_cast<uintptr_t>(x)&63)){
4325        native_mmvq(23,w,x,y,K,N,T,stream);return;
4326    }
4327    if(K==2560)iq4_e_T<10>(T,static_cast<const uint8_t*>(w),static_cast<const Q81Block*>(x),y,N,strata::q_of(stream));
4328    else iq4_e_T<24>(T,static_cast<const uint8_t*>(w),static_cast<const Q81Block*>(x),y,N,strata::q_of(stream));
4329}
4330
4331namespace {
4332template<int NT,int KB>class IQ4PairAllT;
4333template<int NT,int KB>
4334void iq4_pair_all_t_launch(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
4335    constexpr int NR=16,XB=KB*8,RB=KB*136;
4336    q->parallel_for<IQ4PairAllT<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
4337        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
4338            i4e::slm_init<32*NT*16*4>();
4339            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
4340            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
4341            i4e::simd<float,16> acc[2][NT];
4342#pragma unroll
4343            for(int p=0;p<2;++p){
4344#pragma unroll
4345                for(int mr=0;mr<NT;++mr)acc[p][mr]=0.f;
4346            }
4347            for(int block=sid/4;block<KB;block+=4){
4348                auto header=i4e::load_2d<uint32_t,2,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4349                    RB-1,N-1,RB-1,block*34,base);
4350                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
4351                i4e::simd<uint16_t,16> bits=dh&0xffffu;
4352                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4353                {const int quarter=sid%4;
4354                    auto packed8=i4e::load_2d<uint32_t,8,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4355                        RB-1,N-1,RB-1,block*34+2+quarter*8,base);
4356#pragma unroll
4357                    for(int half=0;half<2;++half){
4358                        const int part=quarter*2+half,seg=block*8+part;
4359                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
4360                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
4361                        i4e::simd<int32_t,16> scale=ls;scale-=32;
4362                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
4363                        const auto lo=iq4_e_lookup<64>(packed&0x0f0f0f0fu);
4364                        const auto hi=iq4_e_lookup<64>((packed>>4)&0x0f0f0f0fu);
4365                        i4e::simd<uint32_t,128> words;
4366                        words.template select<64,1>(0)=lo;words.template select<64,1>(64)=hi;
4367                        i4e::simd<int8_t,512> B=words.template bit_cast_view<int8_t>();
4368                        auto a_words=i4e::load_2d<uint32_t,8,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4369                            XB*36-1,NT-1,XB*36-1,seg*9+1,0);
4370                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
4371                        i4e::simd<int32_t,NT*16> zero=0;
4372                        auto C=i4e::xmx::dpas<8,NT,int32_t>(zero,B,A);
4373#pragma unroll
4374                        for(int mr=0;mr<NT;++mr){
4375                            i4e::simd<uint16_t,1> dbits=reinterpret_cast<const uint16_t*>(acts)[(mr*XB+seg)*18];
4376                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
4377                            const float ds=dvalue[0];
4378                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
4379                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
4380                            i4e::simd<float,16> term=factor*dot;
4381                            term.merge(0.f,!valid);
4382                            const i4e::simd<float,16> next=acc[half][mr]+term;acc[half][mr].merge(next,valid);
4383                        }
4384                    }
4385                }
4386            }
4387#pragma unroll
4388            for(int part=0;part<2;++part){
4389#pragma unroll
4390                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[part][mr]);
4391            }
4392            i4e::barrier();
4393            if(sid<NT){
4394            i4e::simd<float,16> p[16];
4395#pragma unroll
4396            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
4397                i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
4398#pragma unroll
4399            for(int off=8;off;off/=2){
4400#pragma unroll
4401                for(int v=0;v<off;++v)p[v]+=p[v+off];
4402            }
4403            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
4404            i4e::scatter<float,16>(y,offsets,p[0],valid);
4405            }
4406        });
4407}
4408template<int KB>
4409void iq4_pair_all_t_dispatch(int T,const uint8_t* w,const Q81Block* x,float* y,int N,sycl::queue* q){
4410    switch(T){
4411    case 1:iq4_pair_all_t_launch<1,KB>(w,x,y,N,q);break;
4412    case 2:iq4_pair_all_t_launch<2,KB>(w,x,y,N,q);break;
4413    case 3:iq4_pair_all_t_launch<3,KB>(w,x,y,N,q);break;
4414    case 4:iq4_pair_all_t_launch<4,KB>(w,x,y,N,q);break;
4415    }
4416}
4417}
4418
4419void launch_iq4_pair_reuse(int mode,const void* w,const void* x,float* y,int K,int N,int T,void* stream){
4420    if(mode==0||T<1||T>4){native_mmvq(23,w,x,y,K,N,T,stream);return;}
4421    if(mode!=1||!w||!x||!y||!stream||N<1||(K!=2560&&K!=6144)||
4422       (reinterpret_cast<uintptr_t>(w)&63)||(reinterpret_cast<uintptr_t>(x)&63))
4423        throw std::invalid_argument("IQ4 pair reuse arguments");
4424    if(K==2560)iq4_pair_all_t_dispatch<10>(T,static_cast<const uint8_t*>(w),static_cast<const Q81Block*>(x),y,N,strata::q_of(stream));
4425    else iq4_pair_all_t_dispatch<24>(T,static_cast<const uint8_t*>(w),static_cast<const Q81Block*>(x),y,N,strata::q_of(stream));
4426    launch_check();
4427}
4428namespace {
4429template<int NT,int KB>class IQ4Q8Split;
4430template<int NT,int KB>
4431void iq4_q8_split_launch(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
4432    constexpr int NR=16,XB=KB*8,RB=KB*136;
4433    q->parallel_for<IQ4Q8Split<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
4434        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
4435            i4e::slm_init<32*NT*16*4>();
4436            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
4437            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
4438            i4e::simd<float,16> acc[2][NT];
4439#pragma unroll
4440            for(int p=0;p<2;++p){
4441#pragma unroll
4442                for(int mr=0;mr<NT;++mr)acc[p][mr]=0.f;
4443            }
4444            for(int block=sid/4;block<KB;block+=4){
4445                auto header=i4e::load_2d<uint32_t,2,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4446                    RB-1,N-1,RB-1,block*34,base);
4447                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
4448                i4e::simd<uint16_t,16> bits=dh&0xffffu;
4449                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4450                {const int quarter=sid%4;
4451                    const int first_segment=block*8+quarter*2;
4452                    auto aq=i4e::load_2d<uint32_t,16,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4453                        XB*36-1,NT-1,XB*36-1,first_segment*9,0);
4454                    auto tail=i4e::load_2d<uint32_t,2,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4455                        XB*36-1,NT-1,XB*36-1,first_segment*9+16,0);
4456                    constexpr int AP=decltype(aq)::length/NT,TP=decltype(tail)::length/NT;
4457                    static_assert(AP==16 && TP==2);
4458                    auto packed8=i4e::load_2d<uint32_t,8,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4459                        RB-1,N-1,RB-1,block*34+2+quarter*8,base);
4460#pragma unroll
4461                    for(int half=0;half<2;++half){
4462                        const int part=quarter*2+half,seg=block*8+part;
4463                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
4464                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
4465                        i4e::simd<int32_t,16> scale=ls;scale-=32;
4466                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
4467                        const auto lo=iq4_e_lookup<64>(packed&0x0f0f0f0fu);
4468                        const auto hi=iq4_e_lookup<64>((packed>>4)&0x0f0f0f0fu);
4469                        i4e::simd<uint32_t,128> words;
4470                        words.template select<64,1>(0)=lo;words.template select<64,1>(64)=hi;
4471                        i4e::simd<int8_t,512> B=words.template bit_cast_view<int8_t>();
4472                        i4e::simd<uint32_t,NT*8> a_words;
4473#pragma unroll
4474                        for(int mr=0;mr<NT;++mr){
4475                            if(half==0)a_words.template select<8,1>(mr*8)=aq.template select<8,1>(mr*AP+1);
4476                            else{
4477                                a_words.template select<6,1>(mr*8)=aq.template select<6,1>(mr*AP+10);
4478                                a_words.template select<2,1>(mr*8+6)=tail.template select<2,1>(mr*TP);
4479                            }
4480                        }
4481                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
4482                        i4e::simd<int32_t,NT*16> zero=0;
4483                        auto C=i4e::xmx::dpas<8,NT,int32_t>(zero,B,A);
4484#pragma unroll
4485                        for(int mr=0;mr<NT;++mr){
4486                            i4e::simd<uint32_t,1> dhdr=half==0?aq.template select<1,1>(mr*AP).read():aq.template select<1,1>(mr*AP+9).read();
4487                            i4e::simd<uint16_t,1> dbits=dhdr&0xffffu;
4488                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
4489                            const float ds=dvalue[0];
4490                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
4491                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
4492                            i4e::simd<float,16> term=factor*dot;
4493                            term.merge(0.f,!valid);
4494                            const i4e::simd<float,16> next=acc[half][mr]+term;acc[half][mr].merge(next,valid);
4495                        }
4496                    }
4497                }
4498            }
4499#pragma unroll
4500            for(int part=0;part<2;++part){
4501#pragma unroll
4502                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[part][mr]);
4503            }
4504            i4e::barrier();
4505            if(sid<NT){
4506            i4e::simd<float,16> p[16];
4507#pragma unroll
4508            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
4509                i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
4510#pragma unroll
4511            for(int off=8;off;off/=2){
4512#pragma unroll
4513                for(int v=0;v<off;++v)p[v]+=p[v+off];
4514            }
4515            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
4516            i4e::scatter<float,16>(y,offsets,p[0],valid);
4517            }
4518        });
4519}
4520SYCL_ESIMD_FUNCTION ESIMD_INLINE i4e::simd<uint32_t,128> iq4_soa_payload_load64(const uint8_t* p){
4521 auto words=i4e::block_load<uint64_t,64>(reinterpret_cast<const uint64_t*>(p));
4522 return words.template bit_cast_view<uint32_t>().read();
4523}
4524template<int NT,int KB>class IQ4SoASplit;
4525template<int NT,int KB>
4526void iq4_soa_split_launch(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
4527    constexpr int NR=16,XB=KB*8,RB=KB*136;
4528    q->parallel_for<IQ4SoASplit<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
4529        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
4530            i4e::slm_init<32*NT*16*4>();
4531            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
4532            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
4533            i4e::simd<float,16> acc[2][NT];
4534#pragma unroll
4535            for(int p=0;p<2;++p){
4536#pragma unroll
4537                for(int mr=0;mr<NT;++mr)acc[p][mr]=0.f;
4538            }
4539            for(int block=sid/4;block<KB;block+=4){
4540                const size_t packed_offset=(NT==1 && KB==10 && base+16>N)?0:size_t(base)*RB+block*16*136;
4541                const uint8_t* packed_block=weights+packed_offset;
4542                i4e::simd<uint32_t,32> header;
4543                if constexpr(NT==1 && KB==10){
4544                    if(base+16>N)header=i4e::load_2d<uint32_t,2,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),RB-1,N-1,RB-1,block*34,base);
4545                    else header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
4546                }else header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
4547                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
4548                i4e::simd<uint16_t,16> bits=dh&0xffffu;
4549                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4550                {const int quarter=sid%4;
4551                    const int first_segment=block*8+quarter*2;
4552                    auto aq=i4e::load_2d<uint32_t,16,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4553                        XB*36-1,NT-1,XB*36-1,first_segment*9,0);
4554                    auto tail=i4e::load_2d<uint32_t,2,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4555                        XB*36-1,NT-1,XB*36-1,first_segment*9+16,0);
4556                    constexpr int AP=decltype(aq)::length/NT,TP=decltype(tail)::length/NT;
4557                    static_assert(AP==16 && TP==2);
4558                    i4e::simd<uint32_t,128> packed8;
4559                    if constexpr(NT==1 && KB==10){
4560                        if(base+16>N)packed8=i4e::load_2d<uint32_t,8,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),RB-1,N-1,RB-1,block*34+2+quarter*8,base);
4561                        else packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
4562                    }else packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
4563#pragma unroll
4564                    for(int half=0;half<2;++half){
4565                        const int part=quarter*2+half,seg=block*8+part;
4566                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
4567                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
4568                        i4e::simd<int32_t,16> scale=ls;scale-=32;
4569                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
4570                        const auto lo=iq4_e_lookup<64>(packed&0x0f0f0f0fu);
4571                        const auto hi=iq4_e_lookup<64>((packed>>4)&0x0f0f0f0fu);
4572                        i4e::simd<uint32_t,128> words;
4573                        words.template select<64,1>(0)=lo;words.template select<64,1>(64)=hi;
4574                        i4e::simd<int8_t,512> B=words.template bit_cast_view<int8_t>();
4575                        i4e::simd<uint32_t,NT*8> a_words;
4576#pragma unroll
4577                        for(int mr=0;mr<NT;++mr){
4578                            if(half==0)a_words.template select<8,1>(mr*8)=aq.template select<8,1>(mr*AP+1);
4579                            else{
4580                                a_words.template select<6,1>(mr*8)=aq.template select<6,1>(mr*AP+10);
4581                                a_words.template select<2,1>(mr*8+6)=tail.template select<2,1>(mr*TP);
4582                            }
4583                        }
4584                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
4585                        i4e::simd<int32_t,NT*16> zero=0;
4586                        auto C=i4e::xmx::dpas<8,NT,int32_t>(zero,B,A);
4587#pragma unroll
4588                        for(int mr=0;mr<NT;++mr){
4589                            i4e::simd<uint32_t,1> dhdr=half==0?aq.template select<1,1>(mr*AP).read():aq.template select<1,1>(mr*AP+9).read();
4590                            i4e::simd<uint16_t,1> dbits=dhdr&0xffffu;
4591                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
4592                            const float ds=dvalue[0];
4593                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
4594                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
4595                            i4e::simd<float,16> term=factor*dot;
4596                            term.merge(0.f,!valid);
4597                            const i4e::simd<float,16> next=acc[half][mr]+term;acc[half][mr].merge(next,valid);
4598                        }
4599                    }
4600                }
4601            }
4602#pragma unroll
4603            for(int part=0;part<2;++part){
4604#pragma unroll
4605                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[part][mr]);
4606            }
4607            i4e::barrier();
4608            if(sid<NT){
4609            i4e::simd<float,16> p[16];
4610#pragma unroll
4611            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
4612                i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
4613#pragma unroll
4614            for(int off=8;off;off/=2){
4615#pragma unroll
4616                for(int v=0;v<off;++v)p[v]+=p[v+off];
4617            }
4618            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
4619            i4e::scatter<float,16>(y,offsets,p[0],valid);
4620            }
4621        });
4622}
4623
4624template<int KB>
4625void iq4_q8_split_dispatch(int T,const uint8_t* w,const Q81Block* x,float* y,int N,sycl::queue* q){
4626    switch(T){
4627    case 1:iq4_q8_split_launch<1,KB>(w,x,y,N,q);break;
4628    case 2:iq4_q8_split_launch<2,KB>(w,x,y,N,q);break;
4629    case 3:iq4_q8_split_launch<3,KB>(w,x,y,N,q);break;
4630    case 4:iq4_q8_split_launch<4,KB>(w,x,y,N,q);break;
4631    }
4632}
4633}
4634
4635void launch_iq4_q8_split(int mode,const void* w,const void* x,float* y,int K,int N,int T,void* stream){
4636    if(mode!=1||!w||!x||!y||!stream||N<1||T<1||T>4||(K!=2560&&K!=6144))throw std::invalid_argument("IQ4 split normal route");
4637    if(K==2560)iq4_q8_split_dispatch<10>(T,(const uint8_t*)w,(const Q81Block*)x,y,N,strata::q_of(stream));
4638    else iq4_q8_split_dispatch<24>(T,(const uint8_t*)w,(const Q81Block*)x,y,N,strata::q_of(stream));
4639    launch_check();
4640}
4641
4642
4643namespace {
4644template<int NT,int KB>class IQ4SoAPairAllT;
4645template<int NT,int KB>
4646void iq4_soa_pair_all_t_launch(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
4647    constexpr int NR=16,XB=KB*8,RB=KB*136;
4648    q->parallel_for<IQ4SoAPairAllT<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
4649        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
4650            i4e::slm_init<32*NT*16*4>();
4651            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
4652            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
4653            i4e::simd<float,16> acc[2][NT];
4654#pragma unroll
4655            for(int p=0;p<2;++p){
4656#pragma unroll
4657                for(int mr=0;mr<NT;++mr)acc[p][mr]=0.f;
4658            }
4659            for(int block=sid/4;block<KB;block+=4){
4660                const uint8_t* packed_block=weights+size_t(base)*RB+block*16*136;
4661                auto header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
4662                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
4663                i4e::simd<uint16_t,16> bits=dh&0xffffu;
4664                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4665                {const int quarter=sid%4;
4666                    auto packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
4667#pragma unroll
4668                    for(int half=0;half<2;++half){
4669                        const int part=quarter*2+half,seg=block*8+part;
4670                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
4671                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
4672                        i4e::simd<int32_t,16> scale=ls;scale-=32;
4673                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
4674                        const auto lo=iq4_e_lookup<64>(packed&0x0f0f0f0fu);
4675                        const auto hi=iq4_e_lookup<64>((packed>>4)&0x0f0f0f0fu);
4676                        i4e::simd<uint32_t,128> words;
4677                        words.template select<64,1>(0)=lo;words.template select<64,1>(64)=hi;
4678                        i4e::simd<int8_t,512> B=words.template bit_cast_view<int8_t>();
4679                        auto a_words=i4e::load_2d<uint32_t,8,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4680                            XB*36-1,NT-1,XB*36-1,seg*9+1,0);
4681                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
4682                        i4e::simd<int32_t,NT*16> zero=0;
4683                        auto C=i4e::xmx::dpas<8,NT,int32_t>(zero,B,A);
4684#pragma unroll
4685                        for(int mr=0;mr<NT;++mr){
4686                            i4e::simd<uint16_t,1> dbits=reinterpret_cast<const uint16_t*>(acts)[(mr*XB+seg)*18];
4687                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
4688                            const float ds=dvalue[0];
4689                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
4690                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
4691                            i4e::simd<float,16> term=factor*dot;
4692                            term.merge(0.f,!valid);
4693                            const i4e::simd<float,16> next=acc[half][mr]+term;acc[half][mr].merge(next,valid);
4694                        }
4695                    }
4696                }
4697            }
4698#pragma unroll
4699            for(int part=0;part<2;++part){
4700#pragma unroll
4701                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[part][mr]);
4702            }
4703            i4e::barrier();
4704            if(sid<NT){
4705            i4e::simd<float,16> p[16];
4706#pragma unroll
4707            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
4708                i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
4709#pragma unroll
4710            for(int off=8;off;off/=2){
4711#pragma unroll
4712                for(int v=0;v<off;++v)p[v]+=p[v+off];
4713            }
4714            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
4715            i4e::scatter<float,16>(y,offsets,p[0],valid);
4716            }
4717        });
4718}
4719
4720template<int KB>void iq4_soa_pair_dispatch(int T,const uint8_t*w,const Q81Block*x,float*y,int N,sycl::queue*q){
4721 switch(T){case 1:iq4_soa_pair_all_t_launch<1,KB>(w,x,y,N,q);break;case 2:iq4_soa_pair_all_t_launch<2,KB>(w,x,y,N,q);break;case 3:iq4_soa_pair_all_t_launch<3,KB>(w,x,y,N,q);break;default:throw std::invalid_argument("SoA PairAllT range");}
4722}
4723
4724}
4725namespace {
4726// T5/T6 retain the normal WideIQ4Lookup FP expression and subgroup tree.
4727inline WideIQ4Lookup::W b60_iq4_packed_wide_load(const IQ4XSBlock* weights,int row,int kb,int g,int KB){
4728 const auto* p=reinterpret_cast<const uint32_t*>(weights)+((size_t(row/16)*KB+kb)*34*16);
4729 const int lane=row&15;const uint32_t dh=p[lane],sl=p[16+lane];
4730 const uint32_t v[4]={p[(2+4*g)*16+lane],p[(3+4*g)*16+lane],p[(4+4*g)*16+lane],p[(5+4*g)*16+lane]};
4731 WideIQ4Lookup::W r;r.sb=g;int lo[4],hi[4];
4732#pragma unroll
4733 for(int i=0;i<4;++i){lo[i]=(int)iq4_decode::bit_select(v[i]&0x0f0f0f0f);hi[i]=(int)iq4_decode::bit_select((v[i]>>4)&0x0f0f0f0f);}
4734 r.lo={lo[0],lo[1],lo[2],lo[3]};r.hi={hi[0],hi[1],hi[2],hi[3]};
4735 const int ls=((sl>>(4*g))&15)|(((dh>>(16+2*g))&3)<<4);
4736 const sycl::half d=sycl::bit_cast<sycl::half>(uint16_t(dh));
4737 r.d=(float)d*(float)(ls-32);return r;
4738}
4739template <typename F, int NCOLS>
4740void b60_iq4_packed_wide_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
4741                             float* __restrict__ y, int n_in, int n_out) {
4742    auto item = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
4743    const int lane = int(item.get_local_id(2)), warp = int(item.get_local_id(1));
4744    const int row = int(item.get_group(2)) * WARPS + warp;
4745    if (row >= n_out) return;
4746    const int blocks_per_row = n_in / QK, x_stride = n_in / Q8K;
4747    const int g = lane & 7, sub = lane >> 3;
4748    const typename F::Block* wr = w + std::size_t(row) * blocks_per_row;
4749    float acc[NCOLS] = {};
4750    for (int kbx = sub; kbx < blocks_per_row; kbx += 4) {
4751        const typename F::W wv = b60_iq4_packed_wide_load(w,row,kbx,g,blocks_per_row);
4752#pragma unroll
4753        for (int j = 0; j < NCOLS; ++j) acc[j] += F::apply(wv, x + std::size_t(j) * x_stride + kbx * (QK / Q8K));
4754    }
4755    auto sg = item.get_sub_group();
4756#pragma unroll
4757    for (int j = 0; j < NCOLS; ++j) {
4758        float v = acc[j];
4759#pragma unroll
4760        for (int o = WARP / 2; o > 0; o >>= 1) v += sycl::permute_group_by_xor(sg, v, o);
4761        if (lane == 0) y[std::size_t(j) * n_out + row] = v;
4762    }
4763}
4764
4765template<int T>class B60Iq4PackedWide;
4766template<int T>void b60_iq4_packed_wide_launch(const void*w,const void*x,float*y,int K,int N,sycl::queue*q){
4767 const size_t blocks=(N+WARPS-1)/WARPS;
4768 q->parallel_for<B60Iq4PackedWide<T>>(
4769  sycl::nd_range<3>(sycl::range(1,1,blocks)*sycl::range(1,WARPS,WARP),sycl::range(1,WARPS,WARP)),
4770  [=](sycl::nd_item<3>)[[sycl::reqd_sub_group_size(32)]]{b60_iq4_packed_wide_kernel<WideIQ4Lookup,T>((const IQ4XSBlock*)w,(const Q81Block*)x,y,K,N);});
4771}
4772
4773}
4774void b60_iq4_soa_probe(bool candidate,const void* w,const void* x,float* y,int K,int N,int T,void* stream){
4775 if(!candidate){native_mmvq(23,w,x,y,K,N,T,stream);return;}
4776 auto*q=strata::q_of(stream);
4777 if(T==5){b60_iq4_packed_wide_launch<5>(w,x,y,K,N,q);return;}
4778 if(T==6){b60_iq4_packed_wide_launch<6>(w,x,y,K,N,q);return;}
4779 if(T>=1&&T<=3&&((K==2560&&N==10240)||(K==6144&&N==2560))){
4780  if(K==2560)iq4_soa_pair_dispatch<10>(T,(const uint8_t*)w,(const Q81Block*)x,y,N,q);
4781  else iq4_soa_pair_dispatch<24>(T,(const uint8_t*)w,(const Q81Block*)x,y,N,q);
4782  return;
4783 }
4784 if(K==2560&&N==10240&&T==4)iq4_soa_split_launch<4,10>((const uint8_t*)w,(const Q81Block*)x,y,N,q);
4785 else if(K==6144&&N==2560&&T==4)iq4_soa_split_launch<4,24>((const uint8_t*)w,(const Q81Block*)x,y,N,q);
4786 else if(K==2560&&N==106299&&T==1)iq4_soa_split_launch<1,10>((const uint8_t*)w,(const Q81Block*)x,y,N,q);
4787 else throw std::invalid_argument("IQ4 SoA component shape");
4788}
4789
4790namespace {
4791template<int L> SYCL_ESIMD_FUNCTION inline i4e::simd<uint32_t,L> iq4_int4_coarse(i4e::simd<uint32_t,L> q){
4792 auto q1=q>>1,q2=q>>2,q3=q>>3;
4793 auto plus=i4e::bfn<static_cast<i4e::bfn_t>(0x7e)>(q,q1,q2)&~q3&0x11111111u;
4794 auto minus=i4e::bfn<static_cast<i4e::bfn_t>(0x38)>(q,q1,q2)&q3&0x11111111u;
4795 return (q+plus-minus)^0x88888888u;
4796}
4797template<int L> SYCL_ESIMD_FUNCTION inline i4e::simd<uint32_t,L> iq4_int4_residual(i4e::simd<uint32_t,L> q){
4798 auto q1=q>>1,q2=q>>2,q3=q>>3;
4799 i4e::simd<uint32_t,L> result=0;
4800 {auto lo=i4e::bfn<static_cast<i4e::bfn_t>(61)>(q,q1,q2);
4801   auto hi=i4e::bfn<static_cast<i4e::bfn_t>(247)>(q,q1,q2);
4802   result|=(i4e::bfn<static_cast<i4e::bfn_t>(0xca)>(lo,hi,q3)&0x11111111u)<<0;}
4803 {auto lo=i4e::bfn<static_cast<i4e::bfn_t>(216)>(q,q1,q2);
4804   auto hi=i4e::bfn<static_cast<i4e::bfn_t>(8)>(q,q1,q2);
4805   result|=(i4e::bfn<static_cast<i4e::bfn_t>(0xca)>(lo,hi,q3)&0x11111111u)<<1;}
4806 {auto lo=i4e::bfn<static_cast<i4e::bfn_t>(188)>(q,q1,q2);
4807   auto hi=i4e::bfn<static_cast<i4e::bfn_t>(58)>(q,q1,q2);
4808   result|=(i4e::bfn<static_cast<i4e::bfn_t>(0xca)>(lo,hi,q3)&0x11111111u)<<2;}
4809 {auto lo=i4e::bfn<static_cast<i4e::bfn_t>(126)>(q,q1,q2);
4810   auto hi=i4e::bfn<static_cast<i4e::bfn_t>(70)>(q,q1,q2);
4811   result|=(i4e::bfn<static_cast<i4e::bfn_t>(0xca)>(lo,hi,q3)&0x11111111u)<<3;}
4812 return result;
4813}
4814template<int L> SYCL_ESIMD_FUNCTION inline i4e::simd<uint16_t,L*2> iq4_int4_vnni(i4e::simd<uint32_t,L> q){
4815 // INT4 Src1 packs eight K elements per dword; keep the 16-row dword order.
4816 // Repacking as four-element halfwords mixed adjacent output rows in source01.
4817 return q.template bit_cast_view<uint16_t>().read();
4818}
4819template<int NT,int KB>class IQ4PairAllTInt4;
4820template<int NT,int KB>
4821void iq4_pair_all_t_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
4822    constexpr int NR=16,XB=KB*8,RB=KB*136;
4823    q->parallel_for<IQ4PairAllTInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
4824        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
4825            i4e::slm_init<32*NT*16*4>();
4826            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
4827            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
4828            i4e::simd<float,16> acc[2][NT];
4829#pragma unroll
4830            for(int p=0;p<2;++p){
4831#pragma unroll
4832                for(int mr=0;mr<NT;++mr)acc[p][mr]=0.f;
4833            }
4834            for(int block=sid/4;block<KB;block+=4){
4835                auto header=i4e::load_2d<uint32_t,2,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4836                    RB-1,N-1,RB-1,block*34,base);
4837                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
4838                i4e::simd<uint16_t,16> bits=dh&0xffffu;
4839                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4840                {const int quarter=sid%4;
4841                    auto packed8=i4e::load_2d<uint32_t,8,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4842                        RB-1,N-1,RB-1,block*34+2+quarter*8,base);
4843#pragma unroll
4844                    for(int half=0;half<2;++half){
4845                        const int part=quarter*2+half,seg=block*8+part;
4846                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
4847                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
4848                        i4e::simd<int32_t,16> scale=ls;scale-=32;
4849                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
4850                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
4851                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
4852                        auto a_words=i4e::load_2d<uint32_t,8,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4853                            XB*36-1,NT-1,XB*36-1,seg*9+1,0);
4854                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
4855                        i4e::simd<int32_t,NT*16> zero=0;
4856                        i4e::simd<int8_t,NT*32> interleaved;
4857#pragma unroll
4858                        for(int mr=0;mr<NT;++mr){
4859                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
4860                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
4861                        }
4862                        using P=i4e::xmx::dpas_argument_type;
4863                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
4864                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
4865                        auto C=Cc*16+Cr;
4866#pragma unroll
4867                        for(int mr=0;mr<NT;++mr){
4868                            i4e::simd<uint16_t,1> dbits=reinterpret_cast<const uint16_t*>(acts)[(mr*XB+seg)*18];
4869                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
4870                            const float ds=dvalue[0];
4871                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
4872                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
4873                            i4e::simd<float,16> term=factor*dot;
4874                            term.merge(0.f,!valid);
4875                            const i4e::simd<float,16> next=acc[half][mr]+term;acc[half][mr].merge(next,valid);
4876                        }
4877                    }
4878                }
4879            }
4880#pragma unroll
4881            for(int part=0;part<2;++part){
4882#pragma unroll
4883                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[part][mr]);
4884            }
4885            i4e::barrier();
4886            if(sid<NT){
4887            i4e::simd<float,16> p[16];
4888#pragma unroll
4889            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
4890                i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
4891#pragma unroll
4892            for(int off=8;off;off/=2){
4893#pragma unroll
4894                for(int v=0;v<off;++v)p[v]+=p[v+off];
4895            }
4896            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
4897            i4e::scatter<float,16>(y,offsets,p[0],valid);
4898            }
4899        });
4900}
4901
4902template<int NT,int KB>class IQ4Q8SplitInt4;
4903template<int NT,int KB>
4904void iq4_q8_split_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
4905    constexpr int NR=16,XB=KB*8,RB=KB*136;
4906    q->parallel_for<IQ4Q8SplitInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
4907        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
4908            i4e::slm_init<32*NT*16*4>();
4909            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
4910            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
4911            i4e::simd<float,16> acc[2][NT];
4912#pragma unroll
4913            for(int p=0;p<2;++p){
4914#pragma unroll
4915                for(int mr=0;mr<NT;++mr)acc[p][mr]=0.f;
4916            }
4917            for(int block=sid/4;block<KB;block+=4){
4918                auto header=i4e::load_2d<uint32_t,2,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4919                    RB-1,N-1,RB-1,block*34,base);
4920                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
4921                i4e::simd<uint16_t,16> bits=dh&0xffffu;
4922                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
4923                {const int quarter=sid%4;
4924                    const int first_segment=block*8+quarter*2;
4925                    auto aq=i4e::load_2d<uint32_t,16,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4926                        XB*36-1,NT-1,XB*36-1,first_segment*9,0);
4927                    auto tail=i4e::load_2d<uint32_t,2,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
4928                        XB*36-1,NT-1,XB*36-1,first_segment*9+16,0);
4929                    constexpr int AP=decltype(aq)::length/NT,TP=decltype(tail)::length/NT;
4930                    static_assert(AP==16 && TP==2);
4931                    auto packed8=i4e::load_2d<uint32_t,8,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),
4932                        RB-1,N-1,RB-1,block*34+2+quarter*8,base);
4933#pragma unroll
4934                    for(int half=0;half<2;++half){
4935                        const int part=quarter*2+half,seg=block*8+part;
4936                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
4937                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
4938                        i4e::simd<int32_t,16> scale=ls;scale-=32;
4939                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
4940                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
4941                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
4942                        i4e::simd<uint32_t,NT*8> a_words;
4943#pragma unroll
4944                        for(int mr=0;mr<NT;++mr){
4945                            if(half==0)a_words.template select<8,1>(mr*8)=aq.template select<8,1>(mr*AP+1);
4946                            else{
4947                                a_words.template select<6,1>(mr*8)=aq.template select<6,1>(mr*AP+10);
4948                                a_words.template select<2,1>(mr*8+6)=tail.template select<2,1>(mr*TP);
4949                            }
4950                        }
4951                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
4952                        i4e::simd<int32_t,NT*16> zero=0;
4953                        i4e::simd<int8_t,NT*32> interleaved;
4954#pragma unroll
4955                        for(int mr=0;mr<NT;++mr){
4956                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
4957                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
4958                        }
4959                        using P=i4e::xmx::dpas_argument_type;
4960                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
4961                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
4962                        auto C=Cc*16+Cr;
4963#pragma unroll
4964                        for(int mr=0;mr<NT;++mr){
4965                            i4e::simd<uint32_t,1> dhdr=half==0?aq.template select<1,1>(mr*AP).read():aq.template select<1,1>(mr*AP+9).read();
4966                            i4e::simd<uint16_t,1> dbits=dhdr&0xffffu;
4967                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
4968                            const float ds=dvalue[0];
4969                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
4970                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
4971                            i4e::simd<float,16> term=factor*dot;
4972                            term.merge(0.f,!valid);
4973                            const i4e::simd<float,16> next=acc[half][mr]+term;acc[half][mr].merge(next,valid);
4974                        }
4975                    }
4976                }
4977            }
4978#pragma unroll
4979            for(int part=0;part<2;++part){
4980#pragma unroll
4981                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[part][mr]);
4982            }
4983            i4e::barrier();
4984            if(sid<NT){
4985            i4e::simd<float,16> p[16];
4986#pragma unroll
4987            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
4988                i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
4989#pragma unroll
4990            for(int off=8;off;off/=2){
4991#pragma unroll
4992                for(int v=0;v<off;++v)p[v]+=p[v+off];
4993            }
4994            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
4995            i4e::scatter<float,16>(y,offsets,p[0],valid);
4996            }
4997        });
4998}
4999
5000template<int NT,int KB>class IQ4SoASplitInt4;
5001template<int NT,int KB>
5002void iq4_soa_split_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5003    constexpr int NR=16,XB=KB*8,RB=KB*136;
5004    q->parallel_for<IQ4SoASplitInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
5005        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5006            i4e::slm_init<32*NT*16*4>();
5007            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5008            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5009            i4e::simd<float,16> acc[2][NT];
5010#pragma unroll
5011            for(int p=0;p<2;++p){
5012#pragma unroll
5013                for(int mr=0;mr<NT;++mr)acc[p][mr]=0.f;
5014            }
5015            for(int block=sid/4;block<KB;block+=4){
5016                const size_t packed_offset=(NT==1 && KB==10 && base+16>N)?0:size_t(base)*RB+block*16*136;
5017                const uint8_t* packed_block=weights+packed_offset;
5018                i4e::simd<uint32_t,32> header;
5019                if constexpr(NT==1 && KB==10){
5020                    if(base+16>N)header=i4e::load_2d<uint32_t,2,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),RB-1,N-1,RB-1,block*34,base);
5021                    else header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5022                }else header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5023                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
5024                i4e::simd<uint16_t,16> bits=dh&0xffffu;
5025                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5026                {const int quarter=sid%4;
5027                    const int first_segment=block*8+quarter*2;
5028                    auto aq=i4e::load_2d<uint32_t,16,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5029                        XB*36-1,NT-1,XB*36-1,first_segment*9,0);
5030                    auto tail=i4e::load_2d<uint32_t,2,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5031                        XB*36-1,NT-1,XB*36-1,first_segment*9+16,0);
5032                    constexpr int AP=decltype(aq)::length/NT,TP=decltype(tail)::length/NT;
5033                    static_assert(AP==16 && TP==2);
5034                    i4e::simd<uint32_t,128> packed8;
5035                    if constexpr(NT==1 && KB==10){
5036                        if(base+16>N)packed8=i4e::load_2d<uint32_t,8,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),RB-1,N-1,RB-1,block*34+2+quarter*8,base);
5037                        else packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5038                    }else packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5039#pragma unroll
5040                    for(int half=0;half<2;++half){
5041                        const int part=quarter*2+half,seg=block*8+part;
5042                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
5043                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
5044                        i4e::simd<int32_t,16> scale=ls;scale-=32;
5045                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
5046                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
5047                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
5048                        i4e::simd<uint32_t,NT*8> a_words;
5049#pragma unroll
5050                        for(int mr=0;mr<NT;++mr){
5051                            if(half==0)a_words.template select<8,1>(mr*8)=aq.template select<8,1>(mr*AP+1);
5052                            else{
5053                                a_words.template select<6,1>(mr*8)=aq.template select<6,1>(mr*AP+10);
5054                                a_words.template select<2,1>(mr*8+6)=tail.template select<2,1>(mr*TP);
5055                            }
5056                        }
5057                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
5058                        i4e::simd<int32_t,NT*16> zero=0;
5059                        i4e::simd<int8_t,NT*32> interleaved;
5060#pragma unroll
5061                        for(int mr=0;mr<NT;++mr){
5062                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
5063                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
5064                        }
5065                        using P=i4e::xmx::dpas_argument_type;
5066                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
5067                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
5068                        auto C=Cc*16+Cr;
5069#pragma unroll
5070                        for(int mr=0;mr<NT;++mr){
5071                            i4e::simd<uint32_t,1> dhdr=half==0?aq.template select<1,1>(mr*AP).read():aq.template select<1,1>(mr*AP+9).read();
5072                            i4e::simd<uint16_t,1> dbits=dhdr&0xffffu;
5073                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
5074                            const float ds=dvalue[0];
5075                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
5076                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
5077                            i4e::simd<float,16> term=factor*dot;
5078                            term.merge(0.f,!valid);
5079                            const i4e::simd<float,16> next=acc[half][mr]+term;acc[half][mr].merge(next,valid);
5080                        }
5081                    }
5082                }
5083            }
5084#pragma unroll
5085            for(int part=0;part<2;++part){
5086#pragma unroll
5087                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[part][mr]);
5088            }
5089            i4e::barrier();
5090            if(sid<NT){
5091            i4e::simd<float,16> p[16];
5092#pragma unroll
5093            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
5094                i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
5095#pragma unroll
5096            for(int off=8;off;off/=2){
5097#pragma unroll
5098                for(int v=0;v<off;++v)p[v]+=p[v+off];
5099            }
5100            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
5101            i4e::scatter<float,16>(y,offsets,p[0],valid);
5102            }
5103        });
5104}
5105
5106template<int NT,int KB>class IQ4SoAPairAllTInt4;
5107template<int NT,int KB>
5108void iq4_soa_pair_all_t_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5109    constexpr int NR=16,XB=KB*8,RB=KB*136;
5110    q->parallel_for<IQ4SoAPairAllTInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
5111        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5112            i4e::slm_init<32*NT*16*4>();
5113            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5114            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5115            i4e::simd<float,16> acc[2][NT];
5116#pragma unroll
5117            for(int p=0;p<2;++p){
5118#pragma unroll
5119                for(int mr=0;mr<NT;++mr)acc[p][mr]=0.f;
5120            }
5121            for(int block=sid/4;block<KB;block+=4){
5122                const uint8_t* packed_block=weights+size_t(base)*RB+block*16*136;
5123                auto header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5124                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
5125                i4e::simd<uint16_t,16> bits=dh&0xffffu;
5126                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5127                {const int quarter=sid%4;
5128                    auto packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5129#pragma unroll
5130                    for(int half=0;half<2;++half){
5131                        const int part=quarter*2+half,seg=block*8+part;
5132                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
5133                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
5134                        i4e::simd<int32_t,16> scale=ls;scale-=32;
5135                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
5136                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
5137                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
5138                        auto a_words=i4e::load_2d<uint32_t,8,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5139                            XB*36-1,NT-1,XB*36-1,seg*9+1,0);
5140                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
5141                        i4e::simd<int32_t,NT*16> zero=0;
5142                        i4e::simd<int8_t,NT*32> interleaved;
5143#pragma unroll
5144                        for(int mr=0;mr<NT;++mr){
5145                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
5146                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
5147                        }
5148                        using P=i4e::xmx::dpas_argument_type;
5149                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
5150                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
5151                        auto C=Cc*16+Cr;
5152#pragma unroll
5153                        for(int mr=0;mr<NT;++mr){
5154                            i4e::simd<uint16_t,1> dbits=reinterpret_cast<const uint16_t*>(acts)[(mr*XB+seg)*18];
5155                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
5156                            const float ds=dvalue[0];
5157                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
5158                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
5159                            i4e::simd<float,16> term=factor*dot;
5160                            term.merge(0.f,!valid);
5161                            const i4e::simd<float,16> next=acc[half][mr]+term;acc[half][mr].merge(next,valid);
5162                        }
5163                    }
5164                }
5165            }
5166#pragma unroll
5167            for(int part=0;part<2;++part){
5168#pragma unroll
5169                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[part][mr]);
5170            }
5171            i4e::barrier();
5172            if(sid<NT){
5173            i4e::simd<float,16> p[16];
5174#pragma unroll
5175            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
5176                i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
5177#pragma unroll
5178            for(int off=8;off;off/=2){
5179#pragma unroll
5180                for(int v=0;v<off;++v)p[v]+=p[v+off];
5181            }
5182            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
5183            i4e::scatter<float,16>(y,offsets,p[0],valid);
5184            }
5185        });
5186}
5187
5188}
5189
5190void b60_iq4_int4_probe(bool candidate,const void*w,const void*x,float*y,int K,int N,int T,void*stream){
5191 const bool soa=(K==2560&&N==10240)||(K==6144&&N==2560);
5192 if(!candidate){
5193  if(soa)b60_iq4_soa_probe(true,w,x,y,K,N,T,stream);
5194  else native_mmvq(23,w,x,y,K,N,T,stream);
5195  return;
5196 }
5197 auto*q=strata::q_of(stream);const auto*weights=(const uint8_t*)w;const auto*acts=(const Q81Block*)x;
5198 if(soa&&T==4){
5199  if(K==2560)iq4_soa_split_launch_int4<4,10>(weights,acts,y,N,q);
5200  else iq4_soa_split_launch_int4<4,24>(weights,acts,y,N,q);
5201 }else if(soa){
5202#define CALL(TOK) case TOK: if(K==2560)iq4_soa_pair_all_t_launch_int4<TOK,10>(weights,acts,y,N,q);else iq4_soa_pair_all_t_launch_int4<TOK,24>(weights,acts,y,N,q);break;
5203  switch(T){CALL(1) CALL(2) CALL(3) default:throw std::invalid_argument("IQ4 Int4 T");}
5204#undef CALL
5205 }else if(K==2560&&N==106299&&T==1){
5206  iq4_q8_split_launch_int4<1,10>(weights,acts,y,N,q);
5207 }else if(K==2560&&N==248320&&T==4){
5208  iq4_pair_all_t_launch_int4<4,10>(weights,acts,y,N,q);
5209 }else throw std::invalid_argument("IQ4 Int4 shape");
5210}
5211
5212
5213void b60_iq4_ssm_soa_probe(bool candidate,const void*w,const void*x,float*y,int K,int N,int T,void*stream){
5214 if(K!=2560||(N!=6144&&N!=12288)||(T!=1&&T!=2&&T!=4))throw std::invalid_argument("IQ4 SSM SoA shape");
5215 if(!candidate){native_mmvq(23,w,x,y,K,N,T,stream);return;}
5216 auto*q=strata::q_of(stream);const auto*weights=(const uint8_t*)w;const auto*acts=(const Q81Block*)x;
5217 switch(T){
5218  case 1:iq4_soa_pair_all_t_launch_int4<1,10>(weights,acts,y,N,q);break;
5219  case 2:iq4_soa_pair_all_t_launch_int4<2,10>(weights,acts,y,N,q);break;
5220  case 4:iq4_soa_pair_all_t_launch_int4<4,10>(weights,acts,y,N,q);break;
5221 }
5222}
5223
5224namespace {
5225template<int NT,int KB>class IQ4Q8SoASplitInt4;
5226template<int NT,int KB>
5227void iq4_q8_soa_split_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5228    constexpr int NR=16,XB=KB*8,RB=KB*136;
5229    q->parallel_for<IQ4Q8SoASplitInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*16,16),
5230        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5231            i4e::slm_init<32*NT*16*4>();
5232            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5233            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5234            i4e::simd<float,16> acc[2][NT];
5235#pragma unroll
5236            for(int p=0;p<2;++p){
5237#pragma unroll
5238                for(int mr=0;mr<NT;++mr)acc[p][mr]=0.f;
5239            }
5240            for(int block=sid/4;block<KB;block+=4){
5241                const uint8_t* packed_block=weights+size_t(base)*RB+block*16*136;
5242                auto header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5243                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
5244                i4e::simd<uint16_t,16> bits=dh&0xffffu;
5245                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5246                {const int quarter=sid%4;
5247                    const int first_segment=block*8+quarter*2;
5248                    auto aq=i4e::load_2d<uint32_t,16,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5249                        XB*36-1,NT-1,XB*36-1,first_segment*9,0);
5250                    auto tail=i4e::load_2d<uint32_t,2,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5251                        XB*36-1,NT-1,XB*36-1,first_segment*9+16,0);
5252                    constexpr int AP=decltype(aq)::length/NT,TP=decltype(tail)::length/NT;
5253                    static_assert(AP==16 && TP==2);
5254                    auto packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5255#pragma unroll
5256                    for(int half=0;half<2;++half){
5257                        const int part=quarter*2+half,seg=block*8+part;
5258                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
5259                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
5260                        i4e::simd<int32_t,16> scale=ls;scale-=32;
5261                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
5262                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
5263                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
5264                        i4e::simd<uint32_t,NT*8> a_words;
5265#pragma unroll
5266                        for(int mr=0;mr<NT;++mr){
5267                            if(half==0)a_words.template select<8,1>(mr*8)=aq.template select<8,1>(mr*AP+1);
5268                            else{
5269                                a_words.template select<6,1>(mr*8)=aq.template select<6,1>(mr*AP+10);
5270                                a_words.template select<2,1>(mr*8+6)=tail.template select<2,1>(mr*TP);
5271                            }
5272                        }
5273                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
5274                        i4e::simd<int32_t,NT*16> zero=0;
5275                        i4e::simd<int8_t,NT*32> interleaved;
5276#pragma unroll
5277                        for(int mr=0;mr<NT;++mr){
5278                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
5279                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
5280                        }
5281                        using P=i4e::xmx::dpas_argument_type;
5282                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
5283                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
5284                        auto C=Cc*16+Cr;
5285#pragma unroll
5286                        for(int mr=0;mr<NT;++mr){
5287                            i4e::simd<uint32_t,1> dhdr=half==0?aq.template select<1,1>(mr*AP).read():aq.template select<1,1>(mr*AP+9).read();
5288                            i4e::simd<uint16_t,1> dbits=dhdr&0xffffu;
5289                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
5290                            const float ds=dvalue[0];
5291                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
5292                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
5293                            i4e::simd<float,16> term=factor*dot;
5294                            term.merge(0.f,!valid);
5295                            const i4e::simd<float,16> next=acc[half][mr]+term;acc[half][mr].merge(next,valid);
5296                        }
5297                    }
5298                }
5299            }
5300#pragma unroll
5301            for(int part=0;part<2;++part){
5302#pragma unroll
5303                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[part][mr]);
5304            }
5305            i4e::barrier();
5306            if(sid<NT){
5307            i4e::simd<float,16> p[16];
5308#pragma unroll
5309            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64)+
5310                i4e::slm_block_load<float,16>((v+16)*NT*64+sid*64);
5311#pragma unroll
5312            for(int off=8;off;off/=2){
5313#pragma unroll
5314                for(int v=0;v<off;++v)p[v]+=p[v+off];
5315            }
5316            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
5317            i4e::scatter<float,16>(y,offsets,p[0],valid);
5318            }
5319        });
5320}
5321}
5322
5323void b60_iq4_head_soa_probe(bool candidate,const void*w,const void*x,float*y,int K,int N,int T,void*stream){
5324 if(K!=2560||!((N==106299&&T==1)||(N==248320&&T==4)))throw std::invalid_argument("IQ4 head SoA shape");
5325 if(!candidate){b60_iq4_int4_probe(true,w,x,y,K,N,T,stream);return;}
5326 auto*q=strata::q_of(stream);const auto*weights=(const uint8_t*)w;const auto*acts=(const Q81Block*)x;
5327 if(N==106299)iq4_q8_soa_split_launch_int4<1,10>(weights,acts,y,N,q);
5328 else iq4_soa_pair_all_t_launch_int4<4,10>(weights,acts,y,N,q);
5329}
5330
5331namespace {
5332template<int NT,int KB>class IQ4LeafPairsInt4;
5333template<int NT,int KB>
5334void iq4_leaf_pairs_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5335    constexpr int NR=16,WG=8,XB=KB*8,RB=KB*136;
5336    q->parallel_for<IQ4LeafPairsInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*WG,WG),
5337        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5338            i4e::slm_init<16*NT*16*4>();
5339            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5340            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5341            i4e::simd<float,16> acc[2][2][NT];
5342#pragma unroll
5343            for(int branch=0;branch<2;++branch){
5344#pragma unroll
5345             for(int p=0;p<2;++p){
5346#pragma unroll
5347                for(int mr=0;mr<NT;++mr)acc[branch][p][mr]=0.f;
5348             }
5349            }
5350#pragma unroll
5351            for(int branch=0;branch<2;++branch){
5352            const int virtual_sid=sid+branch*8;
5353            for(int block=virtual_sid/4;block<KB;block+=4){
5354                const size_t packed_offset=(NT==1 && KB==10 && base+16>N)?0:size_t(base)*RB+block*16*136;
5355                const uint8_t* packed_block=weights+packed_offset;
5356                i4e::simd<uint32_t,32> header;
5357                if constexpr(NT==1 && KB==10){
5358                    if(base+16>N)header=i4e::load_2d<uint32_t,2,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),RB-1,N-1,RB-1,block*34,base);
5359                    else header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5360                }else header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5361                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
5362                i4e::simd<uint16_t,16> bits=dh&0xffffu;
5363                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5364                {const int quarter=virtual_sid%4;
5365                    const int first_segment=block*8+quarter*2;
5366                    auto aq=i4e::load_2d<uint32_t,16,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5367                        XB*36-1,NT-1,XB*36-1,first_segment*9,0);
5368                    auto tail=i4e::load_2d<uint32_t,2,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5369                        XB*36-1,NT-1,XB*36-1,first_segment*9+16,0);
5370                    constexpr int AP=decltype(aq)::length/NT,TP=decltype(tail)::length/NT;
5371                    static_assert(AP==16 && TP==2);
5372                    i4e::simd<uint32_t,128> packed8;
5373                    if constexpr(NT==1 && KB==10){
5374                        if(base+16>N)packed8=i4e::load_2d<uint32_t,8,16,1,true,false>(reinterpret_cast<const uint32_t*>(weights),RB-1,N-1,RB-1,block*34+2+quarter*8,base);
5375                        else packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5376                    }else packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5377#pragma unroll
5378                    for(int half=0;half<2;++half){
5379                        const int part=quarter*2+half,seg=block*8+part;
5380                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
5381                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
5382                        i4e::simd<int32_t,16> scale=ls;scale-=32;
5383                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
5384                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
5385                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
5386                        i4e::simd<uint32_t,NT*8> a_words;
5387#pragma unroll
5388                        for(int mr=0;mr<NT;++mr){
5389                            if(half==0)a_words.template select<8,1>(mr*8)=aq.template select<8,1>(mr*AP+1);
5390                            else{
5391                                a_words.template select<6,1>(mr*8)=aq.template select<6,1>(mr*AP+10);
5392                                a_words.template select<2,1>(mr*8+6)=tail.template select<2,1>(mr*TP);
5393                            }
5394                        }
5395                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
5396                        i4e::simd<int32_t,NT*16> zero=0;
5397                        i4e::simd<int8_t,NT*32> interleaved;
5398#pragma unroll
5399                        for(int mr=0;mr<NT;++mr){
5400                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
5401                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
5402                        }
5403                        using P=i4e::xmx::dpas_argument_type;
5404                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
5405                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
5406                        auto C=Cc*16+Cr;
5407#pragma unroll
5408                        for(int mr=0;mr<NT;++mr){
5409                            i4e::simd<uint32_t,1> dhdr=half==0?aq.template select<1,1>(mr*AP).read():aq.template select<1,1>(mr*AP+9).read();
5410                            i4e::simd<uint16_t,1> dbits=dhdr&0xffffu;
5411                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
5412                            const float ds=dvalue[0];
5413                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
5414                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
5415                            i4e::simd<float,16> term=factor*dot;
5416                            term.merge(0.f,!valid);
5417                            const i4e::simd<float,16> next=acc[branch][half][mr]+term;acc[branch][half][mr].merge(next,valid);
5418                        }
5419                    }
5420                }
5421            }
5422            }
5423#pragma unroll
5424            for(int part=0;part<2;++part){
5425#pragma unroll
5426                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[0][part][mr]+acc[1][part][mr]);
5427            }
5428            i4e::barrier();
5429            if(sid<NT){
5430            i4e::simd<float,16> p[16];
5431#pragma unroll
5432            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64);
5433#pragma unroll
5434            for(int off=8;off;off/=2){
5435#pragma unroll
5436                for(int v=0;v<off;++v)p[v]+=p[v+off];
5437            }
5438            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
5439            i4e::scatter<float,16>(y,offsets,p[0],valid);
5440            }
5441        });
5442}
5443}
5444
5445void b60_iq4_leaf_pairs_probe(bool candidate,const void*w,const void*x,float*y,int K,int N,int T,void*stream){
5446 if(T!=4||!((K==2560&&N==10240)||(K==6144&&N==2560)))throw std::invalid_argument("IQ4 leaf-pair screen shape");
5447 if(!candidate){b60_iq4_int4_probe(true,w,x,y,K,N,T,stream);return;}
5448 auto*q=strata::q_of(stream);const auto*weights=static_cast<const uint8_t*>(w);const auto*acts=static_cast<const Q81Block*>(x);
5449 if(K==2560)iq4_leaf_pairs_launch_int4<4,10>(weights,acts,y,N,q);
5450 else iq4_leaf_pairs_launch_int4<4,24>(weights,acts,y,N,q);
5451}
5452
5453namespace {
5454template<int NT,int KB>class IQ4MTPLeafPairsInt4;
5455template<int NT,int KB>
5456void iq4_mtp_leaf_pairs_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5457    constexpr int NR=16,WG=8,XB=KB*8,RB=KB*136;
5458    q->parallel_for<IQ4MTPLeafPairsInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*WG,WG),
5459        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5460            i4e::slm_init<16*NT*16*4>();
5461            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5462            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5463            i4e::simd<float,16> acc[2][2][NT];
5464#pragma unroll
5465            for(int branch=0;branch<2;++branch){
5466#pragma unroll
5467             for(int p=0;p<2;++p){
5468#pragma unroll
5469                for(int mr=0;mr<NT;++mr)acc[branch][p][mr]=0.f;
5470             }
5471            }
5472#pragma unroll
5473            for(int branch=0;branch<2;++branch){
5474            const int virtual_sid=sid+branch*8;
5475            for(int block=virtual_sid/4;block<KB;block+=4){
5476                const uint8_t* packed_block=weights+size_t(base)*RB+block*16*136;
5477                auto header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5478                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
5479                i4e::simd<uint16_t,16> bits=dh&0xffffu;
5480                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5481                {const int quarter=virtual_sid%4;
5482                    const int first_segment=block*8+quarter*2;
5483                    auto aq=i4e::load_2d<uint32_t,16,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5484                        XB*36-1,NT-1,XB*36-1,first_segment*9,0);
5485                    auto tail=i4e::load_2d<uint32_t,2,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5486                        XB*36-1,NT-1,XB*36-1,first_segment*9+16,0);
5487                    constexpr int AP=decltype(aq)::length/NT,TP=decltype(tail)::length/NT;
5488                    static_assert(AP==16 && TP==2);
5489                    auto packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5490#pragma unroll
5491                    for(int half=0;half<2;++half){
5492                        const int part=quarter*2+half,seg=block*8+part;
5493                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
5494                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
5495                        i4e::simd<int32_t,16> scale=ls;scale-=32;
5496                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
5497                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
5498                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
5499                        i4e::simd<uint32_t,NT*8> a_words;
5500#pragma unroll
5501                        for(int mr=0;mr<NT;++mr){
5502                            if(half==0)a_words.template select<8,1>(mr*8)=aq.template select<8,1>(mr*AP+1);
5503                            else{
5504                                a_words.template select<6,1>(mr*8)=aq.template select<6,1>(mr*AP+10);
5505                                a_words.template select<2,1>(mr*8+6)=tail.template select<2,1>(mr*TP);
5506                            }
5507                        }
5508                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
5509                        i4e::simd<int32_t,NT*16> zero=0;
5510                        i4e::simd<int8_t,NT*32> interleaved;
5511#pragma unroll
5512                        for(int mr=0;mr<NT;++mr){
5513                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
5514                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
5515                        }
5516                        using P=i4e::xmx::dpas_argument_type;
5517                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
5518                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
5519                        auto C=Cc*16+Cr;
5520#pragma unroll
5521                        for(int mr=0;mr<NT;++mr){
5522                            i4e::simd<uint32_t,1> dhdr=half==0?aq.template select<1,1>(mr*AP).read():aq.template select<1,1>(mr*AP+9).read();
5523                            i4e::simd<uint16_t,1> dbits=dhdr&0xffffu;
5524                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
5525                            const float ds=dvalue[0];
5526                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
5527                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
5528                            i4e::simd<float,16> term=factor*dot;
5529                            term.merge(0.f,!valid);
5530                            const i4e::simd<float,16> next=acc[branch][half][mr]+term;acc[branch][half][mr].merge(next,valid);
5531                        }
5532                    }
5533                }
5534            }
5535            }
5536#pragma unroll
5537            for(int part=0;part<2;++part){
5538#pragma unroll
5539                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[0][part][mr]+acc[1][part][mr]);
5540            }
5541            i4e::barrier();
5542            if(sid<NT){
5543            i4e::simd<float,16> p[16];
5544#pragma unroll
5545            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64);
5546#pragma unroll
5547            for(int off=8;off;off/=2){
5548#pragma unroll
5549                for(int v=0;v<off;++v)p[v]+=p[v+off];
5550            }
5551            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
5552            i4e::scatter<float,16>(y,offsets,p[0],valid);
5553            }
5554        });
5555}
5556
5557template<int NT,int KB>class IQ4MainHeadLeafPairsInt4;
5558template<int NT,int KB>
5559void iq4_mainhead_leaf_pairs_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5560    constexpr int NR=16,WG=8,XB=KB*8,RB=KB*136;
5561    q->parallel_for<IQ4MainHeadLeafPairsInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*WG,WG),
5562        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5563            i4e::slm_init<16*NT*16*4>();
5564            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5565            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5566            i4e::simd<float,16> acc[2][2][NT];
5567#pragma unroll
5568            for(int branch=0;branch<2;++branch){
5569#pragma unroll
5570             for(int p=0;p<2;++p){
5571#pragma unroll
5572                for(int mr=0;mr<NT;++mr)acc[branch][p][mr]=0.f;
5573             }
5574            }
5575#pragma unroll
5576            for(int branch=0;branch<2;++branch){
5577            const int virtual_sid=sid+branch*8;
5578            for(int block=virtual_sid/4;block<KB;block+=4){
5579                const uint8_t* packed_block=weights+size_t(base)*RB+block*16*136;
5580                auto header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5581                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
5582                i4e::simd<uint16_t,16> bits=dh&0xffffu;
5583                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5584                {const int quarter=virtual_sid%4;
5585                    auto packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5586#pragma unroll
5587                    for(int half=0;half<2;++half){
5588                        const int part=quarter*2+half,seg=block*8+part;
5589                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
5590                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
5591                        i4e::simd<int32_t,16> scale=ls;scale-=32;
5592                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
5593                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
5594                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
5595                        auto a_words=i4e::load_2d<uint32_t,8,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5596                            XB*36-1,NT-1,XB*36-1,seg*9+1,0);
5597                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
5598                        i4e::simd<int32_t,NT*16> zero=0;
5599                        i4e::simd<int8_t,NT*32> interleaved;
5600#pragma unroll
5601                        for(int mr=0;mr<NT;++mr){
5602                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
5603                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
5604                        }
5605                        using P=i4e::xmx::dpas_argument_type;
5606                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
5607                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
5608                        auto C=Cc*16+Cr;
5609#pragma unroll
5610                        for(int mr=0;mr<NT;++mr){
5611                            i4e::simd<uint16_t,1> dbits=reinterpret_cast<const uint16_t*>(acts)[(mr*XB+seg)*18];
5612                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
5613                            const float ds=dvalue[0];
5614                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
5615                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
5616                            i4e::simd<float,16> term=factor*dot;
5617                            term.merge(0.f,!valid);
5618                            const i4e::simd<float,16> next=acc[branch][half][mr]+term;acc[branch][half][mr].merge(next,valid);
5619                        }
5620                    }
5621                }
5622            }
5623            }
5624#pragma unroll
5625            for(int part=0;part<2;++part){
5626#pragma unroll
5627                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,acc[0][part][mr]+acc[1][part][mr]);
5628            }
5629            i4e::barrier();
5630            if(sid<NT){
5631            i4e::simd<float,16> p[16];
5632#pragma unroll
5633            for(int v=0;v<16;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64);
5634#pragma unroll
5635            for(int off=8;off;off/=2){
5636#pragma unroll
5637                for(int v=0;v<off;++v)p[v]+=p[v+off];
5638            }
5639            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
5640            i4e::scatter<float,16>(y,offsets,p[0],valid);
5641            }
5642        });
5643}
5644}
5645
5646void b60_iq4_head_leaf_pairs_probe(bool candidate,const void*w,const void*x,float*y,int K,int N,int T,void*stream){
5647 if(K!=2560||!((N==106299&&T==1)||(N==248320&&T==4)))throw std::invalid_argument("IQ4 head leaf-pair shape");
5648 if(!candidate){b60_iq4_head_soa_probe(true,w,x,y,K,N,T,stream);return;}
5649 auto*q=strata::q_of(stream);const auto*weights=static_cast<const uint8_t*>(w);const auto*acts=static_cast<const Q81Block*>(x);
5650 if(N==106299)iq4_mtp_leaf_pairs_launch_int4<1,10>(weights,acts,y,N,q);
5651 else iq4_mainhead_leaf_pairs_launch_int4<4,10>(weights,acts,y,N,q);
5652}
5653
5654namespace {
5655template<int NT,int KB>class IQ4MTPLeafQuartetsInt4;
5656template<int NT,int KB>
5657void iq4_mtp_leaf_quartets_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5658    constexpr int NR=16,WG=4,XB=KB*8,RB=KB*136;
5659    q->parallel_for<IQ4MTPLeafQuartetsInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*WG,WG),
5660        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5661            i4e::slm_init<8*NT*16*4>();
5662            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5663            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5664            i4e::simd<float,16> acc[4][2][NT];
5665#pragma unroll
5666            for(int branch=0;branch<4;++branch){
5667#pragma unroll
5668             for(int p=0;p<2;++p){
5669#pragma unroll
5670                for(int mr=0;mr<NT;++mr)acc[branch][p][mr]=0.f;
5671             }
5672            }
5673#pragma unroll
5674            for(int branch=0;branch<4;++branch){
5675            const int virtual_sid=sid+branch*4;
5676            for(int block=virtual_sid/4;block<KB;block+=4){
5677                const uint8_t* packed_block=weights+size_t(base)*RB+block*16*136;
5678                auto header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5679                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
5680                i4e::simd<uint16_t,16> bits=dh&0xffffu;
5681                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5682                {const int quarter=virtual_sid%4;
5683                    const int first_segment=block*8+quarter*2;
5684                    auto aq=i4e::load_2d<uint32_t,16,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5685                        XB*36-1,NT-1,XB*36-1,first_segment*9,0);
5686                    auto tail=i4e::load_2d<uint32_t,2,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5687                        XB*36-1,NT-1,XB*36-1,first_segment*9+16,0);
5688                    constexpr int AP=decltype(aq)::length/NT,TP=decltype(tail)::length/NT;
5689                    static_assert(AP==16 && TP==2);
5690                    auto packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5691#pragma unroll
5692                    for(int half=0;half<2;++half){
5693                        const int part=quarter*2+half,seg=block*8+part;
5694                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
5695                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
5696                        i4e::simd<int32_t,16> scale=ls;scale-=32;
5697                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
5698                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
5699                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
5700                        i4e::simd<uint32_t,NT*8> a_words;
5701#pragma unroll
5702                        for(int mr=0;mr<NT;++mr){
5703                            if(half==0)a_words.template select<8,1>(mr*8)=aq.template select<8,1>(mr*AP+1);
5704                            else{
5705                                a_words.template select<6,1>(mr*8)=aq.template select<6,1>(mr*AP+10);
5706                                a_words.template select<2,1>(mr*8+6)=tail.template select<2,1>(mr*TP);
5707                            }
5708                        }
5709                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
5710                        i4e::simd<int32_t,NT*16> zero=0;
5711                        i4e::simd<int8_t,NT*32> interleaved;
5712#pragma unroll
5713                        for(int mr=0;mr<NT;++mr){
5714                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
5715                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
5716                        }
5717                        using P=i4e::xmx::dpas_argument_type;
5718                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
5719                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
5720                        auto C=Cc*16+Cr;
5721#pragma unroll
5722                        for(int mr=0;mr<NT;++mr){
5723                            i4e::simd<uint32_t,1> dhdr=half==0?aq.template select<1,1>(mr*AP).read():aq.template select<1,1>(mr*AP+9).read();
5724                            i4e::simd<uint16_t,1> dbits=dhdr&0xffffu;
5725                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
5726                            const float ds=dvalue[0];
5727                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
5728                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
5729                            i4e::simd<float,16> term=factor*dot;
5730                            term.merge(0.f,!valid);
5731                            const i4e::simd<float,16> next=acc[branch][half][mr]+term;acc[branch][half][mr].merge(next,valid);
5732                        }
5733                    }
5734                }
5735            }
5736            }
5737#pragma unroll
5738            for(int part=0;part<2;++part){
5739#pragma unroll
5740                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,(acc[0][part][mr]+acc[2][part][mr])+(acc[1][part][mr]+acc[3][part][mr]));
5741            }
5742            i4e::barrier();
5743            if(sid<NT){
5744            i4e::simd<float,16> p[8];
5745#pragma unroll
5746            for(int v=0;v<8;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64);
5747#pragma unroll
5748            for(int off=4;off;off/=2){
5749#pragma unroll
5750                for(int v=0;v<off;++v)p[v]+=p[v+off];
5751            }
5752            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
5753            i4e::scatter<float,16>(y,offsets,p[0],valid);
5754            }
5755        });
5756}
5757
5758template<int NT,int KB>class IQ4MainHeadLeafQuartetsInt4;
5759template<int NT,int KB>
5760void iq4_mainhead_leaf_quartets_launch_int4(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5761    constexpr int NR=16,WG=4,XB=KB*8,RB=KB*136;
5762    q->parallel_for<IQ4MainHeadLeafQuartetsInt4<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*WG,WG),
5763        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5764            i4e::slm_init<8*NT*16*4>();
5765            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5766            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5767            i4e::simd<float,16> acc[4][2][NT];
5768#pragma unroll
5769            for(int branch=0;branch<4;++branch){
5770#pragma unroll
5771             for(int p=0;p<2;++p){
5772#pragma unroll
5773                for(int mr=0;mr<NT;++mr)acc[branch][p][mr]=0.f;
5774             }
5775            }
5776#pragma unroll
5777            for(int branch=0;branch<4;++branch){
5778            const int virtual_sid=sid+branch*4;
5779            for(int block=virtual_sid/4;block<KB;block+=4){
5780                const uint8_t* packed_block=weights+size_t(base)*RB+block*16*136;
5781                auto header=i4e::block_load<uint32_t,32>(reinterpret_cast<const uint32_t*>(packed_block));
5782                i4e::simd<uint32_t,16> dh=header.template select<16,1>(0),sl=header.template select<16,1>(16);
5783                i4e::simd<uint16_t,16> bits=dh&0xffffu;
5784                i4e::simd<float,16> d=bits.template bit_cast_view<sycl::half>().read();
5785                {const int quarter=virtual_sid%4;
5786                    auto packed8=iq4_soa_payload_load64(packed_block+128+quarter*512);
5787#pragma unroll
5788                    for(int half=0;half<2;++half){
5789                        const int part=quarter*2+half,seg=block*8+part;
5790                        i4e::simd<uint32_t,64> packed=packed8.template select<64,1>(half*64);
5791                        i4e::simd<uint32_t,16> ls=((sl>>(4*part))&15u)|(((dh>>(16+2*part))&3u)<<4);
5792                        i4e::simd<int32_t,16> scale=ls;scale-=32;
5793                        i4e::simd<float,16> fscale=scale;const i4e::simd<float,16> dw=d*fscale;
5794                        auto Bc=iq4_int4_vnni<64>(iq4_int4_coarse<64>(packed));
5795                        auto Br=iq4_int4_vnni<64>(iq4_int4_residual<64>(packed));
5796                        auto a_words=i4e::load_2d<uint32_t,8,NT,1,false,false>(reinterpret_cast<const uint32_t*>(acts),
5797                            XB*36-1,NT-1,XB*36-1,seg*9+1,0);
5798                        i4e::simd<int8_t,NT*32> A=a_words.template bit_cast_view<int8_t>();
5799                        i4e::simd<int32_t,NT*16> zero=0;
5800                        i4e::simd<int8_t,NT*32> interleaved;
5801#pragma unroll
5802                        for(int mr=0;mr<NT;++mr){
5803                            interleaved.template select<16,2>(mr*32)=A.template select<16,1>(mr*32);
5804                            interleaved.template select<16,2>(mr*32+1)=A.template select<16,1>(mr*32+16);
5805                        }
5806                        using P=i4e::xmx::dpas_argument_type;
5807                        auto Cc=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Bc,interleaved);
5808                        auto Cr=i4e::xmx::dpas<8,NT,int32_t,int32_t,uint16_t,int8_t,P::s4,P::s8>(zero,Br,interleaved);
5809                        auto C=Cc*16+Cr;
5810#pragma unroll
5811                        for(int mr=0;mr<NT;++mr){
5812                            i4e::simd<uint16_t,1> dbits=reinterpret_cast<const uint16_t*>(acts)[(mr*XB+seg)*18];
5813                            i4e::simd<float,1> dvalue=dbits.template bit_cast_view<sycl::half>().read();
5814                            const float ds=dvalue[0];
5815                            i4e::simd<int32_t,16> ci=C.template select<16,1>(mr*16);
5816                            i4e::simd<float,16> dot=ci;const i4e::simd<float,16> factor=dw*ds;
5817                            i4e::simd<float,16> term=factor*dot;
5818                            term.merge(0.f,!valid);
5819                            const i4e::simd<float,16> next=acc[branch][half][mr]+term;acc[branch][half][mr].merge(next,valid);
5820                        }
5821                    }
5822                }
5823            }
5824            }
5825#pragma unroll
5826            for(int part=0;part<2;++part){
5827#pragma unroll
5828                for(int mr=0;mr<NT;++mr)i4e::slm_block_store<float,16>((sid*2+part)*NT*64+mr*64,(acc[0][part][mr]+acc[2][part][mr])+(acc[1][part][mr]+acc[3][part][mr]));
5829            }
5830            i4e::barrier();
5831            if(sid<NT){
5832            i4e::simd<float,16> p[8];
5833#pragma unroll
5834            for(int v=0;v<8;++v)p[v]=i4e::slm_block_load<float,16>(v*NT*64+sid*64);
5835#pragma unroll
5836            for(int off=4;off;off/=2){
5837#pragma unroll
5838                for(int v=0;v<off;++v)p[v]+=p[v+off];
5839            }
5840            i4e::simd<uint32_t,16> offsets=(row+uint32_t(sid)*uint32_t(N))*4u;
5841            i4e::scatter<float,16>(y,offsets,p[0],valid);
5842            }
5843        });
5844}
5845}
5846
5847void b60_iq4_head_leaf_quartets_probe(bool candidate,const void*w,const void*x,float*y,int K,int N,int T,void*stream){
5848 if(K!=2560||!((N==106299&&T==1)||(N==248320&&T==4)))throw std::invalid_argument("IQ4 head leaf-quartet shape");
5849 if(!candidate){b60_iq4_head_leaf_pairs_probe(true,w,x,y,K,N,T,stream);return;}
5850 auto*q=strata::q_of(stream);const auto*weights=static_cast<const uint8_t*>(w);const auto*acts=static_cast<const Q81Block*>(x);
5851 if(N==106299)iq4_mtp_leaf_quartets_launch_int4<1,10>(weights,acts,y,N,q);
5852 else iq4_mainhead_leaf_quartets_launch_int4<4,10>(weights,acts,y,N,q);
5853}
5854
5855namespace {
5856template<int KB>class MtpQ8SoAInt8;
5857template<int KB>
5858void mtp_q8_soa_launch(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5859#pragma clang fp contract(off)
5860    constexpr int WG=8,RB=KB*34;
5861    q->parallel_for<MtpQ8SoAInt8<KB>>(sycl::nd_range<1>(size_t((N+15)/16)*WG,WG),
5862        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5863            i4e::slm_init<16*16*4>();
5864            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5865            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5866            i4e::simd<float,16> acc[2][2];
5867#pragma unroll
5868            for(int branch=0;branch<2;++branch){
5869#pragma unroll
5870                for(int half=0;half<2;++half)acc[branch][half]=0.f;
5871            }
5872#pragma unroll
5873            for(int branch=0;branch<2;++branch){
5874                const int sub=sid+branch*8;
5875                for(int kb=sub;kb<KB;kb+=16){
5876                    const uint8_t* block=weights+size_t(base)*RB+kb*544;
5877                    auto dh=i4e::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block));
5878                    i4e::simd<float,16> d=dh.template bit_cast_view<sycl::half>().read();
5879                    auto bytes=i4e::block_load<uint64_t,64>(reinterpret_cast<const uint64_t*>(block+32));
5880                    i4e::simd<int8_t,512> B=bytes.template bit_cast_view<int8_t>();
5881                    const uint8_t* raw=reinterpret_cast<const uint8_t*>(acts+kb);
5882                    i4e::simd<uint32_t,8> q_offsets(4,4);
5883                    auto u=i4e::gather<int32_t,8>(reinterpret_cast<const int32_t*>(raw),q_offsets);
5884                    i4e::simd<int32_t,16> aw=0;
5885                    aw.template select<4,1>(0)=u.template select<4,1>(0);
5886                    aw.template select<4,1>(12)=u.template select<4,1>(4);
5887                    i4e::simd<int8_t,64> A=aw.template bit_cast_view<int8_t>();
5888                    i4e::simd<int32_t,32> zero=0;
5889                    auto dots=i4e::xmx::dpas<8,2,int32_t>(zero,B,A);
5890                    i4e::simd<uint16_t,1> dsbits=reinterpret_cast<const uint16_t*>(raw)[0];
5891                    i4e::simd<float,1> dsvalue=dsbits.template bit_cast_view<sycl::half>().read();
5892                    const float ds=dsvalue[0];
5893                    const i4e::simd<float,16> factor=d*ds;
5894#pragma unroll
5895                    for(int half=0;half<2;++half){
5896                        i4e::simd<int32_t,16> ci=dots.template select<16,1>(half*16);
5897                        i4e::simd<float,16> dot=ci;
5898                        i4e::simd<float,16> term=factor*dot;
5899                        term.merge(0.f,!valid);
5900                        const i4e::simd<float,16> next=acc[branch][half]+term;
5901                        acc[branch][half].merge(next,valid);
5902                    }
5903                }
5904            }
5905#pragma unroll
5906            for(int half=0;half<2;++half)
5907                i4e::slm_block_store<float,16>((sid*2+half)*64,acc[0][half]+acc[1][half]);
5908            i4e::barrier();
5909            if(sid==0){
5910                i4e::simd<float,16> partial[16];
5911#pragma unroll
5912                for(int v=0;v<16;++v)partial[v]=i4e::slm_block_load<float,16>(v*64);
5913#pragma unroll
5914                for(int off=8;off;off/=2){
5915#pragma unroll
5916                    for(int v=0;v<off;++v)partial[v]+=partial[v+off];
5917                }
5918                i4e::scatter<float,16>(y,row*4u,partial[0],valid);
5919            }
5920        });
5921}
5922}
5923void b60_mtp_q8_soa_probe(const void*w,const void*x,float*y,int K,int N,void*stream){
5924    if(N%16||N<=0)throw std::invalid_argument("MTP Q8 SoA rows");
5925    auto*q=strata::q_of(stream);const auto*weights=static_cast<const uint8_t*>(w);const auto*acts=static_cast<const Q81Block*>(x);
5926    if(K==2560)mtp_q8_soa_launch<80>(weights,acts,y,N,q);
5927    else if(K==6144)mtp_q8_soa_launch<192>(weights,acts,y,N,q);
5928    else if(K==640)mtp_q8_soa_launch<20>(weights,acts,y,N,q);
5929    else throw std::invalid_argument("MTP Q8 SoA columns");
5930}
5931
5932namespace {
5933template<int NT,int KB>class MtpQ8MultiSoAInt8;
5934template<int NT,int KB>
5935void mtp_q8_multi_soa_launch(const uint8_t* weights,const Q81Block* acts,float* y,int N,sycl::queue* q){
5936#pragma clang fp contract(off)
5937    static_assert(NT==4||NT==8);constexpr int WG=8,RB=KB*34;
5938    q->parallel_for<MtpQ8MultiSoAInt8<NT,KB>>(sycl::nd_range<1>(size_t((N+15)/16)*WG,WG),
5939        [=](sycl::nd_item<1> it)[[intel::sycl_explicit_simd]]{
5940            i4e::slm_init<16*NT*16*4>();
5941            const int sid=it.get_local_linear_id(),base=it.get_group_linear_id()*16;
5942            i4e::simd<uint32_t,16> row(base,1);auto valid=row<uint32_t(N);
5943            i4e::simd<float,16> acc[2][2][NT];
5944#pragma unroll
5945            for(int branch=0;branch<2;++branch){
5946#pragma unroll
5947                for(int half=0;half<2;++half){
5948#pragma unroll
5949                    for(int e=0;e<NT;++e)acc[branch][half][e]=0.f;
5950                }
5951            }
5952#pragma unroll
5953            for(int branch=0;branch<2;++branch){
5954                const int sub=sid+branch*8;
5955                for(int kb=sub;kb<KB;kb+=16){
5956                    const uint8_t* block=weights+size_t(base)*RB+kb*544;
5957                    auto dh=i4e::block_load<uint16_t,16>(reinterpret_cast<const uint16_t*>(block));
5958                    i4e::simd<float,16> d=dh.template bit_cast_view<sycl::half>().read();
5959                    auto bytes=i4e::block_load<uint64_t,64>(reinterpret_cast<const uint64_t*>(block+32));
5960                    i4e::simd<int8_t,512> B=bytes.template bit_cast_view<int8_t>();
5961#pragma unroll
5962                    for(int e0=0;e0<NT;e0+=4){
5963                        i4e::simd<int32_t,64> aw=0;i4e::simd<float,4> activation_scale;
5964#pragma unroll
5965                        for(int e=0;e<4;++e){
5966                            const uint8_t* raw=reinterpret_cast<const uint8_t*>(acts+(e0+e)*KB+kb);
5967                            i4e::simd<uint32_t,8> offsets(4,4);
5968                            auto u=i4e::gather<int32_t,8>(reinterpret_cast<const int32_t*>(raw),offsets);
5969                            aw.template select<4,1>(e*16)=u.template select<4,1>(0);
5970                            aw.template select<4,1>(e*16+12)=u.template select<4,1>(4);
5971                            i4e::simd<uint16_t,1> dsbits=reinterpret_cast<const uint16_t*>(raw)[0];
5972                            i4e::simd<float,1> dsvalue=dsbits.template bit_cast_view<sycl::half>().read();activation_scale[e]=dsvalue[0];
5973                        }
5974                        i4e::simd<int8_t,256> A=aw.template bit_cast_view<int8_t>();
5975                        i4e::simd<int32_t,128> zero=0;
5976                        auto dots=i4e::xmx::dpas<8,8,int32_t>(zero,B,A);
5977#pragma unroll
5978                        for(int e=0;e<4;++e){
5979                            const float ds=activation_scale[e];const i4e::simd<float,16> factor=d*ds;
5980#pragma unroll
5981                            for(int half=0;half<2;++half){
5982                                i4e::simd<int32_t,16> ci=dots.template select<16,1>(e*32+half*16);
5983                                i4e::simd<float,16> dot=ci;i4e::simd<float,16> term=factor*dot;
5984                                term.merge(0.f,!valid);
5985                                const i4e::simd<float,16> next=acc[branch][half][e0+e]+term;
5986                                acc[branch][half][e0+e].merge(next,valid);
5987                            }
5988                        }
5989                    }
5990                }
5991            }
5992#pragma unroll
5993            for(int half=0;half<2;++half){
5994#pragma unroll
5995                for(int e=0;e<NT;++e)i4e::slm_block_store<float,16>(((sid*2+half)*NT+e)*64,acc[0][half][e]+acc[1][half][e]);
5996            }
5997            i4e::barrier();
5998            if(sid<NT){
5999                i4e::simd<float,16> partial[16];
6000#pragma unroll
6001                for(int v=0;v<16;++v)partial[v]=i4e::slm_block_load<float,16>((v*NT+sid)*64);
6002#pragma unroll
6003                for(int off=8;off;off/=2){
6004#pragma unroll
6005                    for(int v=0;v<off;++v)partial[v]+=partial[v+off];
6006                }
6007                i4e::scatter<float,16>(y,(row+uint32_t(sid)*uint32_t(N))*4u,partial[0],valid);
6008            }
6009        });
6010}
6011}
6012
6013void b60_mtp_q8_multi_soa_probe(const void*w,const void*x,float*y,int K,int N,int T,void*stream){
6014 if(T==1){b60_mtp_q8_soa_probe(w,x,y,K,N,stream);return;}
6015 if((T!=4&&T!=8)||N%16||N<=0)throw std::invalid_argument("MTP multi Q8 SoA shape");
6016 auto*q=strata::q_of(stream);const auto*weights=static_cast<const uint8_t*>(w);const auto*acts=static_cast<const Q81Block*>(x);
6017 if(K==2560){if(T==4)mtp_q8_multi_soa_launch<4,80>(weights,acts,y,N,q);else mtp_q8_multi_soa_launch<8,80>(weights,acts,y,N,q);}
6018 else if(K==6144){if(T==4)mtp_q8_multi_soa_launch<4,192>(weights,acts,y,N,q);else mtp_q8_multi_soa_launch<8,192>(weights,acts,y,N,q);}
6019 else if(K==640){if(T==4)mtp_q8_multi_soa_launch<4,20>(weights,acts,y,N,q);else mtp_q8_multi_soa_launch<8,20>(weights,acts,y,N,q);}
6020 else throw std::invalid_argument("MTP multi Q8 SoA columns");
6021}
6022
6023} // namespace strata::kernels