okami.mom/strata

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

Niko1221Merge f-037-arc (5eaee81a4)86bed1c92

main
54.6 KiB1016 linesraw
1// src/kernels/cuda/s_gemv.cu - P2.S2: the S-family GEMV, one thread per output row.
2//
3// Naive per the phase rule: dequantize on the fly, FP32 accumulation inside the row, no shared memory, no
4// vector loads.  The kernel is templated on the code WIDTH (a compile-time property of the unpacking loop) and
5// takes the rest of the per-type attributes as run-time arguments, because the manifest supplies them per
6// tensor and a 13-way switch inside the inner loop would be the naive-but-wrong kind of naive.
7#define DPCT_PROFILING_ENABLED
8#include <sycl/sycl.hpp>
9#include "strata/kprof.hpp"
10#include <dpct/dpct.hpp>
11#include "strata/sycl_queue.hpp"
12#include "strata/kernels/s_gemv.hpp"
13
14#include <cstdio>
15#include <cstdlib>
16
17namespace strata::kernels {
18namespace {
19
20// `kvalues_iq4nl`: the non-linear codebook, verbatim from ggml-common.h / ggml-quants.c.
21//
22// **IT WAS IN `__constant__` FOR THE WRONG REASON, AND IT COST 2.12x.**  The old comment justified constant
23// memory with "every thread reads it and it is the same 16 values for the whole launch".  That reasoning is
24// exactly backwards: constant memory is fast when the access is UNIFORM - every lane reading the SAME address -
25// and a NON-LINEAR codebook means every lane reads a DIFFERENT index, which is the pattern it handles worst.
26//
27// Measured on `attn_qkv` (IQ4_XS, 10240 x 2560), forcing the Affine codebook so that the memory traffic and the
28// instruction count stay identical and only the table read is removed:
29//
30//     codebook probe: IQ4NL 0.2032 ms   Affine 0.0960 ms   ratio 2.12x
31//
32// `decode_tbl` below reads a SHARED copy instead: 16 bytes loaded once per block, then an index into shared
33// memory that costs at most a four-way bank conflict.  The `__constant__` array stays as the source of it.
34const signed char kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10,
35                                1,    13,   25,  38,  53,  69,  89,  113};
36
37template <int CODE_BITS>
38__dpct_inline__ float decode(int code, int bias, int codebook) {
39    if (codebook == (int) Codebook::Iq4Nl) return (float) kIq4Nl[code & 0x0F];
40    return (float) (code + bias);       // the bias is applied to the CODE, in the integer domain
41}
42
43/// The same decode with the codebook in SHARED memory, which is what the hot kernels use - see the measurement
44/// above.  A divergent read of a 16-entry table is the one access pattern constant memory is worst at.
45template <int CODE_BITS>
46__dpct_inline__ float decode_tbl(int code, int bias, int codebook,
47                                 const signed char *tbl) {
48    if (codebook == (int) Codebook::Iq4Nl) return (float) tbl[code & 0x0F];
49    return (float) (code + bias);
50}
51
52// ---- Q8_K ACTIVATIONS ----------------------------------------------------------------------------------
53//
54// 292 bytes per 256 elements: `{ f32 d ; int8_t qs[256] ; int16_t bsums[16] }`.  `bsums` is not read - it
55// exists for ggml's AVX2 dot product - but the STRIDE includes it, so a buffer from `quantize_q8_K` passes
56// straight in.
57//
58// The block's `d` sits at a 4-byte-aligned offset from the buffer base as long as the base is aligned, which
59// `cudaMalloc` guarantees.
60constexpr int Q8K_BLOCK_BYTES = 292;
61constexpr int Q8K_BLOCK_ELEMS = 256;
62
63__dpct_inline__ float q8k_at(const uint8_t *__restrict__ x, long long i) {
64    const uint8_t* blk = x + (i / Q8K_BLOCK_ELEMS) * Q8K_BLOCK_BYTES;
65    /*
66    DPCT1098: The '*' expression is used instead of the __ldg call. These
67    two expressions do not provide the exact same functionality. Check the
68    generated code for potential precision and/or performance issues.
69    */
70    const float d = *(const float*) blk;
71    const int8_t q = ((const int8_t*) (blk + 4))[i % Q8K_BLOCK_ELEMS];
72    return d * (float) q;
73}
74
75/// **THE Q8_0 ACTIVATION**, which is what the LEGACY block formats want: `block_q8_0` is `{fp16 d; int8 qs[32]}`,
76/// 34 bytes per 32 elements, produced by `quantize_q8_0`.
77///
78/// THE ENGINE HAD NO GEMV FOR THIS, and it was the last activation-contract gap (LEDGER L54).  It was described
79/// as "Q8_K is not implemented", which is not the situation: `ffn_down_shexp` is IQ4_NL/Q4_0/Q5_0/Q8_0 in EVERY
80/// layer, whose `vec_dot_type` is Q8_0 - and its `n_in` is 640, which is not a multiple of 256, so **Q8_K is
81/// STRUCTURALLY IMPOSSIBLE for it rather than merely absent**.  Every other legacy tensor in the pack is Q2_0,
82/// whose attributes happen to be S2's, which is how the S2-only kernel covered them and the hole stayed hidden.
83constexpr int Q8_0_BLOCK_BYTES = 34;
84constexpr int Q8_0_BLOCK_ELEMS = 32;
85
86__dpct_inline__ float q8_0_at(const uint8_t *__restrict__ x, long long i) {
87    const uint8_t* blk = x + (i / Q8_0_BLOCK_ELEMS) * Q8_0_BLOCK_BYTES;
88    // a `uint16_t` needs 2-byte alignment and the stride is 34, so every block's `d` is aligned
89    const float d =
90        sycl::vec<sycl::half, 1>(
91            sycl::bit_cast<sycl::half, unsigned short>(*(const uint16_t *)blk))
92            .convert<float, sycl::rounding_mode::automatic>()[0];
93    const int8_t q = ((const int8_t*) (blk + 2))[i % Q8_0_BLOCK_ELEMS];
94    return d * (float) q;
95}
96
97/// The Q8_K path, with the SAME weight decode as `s_gemv_kernel` and a different activation loader.  The two
98/// are separate kernels rather than one templated on the activation kind because the activation POINTER TYPE
99/// differs (`uint16_t*` vs `uint8_t*`) and a templated pointer would need a cast at every call site - which is
100/// where a wrong stride would hide.
101template <int CODE_BITS>
102__dpct_inline__ void s_gemv_q8k_kernel(const uint8_t *__restrict__ x,
103                                       const uint8_t *__restrict__ codes,
104                                       const float *__restrict__ scales,
105                                       const float *__restrict__ offset,
106                                       float *__restrict__ y, long long n_in,
107                                       long long n_out, int bias, int codebook,
108                                       int group_elems, int has_offset) {
109    // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block.  See the note on `kIq4Nl`.
110    // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread
111    // that returned first would leave the others waiting at a barrier it never reaches.
112    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
113auto &s_iq4nl =
114    *sycl::ext::oneapi::group_local_memory_for_overwrite<signed char[16]>(
115        sycl::ext::oneapi::this_work_item::get_work_group<3>());
116    if (item_ct1.get_local_id(2) < 16) s_iq4nl[item_ct1.get_local_id(2)] =
117        kIq4Nl[item_ct1.get_local_id(2)];
118    item_ct1.barrier(sycl::access::fence_space::local_space);
119    const long long o =
120        (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
121        item_ct1.get_local_id(2);
122    if (o >= n_out) return;
123
124    constexpr int PER_BYTE = 8 / CODE_BITS;
125    const long long n_groups = n_in / group_elems;
126    const long long codes_per_row = n_in / PER_BYTE;
127    const uint8_t* c = codes + o * codes_per_row;
128    const float* s = scales + o * n_groups;
129    const float* off = has_offset ? offset + o * n_groups : nullptr;
130
131    float acc = 0.0f;
132    for (long long g = 0; g < n_groups; ++g) {
133        const float d = s[g];
134        const float b = off ? off[g] : 0.0f;
135        const long long base = g * (long long) group_elems;
136        for (int j = 0; j < group_elems; ++j) {
137            const long long i = base + j;
138            const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1);
139            // The offset belongs to the WEIGHT and is applied before the activation multiply - see the note in
140            // `s_gemv_kernel`, where writing it the other way rounded differently and only the Q4_K case could
141            // tell.
142            const float w = decode_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * d + b;
143            acc += w * q8k_at(x, i);
144        }
145    }
146    y[o] = acc;
147}
148
149/// One warp per output row, lanes striding the reduction axis: for a fixed `i` consecutive lanes read
150/// consecutive activations, which is the coalescing that matters once the output width is small.
151///
152/// **`group_shift`, NOT `group_elems`, AND IT COSTS A DIVISION PER ELEMENT IF YOU GET IT WRONG.**  The
153/// sibling fp16 kernel was given this treatment ("a 64-bit integer division on this hardware is a long
154/// instruction sequence - one per element, in the hottest loop in the engine") and THIS one was not: it kept
155/// `i / group_elems` with `group_elems` a RUNTIME value, once per element, in the kernel that carries most of
156/// the model's weight bytes.  Every group size the format defines is a power of two, so the divisor is passed
157/// as its logarithm and the division becomes a shift; the host refuses a non-power-of-two group rather than
158/// computing a wrong index.
159/// ONE KERNEL FOR BOTH QUANTIZED ACTIVATIONS, templated on which block format `x` holds.  A second copy with a
160/// different loader would be a second thing to get wrong, and the only difference IS the loader - the weight
161/// decode, the quad loop, the shared codebook and the reduction are identical.
162template <int CODE_BITS, bool Q8K>
163/*
164DPCT1110: The total declared local variable size in device function
165s_gemv_q8_split_kernel exceeds 128 bytes and may cause high register pressure.
166Consult with your hardware vendor to find the total register size available and
167adjust the code, or use smaller sub-group size to avoid high register pressure.
168*/
169__dpct_inline__ void s_gemv_q8_split_kernel(
170    const uint8_t *__restrict__ x, const uint8_t *__restrict__ codes,
171    const float *__restrict__ scales, const float *__restrict__ offset,
172    float *__restrict__ y, long long n_in, long long n_out, int bias,
173    int codebook, int group_shift, int has_offset) {
174    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
175    constexpr int PER_BYTE = 8 / CODE_BITS;
176    const int warps_per_block = (int)(item_ct1.get_local_range(2) >> 5);
177    const long long o = (long long)item_ct1.get_group(2) * warps_per_block +
178                        (item_ct1.get_local_id(2) >> 5);
179    const int lane = item_ct1.get_local_id(2) & 31;
180
181    // THE CODEBOOK, IN SHARED MEMORY.  16 bytes, loaded once per block by the first 16 threads, instead of a
182    // divergent constant read per element - measured at 2.12x of this whole kernel (see the note on `kIq4Nl`).
183    //
184    // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN, as in `s_gemv_q8k_kernel`.  The return used to
185    // sit above them, so whenever `n_out % 8 != 0` the last block's surplus warps left before a barrier the
186    // others still waited at - undefined behaviour that every shape in the pack (a multiple of 8) happened to
187    // avoid.  `o` is per-WARP, so the return below keeps whole warps together and the shuffle reduction's
188    // full mask stays valid.
189    auto &s_iq4nl =
190        *sycl::ext::oneapi::group_local_memory_for_overwrite<signed char[16]>(
191            sycl::ext::oneapi::this_work_item::get_work_group<3>());
192    if (item_ct1.get_local_id(2) < 16) s_iq4nl[item_ct1.get_local_id(2)] =
193        kIq4Nl[item_ct1.get_local_id(2)];
194    item_ct1.barrier(sycl::access::fence_space::local_space);
195    if (o >= n_out) return;
196
197    const long long n_groups = n_in >> group_shift;
198    const long long codes_per_row = n_in / PER_BYTE;
199    const uint8_t* c = codes + o * codes_per_row;
200    const float* s = scales + o * n_groups;
201    const float* off = has_offset ? offset + o * n_groups : nullptr;
202
203    float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f;
204    float acc4 = 0.0f, acc5 = 0.0f, acc6 = 0.0f, acc7 = 0.0f;
205    float acc8 = 0.0f, acc9 = 0.0f, acc10 = 0.0f, acc11 = 0.0f;
206    float acc12 = 0.0f, acc13 = 0.0f, acc14 = 0.0f, acc15 = 0.0f;
207    // ---- EIGHT CONSECUTIVE ELEMENTS PER LANE, from TWO code loads and ONE scale.
208    //
209    // **THIS IS THE EXPERIMENT THE `#pragma unroll` NOTE BELOW LEFT OPEN**, and the note said what it would
210    // be: "Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four independent 16-bit words per
211    // lane - which an unroll cannot do because the extraction code is written for exactly four codes."  So a
212    // lane now takes a double quad: two code words issued before either is consumed, which is what raises the
213    // bytes in flight.  The scale and offset are still ONE load, because eight consecutive elements lie in one
214    // group whenever `group_elems % 8 == 0` - the launcher asserts that, and every group size this format
215    // defines (16, 32, 64) satisfies it.
216    //
217    // The loop used to take `i = lane, lane+32, ...` - a STRIDE, chosen so consecutive lanes read consecutive
218    // activations - and paid a code load, a shift-and-mask, and a scale load FOR EVERY ELEMENT.  But four
219    // consecutive elements share one code word (1, 2 or 4 bytes depending on width) and lie in one group,
220    // because every group size this format defines is a multiple of four.  So a lane takes a QUAD:
221    //
222    //     one code load        instead of four
223    //     one scale load       instead of four
224    //     one shift per element instead of a divide, a modulo and a shift
225    //
226    // THE BIT ORDER IS THE SAME ONE, verified for all three widths: element `i+k` is bits
227    // `[k*CODE_BITS, (k+1)*CODE_BITS)` of the little-endian word at byte `i/PER_BYTE`, which is what the old
228    // `(c[e/PER_BYTE] >> ((e%PER_BYTE)*CODE_BITS)) & MASK` computed one element at a time.
229    //
230    // THE SUMMATION ORDER CHANGES, which is why `s_gemv_parity` and `s_gemv_q8k_parity` carry tolerances and
231    // compare against the naive kernel - they are the guard for this, and they are the reason it is safe to do.
232    constexpr int QE = 16;
233    // BYTES PER FOUR-CODE WORD, not per octet.  The two are easy to confuse and the first version of this
234    // did: it branched on the octet's total width and so read a uint32 for S4 (whose four codes are a
235    // uint16) and single bytes for S8 (whose four codes are a uint32).  `s_gemv_q8k_parity` failed on
236    // exactly that, which is what it is for.
237    constexpr int QW = 4 * CODE_BITS / 8;              // 1 for S2, 2 for S4, 4 for S8
238    constexpr unsigned MASK = (1u << CODE_BITS) - 1u;
239    long long i = (long long) lane * QE;
240    // **`#pragma unroll 4` WAS TRIED HERE AND DID NOTHING.**  Measured: 184.6 -> 183.9 GB/s at n_out 10240,
241    // with `s_gemv_parity` and `s_gemv_q8k_parity` both still clean.  The hypothesis it was testing is L93 -
242    // that this kernel's flat ~6 ns per output row is a bytes-in-flight limit, one code load and one scale
243    // load per lane-iteration with only 20 iterations.  A 4x unroll issues four of each before the first is
244    // consumed, so either the compiler was already doing it or **the limit is not instruction scheduling.**
245    // Removed rather than kept, because a hint that does not change the timing is a claim that is not true.
246    //
247    // What it does NOT rule out is the structural version of the same idea: QE is 4, so a lane consumes ONE
248    // 2-byte code word per iteration.  Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four
249    // independent 16-bit words per lane - which an unroll cannot do because the extraction code is written for
250    // exactly four codes.  That is the experiment that would settle it, and it is not this one.
251    for (; i + QE <= n_in; i += 32 * QE) {
252        const long long g = i >> group_shift;          // the whole octet is in one group: group_elems % 8 == 0
253        const float d = s[g];
254        const float b = off ? off[g] : 0.0f;
255        const uint8_t* cp = c + i / PER_BYTE;
256        unsigned v, v2, v3, v4;
257        if (QW == 1) { v = cp[0]; v2 = cp[1]; v3 = cp[2]; v4 = cp[3]; }
258        else if (QW == 2) { v = *(const uint16_t*) cp; v2 = *(const uint16_t*) (cp + 2);
259                            v3 = *(const uint16_t*) (cp + 4); v4 = *(const uint16_t*) (cp + 6); }
260        else { v = *(const uint32_t*) cp; v2 = *(const uint32_t*) (cp + 4);
261               v3 = *(const uint32_t*) (cp + 8); v4 = *(const uint32_t*) (cp + 12); }
262        // ---- THE ACTIVATION BLOCK IS HOISTED OUT OF THE SIXTEEN ELEMENTS, AND THAT WAS THE KERNEL'S COST.
263        //
264        // `q8k_at(x, i + k)` computes `(i + k) / 256` and `(i + k) % 256` on EVERY call: a 64-bit integer
265        // division AND modulo per element, sixteen times per lane-iteration.  A 64-bit division on a GPU is a
266        // software routine of roughly a hundred cycles, and the compiler cannot strength-reduce it because it
267        // cannot prove `(i + k) / 256 == i / 256` without knowing `i % 256`.
268        //
269        // But `QE` is 16, `Q8K_BLOCK_ELEMS` is 256 and `Q8_0_BLOCK_ELEMS` is 32, and the loop advances `i` by
270        // `32 * QE`.  So `i % 256` and `i % 32` are ALWAYS multiples of 16 - which means all QE elements of one
271        // lane-iteration lie inside ONE block, for either activation kind.  One division and one modulo per
272        // iteration replace sixteen of each, and the sixteen activations become sixteen consecutive int8 loads
273        // from a pointer computed once.
274        //
275        // This is exact, not an approximation: `xi + QE <= blk_elems` holds for every reachable `xi`, so no
276        // lane-iteration can straddle a block boundary.  The tail loop below still uses the accessors because
277        // its elements do not share a block, and it runs at most once per lane.
278        const int blk_elems = Q8K ? Q8K_BLOCK_ELEMS : Q8_0_BLOCK_ELEMS;
279        const uint8_t* xb = x + (i / blk_elems) * (Q8K ? Q8K_BLOCK_BYTES : Q8_0_BLOCK_BYTES);
280        const int xi = (int) (i % blk_elems);
281        /*
282        DPCT1098: The '*' expression is used instead of the __ldg call.
283        These two expressions do not provide the exact same functionality. Check
284        the generated code for potential precision and/or performance issues.
285        */
286        const float xd =
287            Q8K ? *(const float*) xb
288                : sycl::vec<sycl::half, 1>(
289                      sycl::bit_cast<sycl::half, unsigned short>(
290                          *(const uint16_t *)xb))
291                      .convert<float, sycl::rounding_mode::automatic>()[0];
292        const int8_t* xq = (const int8_t*) (xb + (Q8K ? 4 : 2)) + xi;
293
294        const float w0 = decode_tbl<CODE_BITS>((int) (v & MASK), bias, codebook, s_iq4nl) * d + b;
295        const float w1 = decode_tbl<CODE_BITS>((int) ((v >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
296        const float w2 = decode_tbl<CODE_BITS>((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
297        const float w3 = decode_tbl<CODE_BITS>((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
298        const float w4 = decode_tbl<CODE_BITS>((int) (v2 & MASK), bias, codebook, s_iq4nl) * d + b;
299        const float w5 = decode_tbl<CODE_BITS>((int) ((v2 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
300        const float w6 = decode_tbl<CODE_BITS>((int) ((v2 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
301        const float w7 = decode_tbl<CODE_BITS>((int) ((v2 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
302        acc0 += w0 * (xd * (float) xq[0]);
303        acc1 += w1 * (xd * (float) xq[1]);
304        acc2 += w2 * (xd * (float) xq[2]);
305        acc3 += w3 * (xd * (float) xq[3]);
306        acc4 += w4 * (xd * (float) xq[4]);
307        acc5 += w5 * (xd * (float) xq[5]);
308        acc6 += w6 * (xd * (float) xq[6]);
309        acc7 += w7 * (xd * (float) xq[7]);
310        const float w8  = decode_tbl<CODE_BITS>((int) (v3 & MASK), bias, codebook, s_iq4nl) * d + b;
311        const float w9  = decode_tbl<CODE_BITS>((int) ((v3 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
312        const float w10 = decode_tbl<CODE_BITS>((int) ((v3 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
313        const float w11 = decode_tbl<CODE_BITS>((int) ((v3 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
314        const float w12 = decode_tbl<CODE_BITS>((int) (v4 & MASK), bias, codebook, s_iq4nl) * d + b;
315        const float w13 = decode_tbl<CODE_BITS>((int) ((v4 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
316        const float w14 = decode_tbl<CODE_BITS>((int) ((v4 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
317        const float w15 = decode_tbl<CODE_BITS>((int) ((v4 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
318        acc8  += w8  * (xd * (float) xq[8]);
319        acc9  += w9  * (xd * (float) xq[9]);
320        acc10 += w10 * (xd * (float) xq[10]);
321        acc11 += w11 * (xd * (float) xq[11]);
322        acc12 += w12 * (xd * (float) xq[12]);
323        acc13 += w13 * (xd * (float) xq[13]);
324        acc14 += w14 * (xd * (float) xq[14]);
325        acc15 += w15 * (xd * (float) xq[15]);
326    }
327    // the last, partial quad - at most one per lane
328    for (; i < n_in; i += 32 * QE) {
329        for (int k = 0; k < QE && i + k < n_in; ++k) {
330            const long long e = i + k;
331            const long long g = e >> group_shift;
332            const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK;
333            acc0 += (decode_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * s[g] + (off ? off[g] : 0.0f)) * (Q8K ? q8k_at(x, e) : q8_0_at(x, e));
334        }
335    }
336    float acc = (((acc0 + acc1) + (acc2 + acc3)) + ((acc4 + acc5) + (acc6 + acc7))) +
337                (((acc8 + acc9) + (acc10 + acc11)) + ((acc12 + acc13) + (acc14 + acc15)));
338    /*
339DPCT1108: '__shfl_down_sync' was migrated with the experimental feature
340masked sub_group function which may not be supported by all compilers or
341runtimes. You may need to adjust the code.
342*/
343#pragma unroll
344    for (int step = 16; step > 0; step >>= 1) acc +=
345        dpct::experimental::shift_sub_group_left(
346            0xFFFFFFFFu, sycl::ext::oneapi::this_work_item::get_sub_group(),
347            acc, step);
348    if (lane == 0) y[o] = acc;
349}
350
351template <int CODE_BITS>
352__dpct_inline__ void
353s_gemv_kernel(const uint16_t *__restrict__ x, const uint8_t *__restrict__ codes,
354              const float *__restrict__ scales,
355              const float *__restrict__ offset, float *__restrict__ y,
356              long long n_in, long long n_out, int bias, int codebook,
357              int group_elems, int has_offset) {
358    // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block.  See the note on `kIq4Nl`.
359    // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread
360    // that returned first would leave the others waiting at a barrier it never reaches.
361    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
362auto &s_iq4nl =
363    *sycl::ext::oneapi::group_local_memory_for_overwrite<signed char[16]>(
364        sycl::ext::oneapi::this_work_item::get_work_group<3>());
365    if (item_ct1.get_local_id(2) < 16) s_iq4nl[item_ct1.get_local_id(2)] =
366        kIq4Nl[item_ct1.get_local_id(2)];
367    item_ct1.barrier(sycl::access::fence_space::local_space);
368    const long long o =
369        (long long)item_ct1.get_group(2) * item_ct1.get_local_range(2) +
370        item_ct1.get_local_id(2);
371    if (o >= n_out) return;
372
373    constexpr int PER_BYTE = 8 / CODE_BITS;
374    const long long n_groups = n_in / group_elems;
375    const long long codes_per_row = n_in / PER_BYTE;
376    const uint8_t* c = codes + o * codes_per_row;
377    const float* s = scales + o * n_groups;
378    const float* off = has_offset ? offset + o * n_groups : nullptr;
379
380    float acc = 0.0f;
381    for (long long g = 0; g < n_groups; ++g) {
382        const float d = s[g];
383        const float b = off ? off[g] : 0.0f;
384        const long long base = g * (long long) group_elems;
385        for (int j = 0; j < group_elems; ++j) {
386            const long long i = base + j;
387            const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1);
388            // The offset belongs to the WEIGHT, so it is applied to the decoded value BEFORE the activation
389            // multiply: `w = code*scale + offset; acc += w * x`.  Writing `acc += code*scale*x + offset*x`
390            // computes a mathematically equal expression that ROUNDS DIFFERENTLY, because it performs two
391            // multiplications and an addition where this performs one of each.  The no-offset types cannot
392            // tell the difference - which is why this was wrong until the Q4_K case was added.
393            const float w = decode_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * d + b;
394            acc += w * sycl::vec<sycl::half, 1>(
395                           sycl::bit_cast<sycl::half, unsigned short>(x[i]))
396                           .convert<float, sycl::rounding_mode::automatic>()[0];
397        }
398    }
399    y[o] = acc;
400}
401
402}  // namespace
403
404void s_gemv(const uint16_t *x, const uint8_t *codes, const float *scales,
405            const float *offset, float *y, int64_t n_in, int64_t n_out,
406            const SForm &form) try {
407    if (n_in <= 0 || n_out <= 0) return;
408    if (form.group_elems <= 0 || n_in % form.group_elems != 0) {
409        std::fprintf(stderr, "s_gemv: n_in %lld is not a multiple of group_elems %d\n", (long long) n_in,
410                     form.group_elems);
411        std::exit(1);
412    }
413    if (form.has_offset && offset == nullptr) {
414        std::fprintf(stderr, "s_gemv: form says has_offset but offset is null\n");
415        std::exit(1);
416    }
417    const int threads = 128;
418    const long long blocks = (n_out + threads - 1) / threads;
419    const int cb = (int) form.codebook;
420    switch (form.code_bits) {
421    case 2: {
422        auto exp_props = sycl::ext::oneapi::experimental::properties{
423            sycl::ext::oneapi::experimental::use_root_sync};
424
425        strata::kprof::kp(&dpct::get_in_order_queue(), __FILE__, __func__, __LINE__)
426            ->template parallel_for<dpct_kernel_name<class s_gemv_kernel_4f63f9,
427                                           dpct_kernel_scalar<2>>>(
428                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)blocks) *
429                                      sycl::range(1, 1, threads),
430                                  sycl::range(1, 1, threads)),
431                exp_props, [=](sycl::nd_item<3> item_ct1) {
432                    s_gemv_kernel<2>(x, codes, scales, offset, y, n_in, n_out,
433                                     form.code_bias, cb, form.group_elems,
434                                     form.has_offset ? 1 : 0);
435                });
436    } break;
437    case 4: {
438        auto exp_props = sycl::ext::oneapi::experimental::properties{
439            sycl::ext::oneapi::experimental::use_root_sync};
440
441        strata::kprof::kp(&dpct::get_in_order_queue(), __FILE__, __func__, __LINE__)
442            ->template parallel_for<dpct_kernel_name<class s_gemv_kernel_9c529a,
443                                           dpct_kernel_scalar<4>>>(
444                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)blocks) *
445                                      sycl::range(1, 1, threads),
446                                  sycl::range(1, 1, threads)),
447                exp_props, [=](sycl::nd_item<3> item_ct1) {
448                    s_gemv_kernel<4>(x, codes, scales, offset, y, n_in, n_out,
449                                     form.code_bias, cb, form.group_elems,
450                                     form.has_offset ? 1 : 0);
451                });
452    } break;
453    case 8: {
454        auto exp_props = sycl::ext::oneapi::experimental::properties{
455            sycl::ext::oneapi::experimental::use_root_sync};
456
457        strata::kprof::kp(&dpct::get_in_order_queue(), __FILE__, __func__, __LINE__)
458            ->template parallel_for<dpct_kernel_name<class s_gemv_kernel_e40e1f,
459                                           dpct_kernel_scalar<8>>>(
460                sycl::nd_range<3>(sycl::range(1, 1, (unsigned)blocks) *
461                                      sycl::range(1, 1, threads),
462                                  sycl::range(1, 1, threads)),
463                exp_props, [=](sycl::nd_item<3> item_ct1) {
464                    s_gemv_kernel<8>(x, codes, scales, offset, y, n_in, n_out,
465                                     form.code_bias, cb, form.group_elems,
466                                     form.has_offset ? 1 : 0);
467                });
468    } break;
469        default:
470            std::fprintf(stderr, "s_gemv: unsupported code_bits %d\n", form.code_bits);
471            std::exit(1);
472    }
473    const dpct::err0 e =
474        DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw());
475}
476catch (sycl::exception const &exc) {
477  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
478            << ", line:" << __LINE__ << std::endl;
479  std::exit(1);
480}
481
482namespace {
483
484// One BLOCK per output row, `threads_per_row` threads splitting it.  Parallelism becomes
485// n_out * threads_per_row instead of n_out, which is the whole point: gate/up is [2560 x 640] and 640 threads
486// cannot fill 48 SMs.
487//
488// The reduction is a fixed tree over shared memory rather than atomics, so the result is DETERMINISTIC for a
489// given threads_per_row - a race would make the parity test flaky rather than wrong, which is the worst kind
490// of failing test.
491// NOTE ON `g = e >> group_shift`.  The group index was `e / group_elems` with `group_elems` a RUNTIME value,
492// and a 64-bit integer division on this hardware is a long instruction sequence - one per element, in the
493// hottest loop in the engine.  Every group size this format defines is a POWER OF TWO (16, 32, 64), so the
494// divisor is passed as its logarithm and the division becomes a shift.  The host wrapper refuses a
495// non-power-of-two group rather than silently computing a wrong index.
496template <int CODE_BITS>
497/*
498DPCT1110: The total declared local variable size in device function
499s_gemv_split_kernel exceeds 128 bytes and may cause high register pressure.
500Consult with your hardware vendor to find the total register size available and
501adjust the code, or use smaller sub-group size to avoid high register pressure.
502*/
503__dpct_inline__ void s_gemv_split_kernel(
504    const uint16_t *__restrict__ x, const uint8_t *__restrict__ codes,
505    const float *__restrict__ scales, const float *__restrict__ offset,
506    float *__restrict__ y, long long n_in, long long n_out, int bias,
507    int codebook, int group_elems, int group_shift, int has_offset,
508    int threads_per_row, uint8_t *dpct_local) {
509    auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
510    auto partial = (float *)dpct_local;
511    // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block.  See the note on `kIq4Nl`.
512    // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread
513    // that returned first would leave the others waiting at a barrier it never reaches.
514    auto &s_iq4nl =
515        *sycl::ext::oneapi::group_local_memory_for_overwrite<signed char[16]>(
516            sycl::ext::oneapi::this_work_item::get_work_group<3>());
517    if (item_ct1.get_local_id(2) < 16) s_iq4nl[item_ct1.get_local_id(2)] =
518        kIq4Nl[item_ct1.get_local_id(2)];
519    item_ct1.barrier(sycl::access::fence_space::local_space);
520    const long long o = item_ct1.get_group(2);
521    if (o >= n_out) return;
522    const int tid = item_ct1.get_local_id(2);
523
524    constexpr int PER_BYTE = 8 / CODE_BITS;
525    const long long n_groups = n_in / group_elems;
526    const uint8_t* c = codes + o * (n_in / PER_BYTE);
527    const float* s = scales + o * n_groups;
528    const float* off = has_offset ? offset + o * n_groups : nullptr;
529
530    // FOUR ACCUMULATORS, NOT ONE.  L2 measured this kernel at 0.4% of FP32 peak and 2.1% of bandwidth, so
531    // neither limit is the constraint - the constraint is the DEPENDENCY CHAIN: a single `acc += ...` serialises
532    // every FMA behind the previous one's latency (4-6 cycles each, ~1 per 4 cycles achieved), so the SM sits
533    // idle.  Four independent accumulators let the scheduler keep four FMAs in flight, and the loop is
534    // unrolled by four so the four chains are interleaved.  The summation ORDER changes, which is why the
535    // parity test carries a tolerance and why this kernel's output is checked against the naive one.
536    // FOUR CONSECUTIVE ELEMENTS PER THREAD, from ONE code load and ONE scale - the same transformation the
537    // Q8_K kernel got, for the same reason and with the same guard (`s_gemv_parity`).  See the long note there
538    // for the bit order, which is unchanged, and for why the group size is passed as a shift.
539    //
540    // THIS KERNEL IS THE ONE `attn_output` AND `shared_expert` USE, so the fix has to exist in both or half the
541    // model keeps the old instruction count.
542    constexpr int QE = 4;
543    constexpr int QB = QE * CODE_BITS / 8;             // 1 for S2, 2 for S4, 4 for S8
544    constexpr unsigned MASK = (1u << CODE_BITS) - 1u;
545    float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f;
546    long long i = (long long) tid * QE;
547    for (; i + QE <= n_in; i += (long long) threads_per_row * QE) {
548        const long long g = i >> group_shift;
549        const float d = s[g];
550        const float b = off ? off[g] : 0.0f;
551        const uint8_t* cp = c + i / PER_BYTE;
552        unsigned v;
553        if (QB == 1) v = cp[0];
554        else if (QB == 2) v = *(const uint16_t*) cp;
555        else v = *(const uint32_t*) cp;
556        // four halves in ONE 8-byte load; `i` is a multiple of four, so `x + i` is 8-byte aligned
557        const sycl::float2 f01 =
558            (*reinterpret_cast<const sycl::half2 *>(x + i))
559                .template convert<float, sycl::rounding_mode::automatic>();
560        const sycl::float2 f23 =
561            (*reinterpret_cast<const sycl::half2 *>(x + i + 2))
562                .template convert<float, sycl::rounding_mode::automatic>();
563        acc0 +=
564            (decode_tbl<CODE_BITS>((int)(v & MASK), bias, codebook, s_iq4nl) *
565                 d +
566             b) *
567            f01.x();
568        acc1 += (decode_tbl<CODE_BITS>((int)((v >> CODE_BITS) & MASK), bias,
569                                       codebook, s_iq4nl) *
570                     d +
571                 b) *
572                f01.y();
573        acc2 += (decode_tbl<CODE_BITS>((int)((v >> (2 * CODE_BITS)) & MASK),
574                                       bias, codebook, s_iq4nl) *
575                     d +
576                 b) *
577                f23.x();
578        acc3 += (decode_tbl<CODE_BITS>((int)((v >> (3 * CODE_BITS)) & MASK),
579                                       bias, codebook, s_iq4nl) *
580                     d +
581                 b) *
582                f23.y();
583    }
584    // the last, partial quad - at most one per thread
585    for (; i < n_in; i += (long long) threads_per_row * QE) {
586        for (int k = 0; k < QE && i + k < n_in; ++k) {
587            const long long e = i + k;
588            const long long g = e >> group_shift;
589            const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK;
590            acc0 +=
591                (decode_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * s[g] +
592                 (off ? off[g] : 0.0f)) *
593                sycl::vec<sycl::half, 1>(
594                    sycl::bit_cast<sycl::half, unsigned short>(x[e]))
595                    .convert<float, sycl::rounding_mode::automatic>()[0];
596        }
597    }
598    partial[tid] = (acc0 + acc1) + (acc2 + acc3);
599    item_ct1.barrier(sycl::access::fence_space::local_space);
600#pragma unroll
601    for (int step = threads_per_row / 2; step > 0; step >>= 1) {
602        if (tid < step) partial[tid] += partial[tid + step];
603        /*
604        DPCT1118: SYCL group functions and algorithms must be encountered in
605        converged control flow. You may need to adjust the code.
606        */
607        item_ct1.barrier(sycl::access::fence_space::local_space);
608    }
609    if (tid == 0) y[o] = partial[0];
610}
611
612}  // namespace
613
614static void s_gemv_split_impl(const uint16_t *x, const uint8_t *codes,
615                              const float *scales, const float *offset,
616                              float *y, int64_t n_in, int64_t n_out,
617                              const SForm &form, int threads_per_row,
618                              dpct::queue_ptr stream, bool sync) try {
619    if (n_in <= 0 || n_out <= 0) return;
620    if (threads_per_row < 1 || (threads_per_row & (threads_per_row - 1)) != 0 || threads_per_row > 1024) {
621        std::fprintf(stderr, "s_gemv_split: threads_per_row must be a power of two in 1..1024, got %d\n",
622                     threads_per_row);
623        std::exit(1);
624    }
625    const int cb = (int) form.codebook;
626    // Every group size this format defines is a power of two, which is what lets the per-element group index
627    // be a shift.  Refuse anything else rather than compute a wrong index quietly.
628    if (form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0) {
629        std::fprintf(stderr, "s_gemv_split: group_elems must be a power of two, got %d\n", form.group_elems);
630        std::exit(1);
631    }
632    // AND THE QUAD MUST FIT INSIDE ONE GROUP: four consecutive elements share a scale and the kernel reads
633    // exactly one.  Every group size this format defines is 16, 32 or 64, so this cannot fire on a real pack.
634    if (form.group_elems % 4 != 0) {
635        std::fprintf(stderr, "s_gemv_split: group_elems %d is not a multiple of 4\n", form.group_elems);
636        std::exit(1);
637    }
638    int group_shift = 0;
639    while ((1 << group_shift) < form.group_elems) ++group_shift;
640    /*
641    DPCT1083: The size of local memory in the migrated code may be different
642    from the original code. Check that the allocated memory size in the migrated
643    code is correct.
644    */
645    const size_t smem = (size_t)threads_per_row * sizeof(float);
646    const unsigned grid = (unsigned) n_out;
647    switch (form.code_bits) {
648        case 2:
649            /*
650            DPCT1049: The work-group size passed to the SYCL kernel may
651            exceed the limit. To get the device limit, query
652            info::device::max_work_group_size. Adjust the work-group size if
653            needed.
654            */
655        {
656            auto exp_props = sycl::ext::oneapi::experimental::properties{
657                sycl::ext::oneapi::experimental::use_root_sync};
658            dpct::has_capability_or_fail(stream->get_device(),
659                                         {sycl::aspect::fp16});
660
661            strata::kprof::kp(stream, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
662                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
663                    sycl::range(smem), cgh);
664
665                cgh.parallel_for<dpct_kernel_name<
666                    class s_gemv_split_kernel_8538ef, dpct_kernel_scalar<2>>>(
667                    sycl::nd_range<3>(sycl::range(1, 1, grid) *
668                                          sycl::range(1, 1, threads_per_row),
669                                      sycl::range(1, 1, threads_per_row)),
670                    exp_props, [=](sycl::nd_item<3> item_ct1) {
671                        s_gemv_split_kernel<2>(
672                            x, codes, scales, offset, y, n_in, n_out,
673                            form.code_bias, cb, form.group_elems, group_shift,
674                            form.has_offset ? 1 : 0, threads_per_row,
675                            dpct_local_acc_ct1
676                                .get_multi_ptr<sycl::access::decorated::no>()
677                                .get());
678                    });
679            });
680        }
681            break;
682        case 4:
683            /*
684            DPCT1049: The work-group size passed to the SYCL kernel may
685            exceed the limit. To get the device limit, query
686            info::device::max_work_group_size. Adjust the work-group size if
687            needed.
688            */
689        {
690            auto exp_props = sycl::ext::oneapi::experimental::properties{
691                sycl::ext::oneapi::experimental::use_root_sync};
692            dpct::has_capability_or_fail(stream->get_device(),
693                                         {sycl::aspect::fp16});
694
695            strata::kprof::kp(stream, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
696                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
697                    sycl::range(smem), cgh);
698
699                cgh.parallel_for<dpct_kernel_name<
700                    class s_gemv_split_kernel_6cb7af, dpct_kernel_scalar<4>>>(
701                    sycl::nd_range<3>(sycl::range(1, 1, grid) *
702                                          sycl::range(1, 1, threads_per_row),
703                                      sycl::range(1, 1, threads_per_row)),
704                    exp_props, [=](sycl::nd_item<3> item_ct1) {
705                        s_gemv_split_kernel<4>(
706                            x, codes, scales, offset, y, n_in, n_out,
707                            form.code_bias, cb, form.group_elems, group_shift,
708                            form.has_offset ? 1 : 0, threads_per_row,
709                            dpct_local_acc_ct1
710                                .get_multi_ptr<sycl::access::decorated::no>()
711                                .get());
712                    });
713            });
714        }
715            break;
716        case 8:
717            /*
718            DPCT1049: The work-group size passed to the SYCL kernel may
719            exceed the limit. To get the device limit, query
720            info::device::max_work_group_size. Adjust the work-group size if
721            needed.
722            */
723        {
724            auto exp_props = sycl::ext::oneapi::experimental::properties{
725                sycl::ext::oneapi::experimental::use_root_sync};
726            dpct::has_capability_or_fail(stream->get_device(),
727                                         {sycl::aspect::fp16});
728
729            strata::kprof::kp(stream, __FILE__, __func__, __LINE__)->submit([&](sycl::handler &cgh) {
730                sycl::local_accessor<uint8_t, 1> dpct_local_acc_ct1(
731                    sycl::range(smem), cgh);
732
733                cgh.parallel_for<dpct_kernel_name<
734                    class s_gemv_split_kernel_63886c, dpct_kernel_scalar<8>>>(
735                    sycl::nd_range<3>(sycl::range(1, 1, grid) *
736                                          sycl::range(1, 1, threads_per_row),
737                                      sycl::range(1, 1, threads_per_row)),
738                    exp_props, [=](sycl::nd_item<3> item_ct1) {
739                        s_gemv_split_kernel<8>(
740                            x, codes, scales, offset, y, n_in, n_out,
741                            form.code_bias, cb, form.group_elems, group_shift,
742                            form.has_offset ? 1 : 0, threads_per_row,
743                            dpct_local_acc_ct1
744                                .get_multi_ptr<sycl::access::decorated::no>()
745                                .get());
746                    });
747            });
748        }
749            break;
750        default:
751            std::fprintf(stderr, "s_gemv_split: unsupported code_bits %d\n", form.code_bits);
752            std::exit(1);
753    }
754    if (sync) {
755        const dpct::err0 e = DPCT_CHECK_ERROR(
756            dpct::get_current_device().queues_wait_and_throw());
757    }
758}
759catch (sycl::exception const &exc) {
760  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
761            << ", line:" << __LINE__ << std::endl;
762  std::exit(1);
763}
764
765void s_gemv_split(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset,
766                  float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row) {
767    s_gemv_split_impl(x, codes, scales, offset, y, n_in, n_out, form,
768                      threads_per_row,
769                      (dpct::queue_ptr)&dpct::get_in_order_queue(), true);
770}
771
772void s_gemv_split_async(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset,
773                        float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row,
774                        void* stream) {
775    s_gemv_split_impl(x, codes, scales, offset, y, n_in, n_out, form,
776                      threads_per_row, strata::q_of(stream), false);
777}
778
779// ---- the Q8_K entry points -----------------------------------------------------------------------------
780
781namespace {
782
783bool q8k_form_ok(const SForm& form, int64_t n_in, const char* who) {
784    if (form.group_elems <= 0 || n_in % form.group_elems != 0) {
785        std::fprintf(stderr, "%s: n_in %lld is not a multiple of group_elems %d\n", who, (long long) n_in,
786                     form.group_elems);
787        return false;
788    }
789    if (n_in % Q8K_BLOCK_ELEMS != 0) {
790        // `quantize_q8_K` requires this too, and a partial block would read past the end of the activation.
791        std::fprintf(stderr, "%s: n_in %lld is not a multiple of the Q8_K block %d\n", who, (long long) n_in,
792                     Q8K_BLOCK_ELEMS);
793        return false;
794    }
795    return true;
796}
797
798void finish(const char *who, void *stream) try {
799    /*
800    DPCT1010: SYCL uses exceptions to report errors and does not use the
801    error codes. The cudaGetLastError function call was replaced with 0. You
802    need to rewrite this code.
803    */
804    const dpct::err0 e = 0;
805
806    if (stream != nullptr) return;
807    const dpct::err0 s =
808        DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw());
809}
810catch (sycl::exception const &exc) {
811  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
812            << ", line:" << __LINE__ << std::endl;
813  std::exit(1);
814}
815
816}  // namespace
817
818void s_gemv_q8k(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, float* y,
819                int64_t n_in, int64_t n_out, const SForm& form, void* stream) {
820    if (n_in <= 0 || n_out <= 0) return;
821    if (!q8k_form_ok(form, n_in, "s_gemv_q8k")) std::exit(1);
822    const int threads = 128;
823    const unsigned blocks = (unsigned) ((n_out + threads - 1) / threads);
824    const int cb = (int) form.codebook;
825    const int ho = form.has_offset ? 1 : 0;
826    switch (form.code_bits) {
827    case 4: {
828        auto exp_props = sycl::ext::oneapi::experimental::properties{
829            sycl::ext::oneapi::experimental::use_root_sync};
830
831        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
832            ->template parallel_for<dpct_kernel_name<class s_gemv_q8k_kernel_9b1637,
833                                            dpct_kernel_scalar<4>>>(
834                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
835                                      sycl::range(1, 1, threads),
836                                  sycl::range(1, 1, threads)),
837                exp_props, [=](sycl::nd_item<3> item_ct1) {
838                    s_gemv_q8k_kernel<4>(x_q8k, codes, scales, offset, y, n_in,
839                                         n_out, form.code_bias, cb,
840                                         form.group_elems, ho);
841                });
842    } break;
843    case 8: {
844        auto exp_props = sycl::ext::oneapi::experimental::properties{
845            sycl::ext::oneapi::experimental::use_root_sync};
846
847        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
848            ->template parallel_for<dpct_kernel_name<class s_gemv_q8k_kernel_adeed5,
849                                            dpct_kernel_scalar<8>>>(
850                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
851                                      sycl::range(1, 1, threads),
852                                  sycl::range(1, 1, threads)),
853                exp_props, [=](sycl::nd_item<3> item_ct1) {
854                    s_gemv_q8k_kernel<8>(x_q8k, codes, scales, offset, y, n_in,
855                                         n_out, form.code_bias, cb,
856                                         form.group_elems, ho);
857                });
858    } break;
859        default:
860            // 2-bit S2 never has a Q8_K activation: its `vec_dot_type` is Q8_0.  Refusing is better than
861            // running a kernel that would be numerically wrong in a way the caller cannot see.
862            std::fprintf(stderr, "s_gemv_q8k: code_bits %d has no Q8_K contract "
863                                 "(S2 uses Q8_0; see docs/activation-contract.md)\n", form.code_bits);
864            std::exit(1);
865    }
866    finish("s_gemv_q8k", stream);
867}
868
869void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset,
870                      float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream) {
871    if (n_in <= 0 || n_out <= 0) return;
872    if (!q8k_form_ok(form, n_in, "s_gemv_q8k_split")) std::exit(1);
873    // THE GROUP SIZE IS PASSED AS ITS LOGARITHM: see the note on the kernel.  A non-power-of-two group would
874    // make the shift a WRONG INDEX rather than a slow one, so it is refused here.
875    int group_shift = 0;
876    while ((1 << group_shift) < form.group_elems) ++group_shift;
877    if ((1 << group_shift) != form.group_elems) {
878        std::fprintf(stderr, "s_gemv_q8k_split: group_elems %d is not a power of two\n", form.group_elems);
879        std::exit(1);
880    }
881    // AND THE QUAD MUST FIT INSIDE ONE GROUP.  Four consecutive elements share a scale, so a group smaller
882    // than four would need two of them and the kernel reads exactly one.  Every group size this format
883    // defines is 16, 32 or 64, so this cannot fire on a real pack - it is here because a future one could.
884    if (form.group_elems % 16 != 0) {
885        std::fprintf(stderr, "s_gemv_q8k_split: group_elems %d is not a multiple of 16\n", form.group_elems);
886        std::exit(1);
887    }
888    const int threads = 256;
889    const int warps = threads / 32;
890    const unsigned blocks = (unsigned) ((n_out + warps - 1) / warps);
891    const int cb = (int) form.codebook;
892    const int ho = form.has_offset ? 1 : 0;
893    switch (form.code_bits) {
894    case 4: {
895        auto exp_props = sycl::ext::oneapi::experimental::properties{
896            sycl::ext::oneapi::experimental::use_root_sync};
897
898        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
899            ->template parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_19ad26,
900                                            dpct_kernel_scalar<4>,
901                                            dpct_kernel_scalar<true>>>(
902                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
903                                      sycl::range(1, 1, threads),
904                                  sycl::range(1, 1, threads)),
905                exp_props,
906                [=](sycl::nd_item<3> item_ct1)
907                    [[sycl::reqd_sub_group_size(32)]] {
908                        s_gemv_q8_split_kernel<4, true>(
909                            x_q8k, codes, scales, offset, y, n_in, n_out,
910                            form.code_bias, cb, group_shift, ho);
911                    });
912    } break;
913    case 8: {
914        auto exp_props = sycl::ext::oneapi::experimental::properties{
915            sycl::ext::oneapi::experimental::use_root_sync};
916
917        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
918            ->template parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_4da4f5,
919                                            dpct_kernel_scalar<8>,
920                                            dpct_kernel_scalar<true>>>(
921                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
922                                      sycl::range(1, 1, threads),
923                                  sycl::range(1, 1, threads)),
924                exp_props,
925                [=](sycl::nd_item<3> item_ct1)
926                    [[sycl::reqd_sub_group_size(32)]] {
927                        s_gemv_q8_split_kernel<8, true>(
928                            x_q8k, codes, scales, offset, y, n_in, n_out,
929                            form.code_bias, cb, group_shift, ho);
930                    });
931    } break;
932        default:
933            std::fprintf(stderr, "s_gemv_q8k_split: code_bits %d has no Q8_K contract\n", form.code_bits);
934            std::exit(1);
935    }
936    finish("s_gemv_q8k_split", stream);
937}
938
939void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float* scales, const float* offset,
940                       float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream) {
941    if (n_in <= 0 || n_out <= 0) return;
942    // THE ACTIVATION IS `block_q8_0`, 32 elements per block, so `n_in` must be a multiple of 32 - which is a
943    // WEAKER requirement than Q8_K's 256 and is exactly why this kernel has to exist: `ffn_down_shexp` has
944    // n_in = 640, a multiple of 32 that is NOT a multiple of 256.
945    if (n_in % Q8_0_BLOCK_ELEMS != 0) {
946        std::fprintf(stderr, "s_gemv_q8_0_split: n_in %lld is not a multiple of %d\n", (long long) n_in,
947                     Q8_0_BLOCK_ELEMS);
948        std::exit(1);
949    }
950    // the same two checks `s_gemv_q8k_split` makes, for the same reasons - see the notes there
951    if (form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0) {
952        std::fprintf(stderr, "s_gemv_q8_0_split: group_elems must be a power of two, got %d\n",
953                     form.group_elems);
954        std::exit(1);
955    }
956    // SIXTEEN, NOT FOUR: a lane-iteration takes QE = 16 consecutive elements under ONE scale (see the kernel),
957    // so a group of 4 or 8 would read the wrong scale for most of them.  The Q8_K launcher already said 16.
958    if (form.group_elems % 16 != 0) {
959        std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 16\n", form.group_elems);
960        std::exit(1);
961    }
962    int group_shift = 0;
963    while ((1 << group_shift) < form.group_elems) ++group_shift;
964
965    const int threads = 256;
966    const int warps = threads / 32;
967    const unsigned blocks = (unsigned) ((n_out + warps - 1) / warps);
968    const int cb = (int) form.codebook;
969    const int ho = form.has_offset ? 1 : 0;
970    switch (form.code_bits) {
971    case 4: {
972        auto exp_props = sycl::ext::oneapi::experimental::properties{
973            sycl::ext::oneapi::experimental::use_root_sync};
974
975        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
976            ->template parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_147ee4,
977                                            dpct_kernel_scalar<4>,
978                                            dpct_kernel_scalar<false>>>(
979                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
980                                      sycl::range(1, 1, threads),
981                                  sycl::range(1, 1, threads)),
982                exp_props,
983                [=](sycl::nd_item<3> item_ct1)
984                    [[sycl::reqd_sub_group_size(32)]] {
985                        s_gemv_q8_split_kernel<4, false>(
986                            x_q8_0, codes, scales, offset, y, n_in, n_out,
987                            form.code_bias, cb, group_shift, ho);
988                    });
989    } break;
990    case 8: {
991        auto exp_props = sycl::ext::oneapi::experimental::properties{
992            sycl::ext::oneapi::experimental::use_root_sync};
993
994        strata::kprof::kp(strata::q_of(stream), __FILE__, __func__, __LINE__)
995            ->template parallel_for<dpct_kernel_name<class s_gemv_q8_split_kernel_bac5c0,
996                                            dpct_kernel_scalar<8>,
997                                            dpct_kernel_scalar<false>>>(
998                sycl::nd_range<3>(sycl::range(1, 1, blocks) *
999                                      sycl::range(1, 1, threads),
1000                                  sycl::range(1, 1, threads)),
1001                exp_props,
1002                [=](sycl::nd_item<3> item_ct1)
1003                    [[sycl::reqd_sub_group_size(32)]] {
1004                        s_gemv_q8_split_kernel<8, false>(
1005                            x_q8_0, codes, scales, offset, y, n_in, n_out,
1006                            form.code_bias, cb, group_shift, ho);
1007                    });
1008    } break;
1009        default:
1010            std::fprintf(stderr, "s_gemv_q8_0_split: code_bits %d has no Q8_0 contract\n", form.code_bits);
1011            std::exit(1);
1012    }
1013    finish("s_gemv_q8_0_split", stream);
1014}
1015
1016}  // namespace strata::kernels