okami.mom/strata

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

Guillaume PUTIERs_gemv: the q8 split kernel reaches its barrier before a rowless warp returns91e8d2122

main
39.9 KiB694 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#include "strata/kernels/s_gemv.hpp"
8
9#include <cuda_fp16.h>
10#include <cuda_runtime.h>
11
12#include <cstdio>
13#include <cstdlib>
14
15namespace strata::kernels {
16namespace {
17
18// `kvalues_iq4nl`: the non-linear codebook, verbatim from ggml-common.h / ggml-quants.c.
19//
20// **IT WAS IN `__constant__` FOR THE WRONG REASON, AND IT COST 2.12x.**  The old comment justified constant
21// memory with "every thread reads it and it is the same 16 values for the whole launch".  That reasoning is
22// exactly backwards: constant memory is fast when the access is UNIFORM - every lane reading the SAME address -
23// and a NON-LINEAR codebook means every lane reads a DIFFERENT index, which is the pattern it handles worst.
24//
25// Measured on `attn_qkv` (IQ4_XS, 10240 x 2560), forcing the Affine codebook so that the memory traffic and the
26// instruction count stay identical and only the table read is removed:
27//
28//     codebook probe: IQ4NL 0.2032 ms   Affine 0.0960 ms   ratio 2.12x
29//
30// `decode_tbl` below reads a SHARED copy instead: 16 bytes loaded once per block, then an index into shared
31// memory that costs at most a four-way bank conflict.  The `__constant__` array stays as the source of it.
32__constant__ signed char kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10,
33                                       1,   13,   25,  38,  53,  69,  89,  113};
34
35template <int CODE_BITS>
36__device__ __forceinline__ float decode(int code, int bias, int codebook) {
37    if (codebook == (int) Codebook::Iq4Nl) return (float) kIq4Nl[code & 0x0F];
38    return (float) (code + bias);       // the bias is applied to the CODE, in the integer domain
39}
40
41/// The same decode with the codebook in SHARED memory, which is what the hot kernels use - see the measurement
42/// above.  A divergent read of a 16-entry table is the one access pattern constant memory is worst at.
43template <int CODE_BITS>
44__device__ __forceinline__ float decode_tbl(int code, int bias, int codebook, const signed char* tbl) {
45    if (codebook == (int) Codebook::Iq4Nl) return (float) tbl[code & 0x0F];
46    return (float) (code + bias);
47}
48
49// ---- Q8_K ACTIVATIONS ----------------------------------------------------------------------------------
50//
51// 292 bytes per 256 elements: `{ f32 d ; int8_t qs[256] ; int16_t bsums[16] }`.  `bsums` is not read - it
52// exists for ggml's AVX2 dot product - but the STRIDE includes it, so a buffer from `quantize_q8_K` passes
53// straight in.
54//
55// The block's `d` sits at a 4-byte-aligned offset from the buffer base as long as the base is aligned, which
56// `cudaMalloc` guarantees.
57constexpr int Q8K_BLOCK_BYTES = 292;
58constexpr int Q8K_BLOCK_ELEMS = 256;
59
60__device__ __forceinline__ float q8k_at(const uint8_t* __restrict__ x, long long i) {
61    const uint8_t* blk = x + (i / Q8K_BLOCK_ELEMS) * Q8K_BLOCK_BYTES;
62    const float d = __ldg((const float*) blk);
63    const int8_t q = ((const int8_t*) (blk + 4))[i % Q8K_BLOCK_ELEMS];
64    return d * (float) q;
65}
66
67/// **THE Q8_0 ACTIVATION**, which is what the LEGACY block formats want: `block_q8_0` is `{fp16 d; int8 qs[32]}`,
68/// 34 bytes per 32 elements, produced by `quantize_q8_0`.
69///
70/// THE ENGINE HAD NO GEMV FOR THIS, and it was the last activation-contract gap (LEDGER L54).  It was described
71/// 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
72/// 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
73/// STRUCTURALLY IMPOSSIBLE for it rather than merely absent**.  Every other legacy tensor in the pack is Q2_0,
74/// whose attributes happen to be S2's, which is how the S2-only kernel covered them and the hole stayed hidden.
75constexpr int Q8_0_BLOCK_BYTES = 34;
76constexpr int Q8_0_BLOCK_ELEMS = 32;
77
78__device__ __forceinline__ float q8_0_at(const uint8_t* __restrict__ x, long long i) {
79    const uint8_t* blk = x + (i / Q8_0_BLOCK_ELEMS) * Q8_0_BLOCK_BYTES;
80    // a `uint16_t` needs 2-byte alignment and the stride is 34, so every block's `d` is aligned
81    const float d = __half2float(__ushort_as_half(*(const uint16_t*) blk));
82    const int8_t q = ((const int8_t*) (blk + 2))[i % Q8_0_BLOCK_ELEMS];
83    return d * (float) q;
84}
85
86/// The Q8_K path, with the SAME weight decode as `s_gemv_kernel` and a different activation loader.  The two
87/// are separate kernels rather than one templated on the activation kind because the activation POINTER TYPE
88/// differs (`uint16_t*` vs `uint8_t*`) and a templated pointer would need a cast at every call site - which is
89/// where a wrong stride would hide.
90template <int CODE_BITS>
91__global__ void s_gemv_q8k_kernel(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes,
92                                  const float* __restrict__ scales, const float* __restrict__ offset,
93                                  float* __restrict__ y, long long n_in, long long n_out, int bias,
94                                  int codebook, int group_elems, int has_offset) {
95    // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block.  See the note on `kIq4Nl`.
96    // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread
97    // that returned first would leave the others waiting at a barrier it never reaches.
98    __shared__ signed char s_iq4nl[16];
99    if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x];
100    __syncthreads();
101    const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x;
102    if (o >= n_out) return;
103
104    constexpr int PER_BYTE = 8 / CODE_BITS;
105    const long long n_groups = n_in / group_elems;
106    const long long codes_per_row = n_in / PER_BYTE;
107    const uint8_t* c = codes + o * codes_per_row;
108    const float* s = scales + o * n_groups;
109    const float* off = has_offset ? offset + o * n_groups : nullptr;
110
111    float acc = 0.0f;
112    for (long long g = 0; g < n_groups; ++g) {
113        const float d = s[g];
114        const float b = off ? off[g] : 0.0f;
115        const long long base = g * (long long) group_elems;
116        for (int j = 0; j < group_elems; ++j) {
117            const long long i = base + j;
118            const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1);
119            // The offset belongs to the WEIGHT and is applied before the activation multiply - see the note in
120            // `s_gemv_kernel`, where writing it the other way rounded differently and only the Q4_K case could
121            // tell.
122            const float w = decode_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * d + b;
123            acc += w * q8k_at(x, i);
124        }
125    }
126    y[o] = acc;
127}
128
129/// One warp per output row, lanes striding the reduction axis: for a fixed `i` consecutive lanes read
130/// consecutive activations, which is the coalescing that matters once the output width is small.
131///
132/// **`group_shift`, NOT `group_elems`, AND IT COSTS A DIVISION PER ELEMENT IF YOU GET IT WRONG.**  The
133/// sibling fp16 kernel was given this treatment ("a 64-bit integer division on this hardware is a long
134/// instruction sequence - one per element, in the hottest loop in the engine") and THIS one was not: it kept
135/// `i / group_elems` with `group_elems` a RUNTIME value, once per element, in the kernel that carries most of
136/// the model's weight bytes.  Every group size the format defines is a power of two, so the divisor is passed
137/// as its logarithm and the division becomes a shift; the host refuses a non-power-of-two group rather than
138/// computing a wrong index.
139/// ONE KERNEL FOR BOTH QUANTIZED ACTIVATIONS, templated on which block format `x` holds.  A second copy with a
140/// different loader would be a second thing to get wrong, and the only difference IS the loader - the weight
141/// decode, the quad loop, the shared codebook and the reduction are identical.
142template <int CODE_BITS, bool Q8K>
143__global__ void s_gemv_q8_split_kernel(const uint8_t* __restrict__ x, const uint8_t* __restrict__ codes,
144                                        const float* __restrict__ scales, const float* __restrict__ offset,
145                                        float* __restrict__ y, long long n_in, long long n_out, int bias,
146                                        int codebook, int group_shift, int has_offset) {
147    constexpr int PER_BYTE = 8 / CODE_BITS;
148    const int warps_per_block = (int) (blockDim.x >> 5);
149    const long long o = (long long) blockIdx.x * warps_per_block + (threadIdx.x >> 5);
150    const int lane = threadIdx.x & 31;
151
152    // THE CODEBOOK, IN SHARED MEMORY.  16 bytes, loaded once per block by the first 16 threads, instead of a
153    // divergent constant read per element - measured at 2.12x of this whole kernel (see the note on `kIq4Nl`).
154    //
155    // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN, as in `s_gemv_q8k_kernel`.  The return used to
156    // sit above them, so whenever `n_out % 8 != 0` the last block's surplus warps left before a barrier the
157    // others still waited at - undefined behaviour that every shape in the pack (a multiple of 8) happened to
158    // avoid.  `o` is per-WARP, so the return below keeps whole warps together and the shuffle reduction's
159    // full mask stays valid.
160    __shared__ signed char s_iq4nl[16];
161    if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x];
162    __syncthreads();
163    if (o >= n_out) return;
164
165    const long long n_groups = n_in >> group_shift;
166    const long long codes_per_row = n_in / PER_BYTE;
167    const uint8_t* c = codes + o * codes_per_row;
168    const float* s = scales + o * n_groups;
169    const float* off = has_offset ? offset + o * n_groups : nullptr;
170
171    float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f;
172    float acc4 = 0.0f, acc5 = 0.0f, acc6 = 0.0f, acc7 = 0.0f;
173    float acc8 = 0.0f, acc9 = 0.0f, acc10 = 0.0f, acc11 = 0.0f;
174    float acc12 = 0.0f, acc13 = 0.0f, acc14 = 0.0f, acc15 = 0.0f;
175    // ---- EIGHT CONSECUTIVE ELEMENTS PER LANE, from TWO code loads and ONE scale.
176    //
177    // **THIS IS THE EXPERIMENT THE `#pragma unroll` NOTE BELOW LEFT OPEN**, and the note said what it would
178    // be: "Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four independent 16-bit words per
179    // lane - which an unroll cannot do because the extraction code is written for exactly four codes."  So a
180    // lane now takes a double quad: two code words issued before either is consumed, which is what raises the
181    // bytes in flight.  The scale and offset are still ONE load, because eight consecutive elements lie in one
182    // group whenever `group_elems % 8 == 0` - the launcher asserts that, and every group size this format
183    // defines (16, 32, 64) satisfies it.
184    //
185    // The loop used to take `i = lane, lane+32, ...` - a STRIDE, chosen so consecutive lanes read consecutive
186    // activations - and paid a code load, a shift-and-mask, and a scale load FOR EVERY ELEMENT.  But four
187    // consecutive elements share one code word (1, 2 or 4 bytes depending on width) and lie in one group,
188    // because every group size this format defines is a multiple of four.  So a lane takes a QUAD:
189    //
190    //     one code load        instead of four
191    //     one scale load       instead of four
192    //     one shift per element instead of a divide, a modulo and a shift
193    //
194    // THE BIT ORDER IS THE SAME ONE, verified for all three widths: element `i+k` is bits
195    // `[k*CODE_BITS, (k+1)*CODE_BITS)` of the little-endian word at byte `i/PER_BYTE`, which is what the old
196    // `(c[e/PER_BYTE] >> ((e%PER_BYTE)*CODE_BITS)) & MASK` computed one element at a time.
197    //
198    // THE SUMMATION ORDER CHANGES, which is why `s_gemv_parity` and `s_gemv_q8k_parity` carry tolerances and
199    // compare against the naive kernel - they are the guard for this, and they are the reason it is safe to do.
200    constexpr int QE = 16;
201    // BYTES PER FOUR-CODE WORD, not per octet.  The two are easy to confuse and the first version of this
202    // did: it branched on the octet's total width and so read a uint32 for S4 (whose four codes are a
203    // uint16) and single bytes for S8 (whose four codes are a uint32).  `s_gemv_q8k_parity` failed on
204    // exactly that, which is what it is for.
205    constexpr int QW = 4 * CODE_BITS / 8;              // 1 for S2, 2 for S4, 4 for S8
206    constexpr unsigned MASK = (1u << CODE_BITS) - 1u;
207    long long i = (long long) lane * QE;
208    // **`#pragma unroll 4` WAS TRIED HERE AND DID NOTHING.**  Measured: 184.6 -> 183.9 GB/s at n_out 10240,
209    // with `s_gemv_parity` and `s_gemv_q8k_parity` both still clean.  The hypothesis it was testing is L93 -
210    // that this kernel's flat ~6 ns per output row is a bytes-in-flight limit, one code load and one scale
211    // load per lane-iteration with only 20 iterations.  A 4x unroll issues four of each before the first is
212    // consumed, so either the compiler was already doing it or **the limit is not instruction scheduling.**
213    // Removed rather than kept, because a hint that does not change the timing is a claim that is not true.
214    //
215    // What it does NOT rule out is the structural version of the same idea: QE is 4, so a lane consumes ONE
216    // 2-byte code word per iteration.  Widening QE to 8 or 16 changes the LOADS THEMSELVES - two or four
217    // independent 16-bit words per lane - which an unroll cannot do because the extraction code is written for
218    // exactly four codes.  That is the experiment that would settle it, and it is not this one.
219    for (; i + QE <= n_in; i += 32 * QE) {
220        const long long g = i >> group_shift;          // the whole octet is in one group: group_elems % 8 == 0
221        const float d = s[g];
222        const float b = off ? off[g] : 0.0f;
223        const uint8_t* cp = c + i / PER_BYTE;
224        unsigned v, v2, v3, v4;
225        if (QW == 1) { v = cp[0]; v2 = cp[1]; v3 = cp[2]; v4 = cp[3]; }
226        else if (QW == 2) { v = *(const uint16_t*) cp; v2 = *(const uint16_t*) (cp + 2);
227                            v3 = *(const uint16_t*) (cp + 4); v4 = *(const uint16_t*) (cp + 6); }
228        else { v = *(const uint32_t*) cp; v2 = *(const uint32_t*) (cp + 4);
229               v3 = *(const uint32_t*) (cp + 8); v4 = *(const uint32_t*) (cp + 12); }
230        // ---- THE ACTIVATION BLOCK IS HOISTED OUT OF THE SIXTEEN ELEMENTS, AND THAT WAS THE KERNEL'S COST.
231        //
232        // `q8k_at(x, i + k)` computes `(i + k) / 256` and `(i + k) % 256` on EVERY call: a 64-bit integer
233        // division AND modulo per element, sixteen times per lane-iteration.  A 64-bit division on a GPU is a
234        // software routine of roughly a hundred cycles, and the compiler cannot strength-reduce it because it
235        // cannot prove `(i + k) / 256 == i / 256` without knowing `i % 256`.
236        //
237        // But `QE` is 16, `Q8K_BLOCK_ELEMS` is 256 and `Q8_0_BLOCK_ELEMS` is 32, and the loop advances `i` by
238        // `32 * QE`.  So `i % 256` and `i % 32` are ALWAYS multiples of 16 - which means all QE elements of one
239        // lane-iteration lie inside ONE block, for either activation kind.  One division and one modulo per
240        // iteration replace sixteen of each, and the sixteen activations become sixteen consecutive int8 loads
241        // from a pointer computed once.
242        //
243        // This is exact, not an approximation: `xi + QE <= blk_elems` holds for every reachable `xi`, so no
244        // lane-iteration can straddle a block boundary.  The tail loop below still uses the accessors because
245        // its elements do not share a block, and it runs at most once per lane.
246        const int blk_elems = Q8K ? Q8K_BLOCK_ELEMS : Q8_0_BLOCK_ELEMS;
247        const uint8_t* xb = x + (i / blk_elems) * (Q8K ? Q8K_BLOCK_BYTES : Q8_0_BLOCK_BYTES);
248        const int xi = (int) (i % blk_elems);
249        const float xd = Q8K ? __ldg((const float*) xb)
250                             : __half2float(__ushort_as_half(*(const uint16_t*) xb));
251        const int8_t* xq = (const int8_t*) (xb + (Q8K ? 4 : 2)) + xi;
252
253        const float w0 = decode_tbl<CODE_BITS>((int) (v & MASK), bias, codebook, s_iq4nl) * d + b;
254        const float w1 = decode_tbl<CODE_BITS>((int) ((v >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
255        const float w2 = decode_tbl<CODE_BITS>((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
256        const float w3 = decode_tbl<CODE_BITS>((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
257        const float w4 = decode_tbl<CODE_BITS>((int) (v2 & MASK), bias, codebook, s_iq4nl) * d + b;
258        const float w5 = decode_tbl<CODE_BITS>((int) ((v2 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
259        const float w6 = decode_tbl<CODE_BITS>((int) ((v2 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
260        const float w7 = decode_tbl<CODE_BITS>((int) ((v2 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
261        acc0 += w0 * (xd * (float) xq[0]);
262        acc1 += w1 * (xd * (float) xq[1]);
263        acc2 += w2 * (xd * (float) xq[2]);
264        acc3 += w3 * (xd * (float) xq[3]);
265        acc4 += w4 * (xd * (float) xq[4]);
266        acc5 += w5 * (xd * (float) xq[5]);
267        acc6 += w6 * (xd * (float) xq[6]);
268        acc7 += w7 * (xd * (float) xq[7]);
269        const float w8  = decode_tbl<CODE_BITS>((int) (v3 & MASK), bias, codebook, s_iq4nl) * d + b;
270        const float w9  = decode_tbl<CODE_BITS>((int) ((v3 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
271        const float w10 = decode_tbl<CODE_BITS>((int) ((v3 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
272        const float w11 = decode_tbl<CODE_BITS>((int) ((v3 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
273        const float w12 = decode_tbl<CODE_BITS>((int) (v4 & MASK), bias, codebook, s_iq4nl) * d + b;
274        const float w13 = decode_tbl<CODE_BITS>((int) ((v4 >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b;
275        const float w14 = decode_tbl<CODE_BITS>((int) ((v4 >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
276        const float w15 = decode_tbl<CODE_BITS>((int) ((v4 >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b;
277        acc8  += w8  * (xd * (float) xq[8]);
278        acc9  += w9  * (xd * (float) xq[9]);
279        acc10 += w10 * (xd * (float) xq[10]);
280        acc11 += w11 * (xd * (float) xq[11]);
281        acc12 += w12 * (xd * (float) xq[12]);
282        acc13 += w13 * (xd * (float) xq[13]);
283        acc14 += w14 * (xd * (float) xq[14]);
284        acc15 += w15 * (xd * (float) xq[15]);
285    }
286    // the last, partial quad - at most one per lane
287    for (; i < n_in; i += 32 * QE) {
288        for (int k = 0; k < QE && i + k < n_in; ++k) {
289            const long long e = i + k;
290            const long long g = e >> group_shift;
291            const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK;
292            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));
293        }
294    }
295    float acc = (((acc0 + acc1) + (acc2 + acc3)) + ((acc4 + acc5) + (acc6 + acc7))) +
296                (((acc8 + acc9) + (acc10 + acc11)) + ((acc12 + acc13) + (acc14 + acc15)));
297    for (int step = 16; step > 0; step >>= 1) acc += __shfl_down_sync(0xFFFFFFFFu, acc, step);
298    if (lane == 0) y[o] = acc;
299}
300
301template <int CODE_BITS>
302__global__ void s_gemv_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
303                              const float* __restrict__ scales, const float* __restrict__ offset,
304                              float* __restrict__ y, long long n_in, long long n_out, int bias, int codebook,
305                              int group_elems, int has_offset) {
306    // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block.  See the note on `kIq4Nl`.
307    // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread
308    // that returned first would leave the others waiting at a barrier it never reaches.
309    __shared__ signed char s_iq4nl[16];
310    if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x];
311    __syncthreads();
312    const long long o = (long long) blockIdx.x * blockDim.x + threadIdx.x;
313    if (o >= n_out) return;
314
315    constexpr int PER_BYTE = 8 / CODE_BITS;
316    const long long n_groups = n_in / group_elems;
317    const long long codes_per_row = n_in / PER_BYTE;
318    const uint8_t* c = codes + o * codes_per_row;
319    const float* s = scales + o * n_groups;
320    const float* off = has_offset ? offset + o * n_groups : nullptr;
321
322    float acc = 0.0f;
323    for (long long g = 0; g < n_groups; ++g) {
324        const float d = s[g];
325        const float b = off ? off[g] : 0.0f;
326        const long long base = g * (long long) group_elems;
327        for (int j = 0; j < group_elems; ++j) {
328            const long long i = base + j;
329            const int code = (c[i / PER_BYTE] >> ((int) (i % PER_BYTE) * CODE_BITS)) & ((1 << CODE_BITS) - 1);
330            // The offset belongs to the WEIGHT, so it is applied to the decoded value BEFORE the activation
331            // multiply: `w = code*scale + offset; acc += w * x`.  Writing `acc += code*scale*x + offset*x`
332            // computes a mathematically equal expression that ROUNDS DIFFERENTLY, because it performs two
333            // multiplications and an addition where this performs one of each.  The no-offset types cannot
334            // tell the difference - which is why this was wrong until the Q4_K case was added.
335            const float w = decode_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * d + b;
336            acc += w * __half2float(__ushort_as_half(x[i]));
337        }
338    }
339    y[o] = acc;
340}
341
342}  // namespace
343
344void s_gemv(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset, float* y,
345            int64_t n_in, int64_t n_out, const SForm& form) {
346    if (n_in <= 0 || n_out <= 0) return;
347    if (form.group_elems <= 0 || n_in % form.group_elems != 0) {
348        std::fprintf(stderr, "s_gemv: n_in %lld is not a multiple of group_elems %d\n", (long long) n_in,
349                     form.group_elems);
350        std::exit(1);
351    }
352    if (form.has_offset && offset == nullptr) {
353        std::fprintf(stderr, "s_gemv: form says has_offset but offset is null\n");
354        std::exit(1);
355    }
356    const int threads = 128;
357    const long long blocks = (n_out + threads - 1) / threads;
358    const int cb = (int) form.codebook;
359    switch (form.code_bits) {
360        case 2:
361            s_gemv_kernel<2><<<(unsigned) blocks, threads>>>(x, codes, scales, offset, y, n_in, n_out,
362                                                             form.code_bias, cb, form.group_elems,
363                                                             form.has_offset ? 1 : 0);
364            break;
365        case 4:
366            s_gemv_kernel<4><<<(unsigned) blocks, threads>>>(x, codes, scales, offset, y, n_in, n_out,
367                                                             form.code_bias, cb, form.group_elems,
368                                                             form.has_offset ? 1 : 0);
369            break;
370        case 8:
371            s_gemv_kernel<8><<<(unsigned) blocks, threads>>>(x, codes, scales, offset, y, n_in, n_out,
372                                                             form.code_bias, cb, form.group_elems,
373                                                             form.has_offset ? 1 : 0);
374            break;
375        default:
376            std::fprintf(stderr, "s_gemv: unsupported code_bits %d\n", form.code_bits);
377            std::exit(1);
378    }
379    const cudaError_t e = cudaDeviceSynchronize();
380    if (e != cudaSuccess) {
381        std::fprintf(stderr, "s_gemv: %s\n", cudaGetErrorString(e));
382        std::exit(1);
383    }
384}
385
386namespace {
387
388// One BLOCK per output row, `threads_per_row` threads splitting it.  Parallelism becomes
389// n_out * threads_per_row instead of n_out, which is the whole point: gate/up is [2560 x 640] and 640 threads
390// cannot fill 48 SMs.
391//
392// The reduction is a fixed tree over shared memory rather than atomics, so the result is DETERMINISTIC for a
393// given threads_per_row - a race would make the parity test flaky rather than wrong, which is the worst kind
394// of failing test.
395// NOTE ON `g = e >> group_shift`.  The group index was `e / group_elems` with `group_elems` a RUNTIME value,
396// and a 64-bit integer division on this hardware is a long instruction sequence - one per element, in the
397// hottest loop in the engine.  Every group size this format defines is a POWER OF TWO (16, 32, 64), so the
398// divisor is passed as its logarithm and the division becomes a shift.  The host wrapper refuses a
399// non-power-of-two group rather than silently computing a wrong index.
400template <int CODE_BITS>
401__global__ void s_gemv_split_kernel(const uint16_t* __restrict__ x, const uint8_t* __restrict__ codes,
402                                    const float* __restrict__ scales, const float* __restrict__ offset,
403                                    float* __restrict__ y, long long n_in, long long n_out, int bias,
404                                    int codebook, int group_elems, int group_shift, int has_offset,
405                                    int threads_per_row) {
406    extern __shared__ float partial[];
407    // THE CODEBOOK, IN SHARED MEMORY - 16 bytes, loaded once per block.  See the note on `kIq4Nl`.
408    // THE LOAD AND THE BARRIER COME BEFORE THE EARLY RETURN: `o` is per-THREAD in this kernel, so a thread
409    // that returned first would leave the others waiting at a barrier it never reaches.
410    __shared__ signed char s_iq4nl[16];
411    if (threadIdx.x < 16) s_iq4nl[threadIdx.x] = kIq4Nl[threadIdx.x];
412    __syncthreads();
413    const long long o = blockIdx.x;
414    if (o >= n_out) return;
415    const int tid = threadIdx.x;
416
417    constexpr int PER_BYTE = 8 / CODE_BITS;
418    const long long n_groups = n_in / group_elems;
419    const uint8_t* c = codes + o * (n_in / PER_BYTE);
420    const float* s = scales + o * n_groups;
421    const float* off = has_offset ? offset + o * n_groups : nullptr;
422
423    // FOUR ACCUMULATORS, NOT ONE.  L2 measured this kernel at 0.4% of FP32 peak and 2.1% of bandwidth, so
424    // neither limit is the constraint - the constraint is the DEPENDENCY CHAIN: a single `acc += ...` serialises
425    // every FMA behind the previous one's latency (4-6 cycles each, ~1 per 4 cycles achieved), so the SM sits
426    // idle.  Four independent accumulators let the scheduler keep four FMAs in flight, and the loop is
427    // unrolled by four so the four chains are interleaved.  The summation ORDER changes, which is why the
428    // parity test carries a tolerance and why this kernel's output is checked against the naive one.
429    // FOUR CONSECUTIVE ELEMENTS PER THREAD, from ONE code load and ONE scale - the same transformation the
430    // Q8_K kernel got, for the same reason and with the same guard (`s_gemv_parity`).  See the long note there
431    // for the bit order, which is unchanged, and for why the group size is passed as a shift.
432    //
433    // THIS KERNEL IS THE ONE `attn_output` AND `shared_expert` USE, so the fix has to exist in both or half the
434    // model keeps the old instruction count.
435    constexpr int QE = 4;
436    constexpr int QB = QE * CODE_BITS / 8;             // 1 for S2, 2 for S4, 4 for S8
437    constexpr unsigned MASK = (1u << CODE_BITS) - 1u;
438    float acc0 = 0.0f, acc1 = 0.0f, acc2 = 0.0f, acc3 = 0.0f;
439    long long i = (long long) tid * QE;
440    for (; i + QE <= n_in; i += (long long) threads_per_row * QE) {
441        const long long g = i >> group_shift;
442        const float d = s[g];
443        const float b = off ? off[g] : 0.0f;
444        const uint8_t* cp = c + i / PER_BYTE;
445        unsigned v;
446        if (QB == 1) v = cp[0];
447        else if (QB == 2) v = *(const uint16_t*) cp;
448        else v = *(const uint32_t*) cp;
449        // four halves in ONE 8-byte load; `i` is a multiple of four, so `x + i` is 8-byte aligned
450        const float2 f01 = __half22float2(*reinterpret_cast<const __half2*>(x + i));
451        const float2 f23 = __half22float2(*reinterpret_cast<const __half2*>(x + i + 2));
452        acc0 += (decode_tbl<CODE_BITS>((int) (v & MASK), bias, codebook, s_iq4nl) * d + b) * f01.x;
453        acc1 += (decode_tbl<CODE_BITS>((int) ((v >> CODE_BITS) & MASK), bias, codebook, s_iq4nl) * d + b) * f01.y;
454        acc2 += (decode_tbl<CODE_BITS>((int) ((v >> (2 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b) * f23.x;
455        acc3 += (decode_tbl<CODE_BITS>((int) ((v >> (3 * CODE_BITS)) & MASK), bias, codebook, s_iq4nl) * d + b) * f23.y;
456    }
457    // the last, partial quad - at most one per thread
458    for (; i < n_in; i += (long long) threads_per_row * QE) {
459        for (int k = 0; k < QE && i + k < n_in; ++k) {
460            const long long e = i + k;
461            const long long g = e >> group_shift;
462            const int code = (c[e / PER_BYTE] >> ((int) (e % PER_BYTE) * CODE_BITS)) & MASK;
463            acc0 += (decode_tbl<CODE_BITS>(code, bias, codebook, s_iq4nl) * s[g] + (off ? off[g] : 0.0f)) *
464                    __half2float(__ushort_as_half(x[e]));
465        }
466    }
467    partial[tid] = (acc0 + acc1) + (acc2 + acc3);
468    __syncthreads();
469    for (int step = threads_per_row / 2; step > 0; step >>= 1) {
470        if (tid < step) partial[tid] += partial[tid + step];
471        __syncthreads();
472    }
473    if (tid == 0) y[o] = partial[0];
474}
475
476}  // namespace
477
478static void s_gemv_split_impl(const uint16_t* x, const uint8_t* codes, const float* scales,
479                               const float* offset, float* y, int64_t n_in, int64_t n_out, const SForm& form,
480                               int threads_per_row, cudaStream_t stream, bool sync) {
481    if (n_in <= 0 || n_out <= 0) return;
482    if (threads_per_row < 1 || (threads_per_row & (threads_per_row - 1)) != 0 || threads_per_row > 1024) {
483        std::fprintf(stderr, "s_gemv_split: threads_per_row must be a power of two in 1..1024, got %d\n",
484                     threads_per_row);
485        std::exit(1);
486    }
487    const int cb = (int) form.codebook;
488    // Every group size this format defines is a power of two, which is what lets the per-element group index
489    // be a shift.  Refuse anything else rather than compute a wrong index quietly.
490    if (form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0) {
491        std::fprintf(stderr, "s_gemv_split: group_elems must be a power of two, got %d\n", form.group_elems);
492        std::exit(1);
493    }
494    // AND THE QUAD MUST FIT INSIDE ONE GROUP: four consecutive elements share a scale and the kernel reads
495    // exactly one.  Every group size this format defines is 16, 32 or 64, so this cannot fire on a real pack.
496    if (form.group_elems % 4 != 0) {
497        std::fprintf(stderr, "s_gemv_split: group_elems %d is not a multiple of 4\n", form.group_elems);
498        std::exit(1);
499    }
500    int group_shift = 0;
501    while ((1 << group_shift) < form.group_elems) ++group_shift;
502    const size_t smem = (size_t) threads_per_row * sizeof(float);
503    const unsigned grid = (unsigned) n_out;
504    switch (form.code_bits) {
505        case 2:
506            s_gemv_split_kernel<2><<<grid, threads_per_row, smem, stream>>>(
507                x, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems,
508                group_shift, form.has_offset ? 1 : 0, threads_per_row);
509            break;
510        case 4:
511            s_gemv_split_kernel<4><<<grid, threads_per_row, smem, stream>>>(
512                x, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems,
513                group_shift, form.has_offset ? 1 : 0, threads_per_row);
514            break;
515        case 8:
516            s_gemv_split_kernel<8><<<grid, threads_per_row, smem, stream>>>(
517                x, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems,
518                group_shift, form.has_offset ? 1 : 0, threads_per_row);
519            break;
520        default:
521            std::fprintf(stderr, "s_gemv_split: unsupported code_bits %d\n", form.code_bits);
522            std::exit(1);
523    }
524    if (sync) {
525        const cudaError_t e = cudaDeviceSynchronize();
526        if (e != cudaSuccess) {
527            std::fprintf(stderr, "s_gemv_split: %s\n", cudaGetErrorString(e));
528            std::exit(1);
529        }
530    }
531}
532
533void s_gemv_split(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset,
534                  float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row) {
535    s_gemv_split_impl(x, codes, scales, offset, y, n_in, n_out, form, threads_per_row, (cudaStream_t) 0, true);
536}
537
538void s_gemv_split_async(const uint16_t* x, const uint8_t* codes, const float* scales, const float* offset,
539                        float* y, int64_t n_in, int64_t n_out, const SForm& form, int threads_per_row,
540                        void* stream) {
541    s_gemv_split_impl(x, codes, scales, offset, y, n_in, n_out, form, threads_per_row, (cudaStream_t) stream,
542                      false);
543}
544
545// ---- the Q8_K entry points -----------------------------------------------------------------------------
546
547namespace {
548
549bool q8k_form_ok(const SForm& form, int64_t n_in, const char* who) {
550    if (form.group_elems <= 0 || n_in % form.group_elems != 0) {
551        std::fprintf(stderr, "%s: n_in %lld is not a multiple of group_elems %d\n", who, (long long) n_in,
552                     form.group_elems);
553        return false;
554    }
555    if (n_in % Q8K_BLOCK_ELEMS != 0) {
556        // `quantize_q8_K` requires this too, and a partial block would read past the end of the activation.
557        std::fprintf(stderr, "%s: n_in %lld is not a multiple of the Q8_K block %d\n", who, (long long) n_in,
558                     Q8K_BLOCK_ELEMS);
559        return false;
560    }
561    return true;
562}
563
564void finish(const char* who, void* stream) {
565    const cudaError_t e = cudaGetLastError();
566    if (e != cudaSuccess) {
567        std::fprintf(stderr, "%s launch: %s\n", who, cudaGetErrorString(e));
568        std::exit(1);
569    }
570    if (stream != nullptr) return;
571    const cudaError_t s = cudaDeviceSynchronize();
572    if (s != cudaSuccess) {
573        std::fprintf(stderr, "%s: %s\n", who, cudaGetErrorString(s));
574        std::exit(1);
575    }
576}
577
578}  // namespace
579
580void s_gemv_q8k(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset, float* y,
581                int64_t n_in, int64_t n_out, const SForm& form, void* stream) {
582    if (n_in <= 0 || n_out <= 0) return;
583    if (!q8k_form_ok(form, n_in, "s_gemv_q8k")) std::exit(1);
584    const int threads = 128;
585    const unsigned blocks = (unsigned) ((n_out + threads - 1) / threads);
586    const int cb = (int) form.codebook;
587    const int ho = form.has_offset ? 1 : 0;
588    switch (form.code_bits) {
589        case 4:
590            s_gemv_q8k_kernel<4><<<blocks, threads, 0, (cudaStream_t) stream>>>(
591                x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, ho);
592            break;
593        case 8:
594            s_gemv_q8k_kernel<8><<<blocks, threads, 0, (cudaStream_t) stream>>>(
595                x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, form.group_elems, ho);
596            break;
597        default:
598            // 2-bit S2 never has a Q8_K activation: its `vec_dot_type` is Q8_0.  Refusing is better than
599            // running a kernel that would be numerically wrong in a way the caller cannot see.
600            std::fprintf(stderr, "s_gemv_q8k: code_bits %d has no Q8_K contract "
601                                 "(S2 uses Q8_0; see docs/activation-contract.md)\n", form.code_bits);
602            std::exit(1);
603    }
604    finish("s_gemv_q8k", stream);
605}
606
607void s_gemv_q8k_split(const uint8_t* x_q8k, const uint8_t* codes, const float* scales, const float* offset,
608                      float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream) {
609    if (n_in <= 0 || n_out <= 0) return;
610    if (!q8k_form_ok(form, n_in, "s_gemv_q8k_split")) std::exit(1);
611    // THE GROUP SIZE IS PASSED AS ITS LOGARITHM: see the note on the kernel.  A non-power-of-two group would
612    // make the shift a WRONG INDEX rather than a slow one, so it is refused here.
613    int group_shift = 0;
614    while ((1 << group_shift) < form.group_elems) ++group_shift;
615    if ((1 << group_shift) != form.group_elems) {
616        std::fprintf(stderr, "s_gemv_q8k_split: group_elems %d is not a power of two\n", form.group_elems);
617        std::exit(1);
618    }
619    // AND THE QUAD MUST FIT INSIDE ONE GROUP.  Four consecutive elements share a scale, so a group smaller
620    // than four would need two of them and the kernel reads exactly one.  Every group size this format
621    // defines is 16, 32 or 64, so this cannot fire on a real pack - it is here because a future one could.
622    if (form.group_elems % 16 != 0) {
623        std::fprintf(stderr, "s_gemv_q8k_split: group_elems %d is not a multiple of 16\n", form.group_elems);
624        std::exit(1);
625    }
626    const int threads = 256;
627    const int warps = threads / 32;
628    const unsigned blocks = (unsigned) ((n_out + warps - 1) / warps);
629    const int cb = (int) form.codebook;
630    const int ho = form.has_offset ? 1 : 0;
631    switch (form.code_bits) {
632        case 4:
633            s_gemv_q8_split_kernel<4, true><<<blocks, threads, 0, (cudaStream_t) stream>>>(
634                x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho);
635            break;
636        case 8:
637            s_gemv_q8_split_kernel<8, true><<<blocks, threads, 0, (cudaStream_t) stream>>>(
638                x_q8k, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho);
639            break;
640        default:
641            std::fprintf(stderr, "s_gemv_q8k_split: code_bits %d has no Q8_K contract\n", form.code_bits);
642            std::exit(1);
643    }
644    finish("s_gemv_q8k_split", stream);
645}
646
647void s_gemv_q8_0_split(const uint8_t* x_q8_0, const uint8_t* codes, const float* scales, const float* offset,
648                       float* y, int64_t n_in, int64_t n_out, const SForm& form, void* stream) {
649    if (n_in <= 0 || n_out <= 0) return;
650    // THE ACTIVATION IS `block_q8_0`, 32 elements per block, so `n_in` must be a multiple of 32 - which is a
651    // WEAKER requirement than Q8_K's 256 and is exactly why this kernel has to exist: `ffn_down_shexp` has
652    // n_in = 640, a multiple of 32 that is NOT a multiple of 256.
653    if (n_in % Q8_0_BLOCK_ELEMS != 0) {
654        std::fprintf(stderr, "s_gemv_q8_0_split: n_in %lld is not a multiple of %d\n", (long long) n_in,
655                     Q8_0_BLOCK_ELEMS);
656        std::exit(1);
657    }
658    // the same two checks `s_gemv_q8k_split` makes, for the same reasons - see the notes there
659    if (form.group_elems <= 0 || (form.group_elems & (form.group_elems - 1)) != 0) {
660        std::fprintf(stderr, "s_gemv_q8_0_split: group_elems must be a power of two, got %d\n",
661                     form.group_elems);
662        std::exit(1);
663    }
664    // SIXTEEN, NOT FOUR: a lane-iteration takes QE = 16 consecutive elements under ONE scale (see the kernel),
665    // so a group of 4 or 8 would read the wrong scale for most of them.  The Q8_K launcher already said 16.
666    if (form.group_elems % 16 != 0) {
667        std::fprintf(stderr, "s_gemv_q8_0_split: group_elems %d is not a multiple of 16\n", form.group_elems);
668        std::exit(1);
669    }
670    int group_shift = 0;
671    while ((1 << group_shift) < form.group_elems) ++group_shift;
672
673    const int threads = 256;
674    const int warps = threads / 32;
675    const unsigned blocks = (unsigned) ((n_out + warps - 1) / warps);
676    const int cb = (int) form.codebook;
677    const int ho = form.has_offset ? 1 : 0;
678    switch (form.code_bits) {
679        case 4:
680            s_gemv_q8_split_kernel<4, false><<<blocks, threads, 0, (cudaStream_t) stream>>>(
681                x_q8_0, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho);
682            break;
683        case 8:
684            s_gemv_q8_split_kernel<8, false><<<blocks, threads, 0, (cudaStream_t) stream>>>(
685                x_q8_0, codes, scales, offset, y, n_in, n_out, form.code_bias, cb, group_shift, ho);
686            break;
687        default:
688            std::fprintf(stderr, "s_gemv_q8_0_split: code_bits %d has no Q8_0 contract\n", form.code_bits);
689            std::exit(1);
690    }
691    finish("s_gemv_q8_0_split", stream);
692}
693
694}  // namespace strata::kernels