okami.mom/strata

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

Niko1221Merge f-q36-mmqoff 30d9fc1a3 into the batch 16 candidate (Qwen3.6 without MMQ)1cdc6033b

main
69.0 KiB1211 linesraw
1// src/kernels/cuda/i8_expert.cuh - our own int8 dot-product kernels for a prompt layer of experts (native_expert_i8, declared in
2// include/strata/kernels/iq_kernels.hpp), for cards that have no matrix cores the fused kernels can use (RDNA2, Pascal, any
3// card with only a byte dot product).  Included once by iq_kernels.cu, INSIDE its anonymous namespace (it uses that file's
4// block types, codebook tables, q8_1 helpers and the dp4a wrapper).
5//
6// What it does, against native_expert_grouped.  The grouped kernels decode every weight block again for each pass of
7// GRP_NC = 4 activation rows; an expert of a prompt chunk carries 40-390 rows.  Here a block owns a tile of
8//   64 weight rows x BM = 16 TM entries of one expert
9// and walks K in stages of 128 values.  Per stage every thread decodes ONE 32-value sub-block of ONE weight row into int8 words
10// in shared memory (once per tile, not once per 4 entries), the tile's activations (q8_1) are staged beside them, and every
11// thread then multiplies a TM x 4 register tile with `__dp4a`:
12//     per 32 values and (entry, weight row):  8 dp4a, the format's integer scale(s), one float fma with d_w * d_x.
13// The arithmetic is the quantized-dot arithmetic of the other native kernels: w = d_w * s * q (q the int8 code, s a small
14// integer scale), x = d_x * a (a in -127..127; d_x an FP32 scale, i8_quantize_kernel / the epilogue below: MMQ's numbers, not the q8_1 half2), sum w x = d_w d_x sum s (q . a).  The scale algebra is ggml's: IQ2_XXS d (2s+1)/8
15// per 32, IQ2_XS / IQ2_S d (2s+1)/8 per 16, IQ3_XXS d (2s+1)/4 per 32, IQ3_S d (2s+1) per 32, IQ4_NL / Q2_0 d.  Unlike the
16// decode kernels the integer division inside the dot is not done (the exact value is used), so the error against FP32 is at
17// most theirs.
18//
19// Two kernels and a small prologue per call:
20//   i8_tiles_kernel  the tile list: tile_off[g] = first tile of group g (device side, no host sync: graph capture is fine)
21//   i8_kernel<T, GU>  GU: gate/up rows of 32 features (32 gate + the same 32 up rows), SwiGLU and the q8_1 quantization of H in the
22//                     epilogue (a thread holds gate and up of the same feature; the 16 lanes of a row hold the 32 features of one
23//                     q8_1 block), so gate/up never go to memory; !GU: down rows, FP32 into out[ent_dst].
24// Formats: gate/up IQ2_XXS(16) IQ2_XS(17) IQ3_XXS(18) IQ3_S(21) IQ2_S(22); down IQ4_NL(20) Q2_0(42).
25//
26// Iteration 4 (what changed against the iteration-3 kernel, all of it exact: the output is bit-identical):
27//   * the byte dot product of a chain starts with the three-operand v_dot4_i32_i8 on gfx1030-1032 (src2 = 0), where the compiler emitted a
28//     v_mov 0 and the accumulating v_dot4c for every one of the 16-32 chains of a sub-block;
29//   * the integer scales and the float base scale of a (row, sub-block) are one 16-byte record in shared memory ({m0, m1, d, 0}):
30//     one read per row, and the two-scale formats use mul24 + mad24 on clean registers (the packed form cost mul, mul, add);
31//     the unit-scale formats (IQ4_NL, Q2_0) skip the scale multiply;
32//   * the sign pattern of the i-quant grids comes from a 256-entry table in shared memory ({mask lo, +1 lo, mask hi, +1 hi}) and is
33//     applied as (grid ^ mask) + 1s: the grids have no zero byte, so no borrow crosses a byte (checked: par/owni8/grid_zero_check.py);
34//   * the activation stage is one thread per (row, q8_1 block): 9 dword loads from one base + immediate offsets, two 16-byte and one
35//     4-byte store, no branch (the old mapping branched per dword); the weight pieces are read with a uniform base plus a per-thread
36//     32-bit offset (global SADDR form) instead of 64-bit address arithmetic per piece;
37//   * a tile whose last entries are empty skips the 16-entry slices that hold no entry (uniform branch; bit-identical for the others).
38#ifndef I8_BLK_UNROLL
39#define I8_BLK_UNROLL 1     // unroll factor of the 32-value sub-block loop of one stage (the full unroll hoisted every LDS read: 256 VGPRs and 55-200 spilled on gfx1031)
40#endif
41#define I8_STR_(x) #x
42#define I8_PRAGMA_UNROLL(n) _Pragma(I8_STR_(unroll n))
43constexpr int I8_KS = 128;     // values of K per stage
44constexpr int I8_LD = 36;      // dwords per shared row of a stage: 32 + 4 (no bank conflicts for the 16-byte reads)
45constexpr int I8_RS = 20;      // dwords per row of the scale records: 4 x 4 + 4 (no bank conflicts for the 16-byte reads)
46constexpr int I8_NT = 256;
47
48// Second wave (same arithmetic, new decodes): gate/up IQ4_XS (23: the IQ4_NL table with a 6-bit scale per 32 values) and IQ1_M (29: the grid of +-1 / 0 times 8, with the
49// block's two delta signs folded into the int8 values: 8 (g - 1 +- 1/8) is an integer, so no activation-sum term is needed); down Q5_0 (6) and Q8_0 (8), the legacy
50// 32-value blocks with one scale (the 5th bit of Q5_0 comes from the 32-bit qh word; 16 is subtracted per byte).
51__host__ __device__ constexpr int i8_block_bytes(int t) {
52    return t == 16 ? 66 : t == 17 ? 74 : t == 22 ? 82 : t == 18 ? 98 : t == 21 ? 110 : t == 20 ? 18 : t == 42 ? 18 : t == 23 ? 136 : t == 29 ? 56 : t == 6 ? 22 : t == 8 ? 34 :
53           t == 12 ? 144 : t == 13 ? 176 : t == 14 ? 210 : t == 7 ? 24 : 0;
54}
55__host__ __device__ constexpr int i8_block_vals(int t) { return t == 20 || t == 6 || t == 8 || t == 7 ? 32 : t == 42 ? 64 : 256; }
56__host__ __device__ constexpr int i8_grid_words(int t) { return t == 16 ? 512 : t == 17 ? 1024 : t == 22 ? 2048 : t == 18 ? 256 : t == 21 ? 512 : t == 29 ? 2048 : 4; }
57__host__ __device__ constexpr bool i8_two_scales(int t) { return t == 17 || t == 22 || t == 29 || t == 14; }
58__host__ __device__ constexpr bool i8_unit_scale(int t) { return t == 20 || t == 42 || t == 6 || t == 8 || t == 7; }
59__host__ __device__ constexpr bool i8_wide_scale(int t) { return t == 23; }   // scale -32..31: |sum x scale| can pass 2^23, plain 32-bit multiply
60__host__ __device__ constexpr bool i8_sign_type(int t) { return t == 16 || t == 17 || t == 18 || t == 21 || t == 22; }
61__host__ __device__ constexpr bool i8_gu_type(int t) { return t == 16 || t == 17 || t == 18 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 12 || t == 13 || t == 14 || t == 8; }   // (42: the Q2_0 pack gate/up; 8: Q8_0 gate/up of the Qwen3.6 Q8_0 set and the one Q8_0 layer of UD-Q6_K_XL)
62__host__ __device__ constexpr bool i8_d_type(int t) { return t == 20 || t == 42 || t == 6 || t == 8 || t == 7 || t == 13 || t == 14; }   // (13, 14: Q5_K / Q6_K down of UD-Q4_K_XL; n_ff must be a whole number of 256-value super-blocks, native_expert_i8_supported)
63// Third wave: the K-quants Q4_K (12), Q5_K (13), Q6_K (14) as gate/up and Q5_1 (7) as down.  Q4_K / Q5_K / Q5_1 have a per-32-value minimum: w = base * s * q + min, so
64// sum w x = d_x (base s sum(q a) + min sum(a)): the kernel keeps d_x * sum(a) of every activation block in shared memory (s_as, summed with dp4a when the block is staged) and
65// the decode puts the float `min` (-dmin * m, or + m for Q5_1) in the fourth word of the scale record: one fma more per (row, entry, sub-block).  Q6_K has two int8 scales per 32
66// values and no minimum (the two-scale form).  These formats run on the tile-2..4 kernels only (no tile 8).
67__host__ __device__ constexpr bool i8_min_type(int t) { return t == 12 || t == 13 || t == 7; }
68__host__ __device__ constexpr bool i8_tile8_type(int t) { return !(t == 12 || t == 13 || t == 14 || t == 7); }
69// raw words one thread loads for a sub-block, and the packed words the decode reads (Q8_0: the 8 code words and the scale)
70template <int T> constexpr int I8NR = T == 8 ? 9 : T == 12 ? 12 : T == 13 ? 20 : T == 14 ? 18 : 6;
71template <int T> constexpr int I8NW = T == 8 ? 9 : T == 6 ? 6 : T == 7 ? 6 : T == 12 ? 10 : T == 13 || T == 14 ? 18 : 5;
72
73// Weight bytes are read through a GLOBAL address-space pointer on HIP: a flat load also counts in lgkmcnt, so every LDS wait of the dot loop then waited
74// for the prefetch that was meant to overlap it (iteration 2 compiled to flat_load + an immediate s_waitcnt vmcnt(0) before the first dot).
75#if defined(__HIPCC__)
76#define I8_AS __attribute__((address_space(1)))
77#else
78#define I8_AS
79#endif
80using I8P = const I8_AS uint8_t*;
81using I8P16 = const I8_AS uint16_t*;
82using I8P32 = const I8_AS uint32_t*;
83#define I8_GPTR(x) ((I8P) (uintptr_t) (x))
84__device__ __forceinline__ uint32_t i8_ld16(I8P p) { return *(I8P16) p; }   // 2-byte aligned only
85__device__ __forceinline__ uint32_t i8_ld8(I8P p) { return *p; }
86__device__ __forceinline__ uint32_t i8_ldw(I8P p) { return *(I8P32) p; }   // 4-byte aligned
87__device__ __forceinline__ float i8_half(uint32_t w) { return __half2float(__ushort_as_half((unsigned short) w)); }
88// The activation image of these kernels (the call's x rows and the H the gate/up epilogue writes): blocks of 32 values {float d; int8 q[32]}, 36 bytes (the q8_1 block's size, so the
89// tables and strides are unchanged), numbers as MMQ's quantizer (quantize_mmq_q8_1, layout D4): d_inv = 127 / amax, q = round(x * d_inv), d = 1 / d_inv, the scale kept in FP32.
90// (The q8_1 half2 would round d to FP16 - up to 2^-11 per block - and the kernels would differ from MMQ's output by more than float rounding.)  An all-zero block: q 0, d 0.
91__device__ __forceinline__ int8_t i8_code(float x, float d_inv, float amax) { return amax == 0.0f ? (int8_t) 0 : (int8_t) roundf(x * d_inv); }
92__device__ __forceinline__ void i8_put_scale(block_q8_1* b, float amax, float d_inv) { *reinterpret_cast<uint32_t*>(&b->ds) = __float_as_uint(amax == 0.0f ? 0.0f : 1.0f / d_inv); }
93__global__ void i8_quantize_kernel(const float* __restrict__ x, block_q8_1* __restrict__ y, long long n) {   // n a multiple of 32: a warp is whole blocks
94    const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;
95    if (i >= n) return;
96    const float xi = x[i];
97    float amax = fabsf(xi);
98#pragma unroll
99    for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
100    const float d_inv = 127.0f / amax;
101    const long long ib = i / 32, iqs = i % 32;
102    y[ib].qs[iqs] = i8_code(xi, d_inv, amax);
103    if (iqs == 0) i8_put_scale(&y[ib], amax, d_inv);
104}
105// byte 0 of v (v < 256) in all four bytes (one v_perm instead of a quarter-rate 32-bit multiply)
106__device__ __forceinline__ uint32_t i8_bcast(uint32_t v) { return __byte_perm(v, 0u, 0x0000); }
107// a pointer that is the same in every lane, as scalar registers (the compiler cannot tell: it came out of a binary search over loads)
108__device__ __forceinline__ I8P i8_uniform(I8P p) {
109#if defined(__HIPCC__)
110    const uint64_t v = (uint64_t) (uintptr_t) p;
111    const uint32_t lo = (uint32_t) __builtin_amdgcn_readfirstlane((int) (uint32_t) v), hi = (uint32_t) __builtin_amdgcn_readfirstlane((int) (uint32_t) (v >> 32));
112    return (I8P) (uintptr_t) (((uint64_t) hi << 32) | lo);
113#else
114    return p;
115#endif
116}
117// the first dot product of a chain: 4 byte products plus 0.  gfx1030-1032 have the three-operand v_dot4_i32_i8 (the accumulating v_dot4c needs the
118// accumulator zeroed first by a v_mov, one extra instruction per chain; the compiler picks the v_dot4c form for sdot4(a, b, 0)).
119__device__ __forceinline__ int i8_dot0(int a, int b) {
120#if defined(__gfx1030__) || defined(__gfx1031__) || defined(__gfx1032__)
121    int r;
122    __asm__("v_dot4_i32_i8 %0, %1, %2, 0" : "=v"(r) : "v"(a), "v"(b));
123    return r;
124#else
125    return ggml_cuda_dp4a(a, b, 0);
126#endif
127}
128
129// bytes of sub-block `ib` of the block at `bp` (the 256-value super-block, ib 0..7; Q2_0: the 64-value block, ib 0..1; IQ4_NL: the block)
130// The raw loads (32-bit words read at 2-byte alignment as one load, a 16-bit scale, byte pieces; nothing combined here) so that the first use of the
131// loaded registers sits after the dot loop of the stage: i8_load issues them, i8_pack (called in the decode, after the dot loop) builds the words that
132// i8_convert reads.  (Read as 16-bit halves the compiler merged them into one dword load and split the dword again right after the load, which put an
133// s_waitcnt vmcnt in front of the dot loop.)
134constexpr int I8_NRAW = 6;
135#if defined(__HIPCC__)
136typedef uint32_t i8_u32a __attribute__((aligned(2)));
137__device__ __forceinline__ uint32_t i8_ld32(I8P p) { return *(const I8_AS i8_u32a*) p; }   // AMD global loads may be unaligned
138#else
139__device__ __forceinline__ uint32_t i8_ld32(I8P p) { return i8_ld16(p) | (i8_ld16(p + 2) << 16); }   // NVIDIA: a 32-bit load must be 4-byte aligned ("misaligned address" otherwise)
140#endif
141// per-thread byte offsets of the pieces of the thread's sub-block (the thread of sub-block wp of the stage's four), all relative to the expert's blob:
142// the row's start plus wp times the stride of the piece's family (8-byte, 4-byte, 1-byte pieces per sub-block; o_h: half a byte), see i8_load
143struct I8Off { uint32_t o8, o4, o1, oh, o0, o2; };
144template <int T>
145__device__ __forceinline__ I8Off i8_offs(uint32_t row_off, int wp) {
146    I8Off o;
147    o.o0 = row_off;
148    o.o8 = row_off + 8 * wp;
149    o.o4 = row_off + 4 * wp;
150    o.o1 = row_off + wp;
151    o.oh = row_off + (wp >> 1);
152    o.o2 = row_off + 2 * wp;
153    if constexpr (T == 20) o.o4 = row_off + 18 * wp;                                   // IQ4_NL: the block of sub-block wp
154    if constexpr (T == 6) o.o4 = row_off + 22 * wp;                                    // Q5_0
155    if constexpr (T == 8) o.o4 = row_off + 34 * wp;                                    // Q8_0
156    if constexpr (T == 23) o.o4 = row_off + 16 * wp;                                   // IQ4_XS: the 16 code bytes of sub-block wp
157    if constexpr (T == 7) o.o4 = row_off + 24 * wp;                                    // Q5_1
158    // (the K-quants read of.o0 = the row's start and wp = of.o1 - of.o0)
159    if constexpr (T == 42) { o.o0 = row_off + (wp >> 1) * 18; o.o8 = o.o0 + 8 * (wp & 1); }   // Q2_0: block wp / 2, half wp % 2
160    return o;
161}
162// the stage's pieces.  Per stage the bases are uniform (scalar), the offsets per thread: super-block bi = st / 2 and half par = st % 2 of it
163// (ib = 4 par + wp); IQ4_NL: block 4 st + wp; Q2_0: block 2 st + wp / 2.
164template <int T>
165__device__ __forceinline__ void i8_load(I8P blob, const I8Off& of, int st, uint32_t (&r)[I8NR<T>]) {
166    const uint32_t bi = (uint32_t) st >> 1, par = (uint32_t) st & 1;
167    if constexpr (T == 12 || T == 13) {   // Q4_K (144 bytes: d, dmin, 12 scale bytes, 128 code bytes) / Q5_K (176: d, dmin, 12 scale bytes, 32 qh bytes, 128 code bytes): sub-block ib = 4 par + wp
168        constexpr uint32_t BB = T == 12 ? 144 : 176, QS = T == 12 ? 16 : 48;
169        const uint32_t ib = 4 * par + (of.o1 - of.o0);
170        I8P b = blob + bi * BB + of.o0;
171        I8P q = b + QS + 32 * (ib >> 1);   // the 32 code bytes of the sub-block pair (ib >> 1): low nibbles = sub-block 2 g, high nibbles = 2 g + 1
172#pragma unroll
173        for (int k = 0; k < 8; ++k) r[k] = i8_ldw(q + 4 * k);
174        r[8] = i8_ldw(b); r[9] = i8_ldw(b + 4); r[10] = i8_ldw(b + 8); r[11] = i8_ldw(b + 12);
175        if constexpr (T == 13) {
176#pragma unroll
177            for (int k = 0; k < 8; ++k) r[12 + k] = i8_ldw(b + 16 + 4 * k);
178        }
179    } else if constexpr (T == 14) {   // Q6_K (210 bytes, 2-byte aligned: ql 128, qh 64, 16 int8 scales, d): sub-block ib = 4 h + k of the 256 values (h half, k quarter)
180        const uint32_t ib = 4 * par + (of.o1 - of.o0), h = ib >> 2, k4 = ib & 3;
181        I8P b = blob + bi * 210 + of.o0;
182        I8P ql = b + 64 * h + 32 * (k4 & 1), qh = b + 128 + 32 * h;
183#pragma unroll
184        for (int k = 0; k < 8; ++k) { r[k] = i8_ld32(ql + 4 * k); r[8 + k] = i8_ld32(qh + 4 * k); }
185        r[16] = i8_ld16(b + 192 + 2 * ib); r[17] = i8_ld16(b + 208);
186    } else if constexpr (T == 7) {   // Q5_1: four 24-byte blocks a stage: d, m, qh (4 bytes), 16 code bytes
187        I8P a = blob + (96u * (uint32_t) st) + of.o4;
188        r[0] = i8_ldw(a + 8); r[1] = i8_ldw(a + 12); r[2] = i8_ldw(a + 16); r[3] = i8_ldw(a + 20); r[4] = i8_ldw(a + 4); r[5] = i8_ldw(a);
189    } else if constexpr (T == 23) {   // IQ4_XS: super-block bi (136 bytes), sub-blocks 4 par + wp: 16 code bytes at 8 + 16 ib, d + scales_h, scales_l
190        I8P a = blob + (bi * 136 + 8 + 64 * par) + of.o4;
191        r[0] = i8_ld32(a); r[1] = i8_ld32(a + 4); r[2] = i8_ld32(a + 8); r[3] = i8_ld32(a + 12);
192        r[4] = i8_ld32(blob + (bi * 136) + of.o0); r[5] = i8_ld32(blob + (bi * 136 + 4) + of.o0);
193    } else if constexpr (T == 29) {   // IQ1_M: super-block bi (56 bytes): 4 qs bytes at 4 ib, 2 qh bytes at 32 + 2 ib, the 8 scale bytes at 48
194        r[0] = i8_ld32(blob + (bi * 56 + 16 * par) + of.o4);
195        r[1] = i8_ld16(blob + (bi * 56 + 32 + 8 * par) + of.o2);
196        r[2] = i8_ld32(blob + (bi * 56 + 48) + of.o0); r[3] = i8_ld32(blob + (bi * 56 + 52) + of.o0);
197    } else if constexpr (T == 6) {   // Q5_0: four 22-byte blocks a stage: d, qh (4 bytes), 16 code bytes
198        I8P a = blob + (88u * (uint32_t) st) + of.o4;
199        r[0] = i8_ld32(a + 6); r[1] = i8_ld32(a + 10); r[2] = i8_ld32(a + 14); r[3] = i8_ld32(a + 18);
200        r[4] = i8_ld32(a + 2); r[5] = i8_ld16(a);
201    } else if constexpr (T == 8) {   // Q8_0: four 34-byte blocks a stage: d, 32 code bytes
202        I8P a = blob + (136u * (uint32_t) st) + of.o4;
203#pragma unroll
204        for (int k = 0; k < 8; ++k) r[k] = i8_ld32(a + 2 + 4 * k);
205        r[8] = i8_ld16(a);
206    } else if constexpr (T == 16 || T == 17) {
207        constexpr uint32_t BB = T == 16 ? 66 : 74;
208        I8P a8 = blob + (bi * BB + 32 * par) + of.o8;
209        r[0] = i8_ld32(a8 + 2); r[1] = i8_ld32(a8 + 6); r[2] = i8_ld16(blob + (bi * BB) + of.o0);
210        if constexpr (T == 17) r[3] = i8_ld8(blob + (bi * BB + 4 * par) + of.o1 + 66);
211    } else if constexpr (T == 42) {
212        I8P a8 = blob + (36u * (uint32_t) st) + of.o8;
213        r[0] = i8_ld32(a8 + 2); r[1] = i8_ld32(a8 + 6); r[2] = i8_ld16(blob + (36u * (uint32_t) st) + of.o0);
214    } else if constexpr (T == 22) {
215        I8P a4 = blob + (bi * 82 + 16 * par) + of.o4, b1 = blob + (bi * 82 + 4 * par) + of.o1;
216        r[0] = i8_ld32(a4 + 2); r[1] = i8_ld32(a4 + 34);
217        r[2] = i8_ld16(blob + (bi * 82) + of.o0); r[3] = i8_ld8(b1 + 66); r[4] = i8_ld8(b1 + 74);
218    } else if constexpr (T == 18) {
219        I8P a8 = blob + (bi * 98 + 32 * par) + of.o8, a4 = blob + (bi * 98 + 16 * par) + of.o4;
220        r[0] = i8_ld32(a8 + 2); r[1] = i8_ld32(a8 + 6); r[2] = i8_ld32(a4 + 66); r[3] = i8_ld16(blob + (bi * 98) + of.o0);
221    } else if constexpr (T == 21) {
222        I8P a8 = blob + (bi * 110 + 32 * par) + of.o8, a4 = blob + (bi * 110 + 16 * par) + of.o4;
223        r[0] = i8_ld32(a8 + 2); r[1] = i8_ld32(a8 + 6); r[2] = i8_ld32(a4 + 74);
224        r[3] = i8_ld16(blob + (bi * 110) + of.o0); r[4] = i8_ld8(blob + (bi * 110 + 4 * par) + of.o1 + 66);
225        r[5] = i8_ld8(blob + (bi * 110 + 2 * par) + of.oh + 106);
226    } else {   // IQ4_NL
227        I8P a = blob + (72u * (uint32_t) st) + of.o4;
228#pragma unroll
229        for (int k = 0; k < 4; ++k) r[k] = i8_ld32(a + 2 + 4 * k);
230        r[4] = i8_ld16(a);
231    }
232}
233template <int T>
234__device__ __forceinline__ void i8_pack(const uint32_t (&r)[I8NR<T>], int ib, uint32_t (&w)[I8NW<T>]) {
235    if constexpr (T == 12 || T == 13) {
236        // get_scale_min_k4(ib) from the 12 scale bytes (r[9..11]): ib < 4: sc = s[ib] & 63, m = s[ib + 4] & 63; else sc = (s[ib + 4] & 15) | (s[ib - 4] >> 6) << 4, m = (s[ib + 4] >> 4) | (s[ib] >> 6) << 4
237        auto sb = [&](int j) -> uint32_t {   // (a select, not a dynamic index into the register array)
238            const int jw = j >> 2;
239            return ((jw == 0 ? r[9] : jw == 1 ? r[10] : r[11]) >> (8 * (j & 3))) & 255u;
240        };
241        uint32_t sc, m;
242        if (ib < 4) { sc = sb(ib) & 63u; m = sb(ib + 4) & 63u; }
243        else { sc = (sb(ib + 4) & 15u) | ((sb(ib - 4) >> 6) << 4); m = (sb(ib + 4) >> 4) | ((sb(ib) >> 6) << 4); }
244#pragma unroll
245        for (int k = 0; k < 8; ++k) w[k] = r[k];
246        if constexpr (T == 12) { w[8] = r[8]; w[9] = sc | (m << 8); }
247        else {
248#pragma unroll
249            for (int k = 0; k < 8; ++k) w[8 + k] = r[12 + k];
250            w[16] = r[8]; w[17] = sc | (m << 8);
251        }
252    } else if constexpr (T == 14) {
253#pragma unroll
254        for (int k = 0; k < 16; ++k) w[k] = r[k];
255        w[16] = r[16]; w[17] = r[17];
256    } else if constexpr (T == 7) {
257#pragma unroll
258        for (int k = 0; k < 6; ++k) w[k] = r[k];
259    } else if constexpr (T == 23) {
260        // scale of sub-block ib: 4 low bits from scales_l[ib / 2] (nibble ib & 1) and 2 high bits from scales_h; w[4] = d | (ls << 16)
261        const uint32_t ls = ((r[5] >> (4 * (ib & 1) + 8 * (ib >> 1))) & 15u) | (((r[4] >> (16 + 2 * ib)) & 3u) << 4);
262        w[0] = r[0]; w[1] = r[1]; w[2] = r[2]; w[3] = r[3];
263        w[4] = (r[4] & 0xFFFFu) | (ls << 16);
264    } else if constexpr (T == 29) {
265        // the block's fp16 scale is spread over the top nibbles of its four 16-bit scale words; the 3-bit scales of the two halves of sub-block ib
266        const uint32_t d16 = ((r[2] >> 12) & 0xFu) | ((r[2] >> 24) & 0xF0u) | ((r[3] >> 4) & 0xF00u) | ((r[3] >> 16) & 0xF000u);
267        const uint32_t v = (((ib >> 2) ? r[3] : r[2]) >> (16 * ((ib >> 1) & 1))) >> (6 * (ib & 1));
268        w[0] = r[0]; w[1] = r[1] & 0xFFFFu;
269        w[2] = d16 | ((2u * (v & 7u) + 1u) << 16) | ((2u * ((v >> 3) & 7u) + 1u) << 24);
270    } else if constexpr (T == 6) {
271        w[0] = r[0]; w[1] = r[1]; w[2] = r[2]; w[3] = r[3]; w[4] = r[4]; w[5] = r[5];
272    } else if constexpr (T == 8) {
273#pragma unroll
274        for (int k = 0; k < 9; ++k) w[k] = r[k];
275    } else if constexpr (T == 16 || T == 42) {
276        w[0] = r[0]; w[1] = r[1]; w[2] = r[2];
277    } else if constexpr (T == 17) {
278        w[0] = r[0]; w[1] = r[1]; w[2] = r[2] | (r[3] << 16);
279    } else if constexpr (T == 22) {
280        w[0] = r[0]; w[1] = r[1]; w[2] = r[2] | (r[3] << 16) | (r[4] << 24);
281    } else if constexpr (T == 18) {
282        w[0] = r[0]; w[1] = r[1]; w[2] = r[2]; w[3] = r[3];
283    } else if constexpr (T == 21) {
284        w[0] = r[0]; w[1] = r[1]; w[2] = r[2];
285        w[3] = r[3] | (r[4] << 16) | (((r[5] >> (4 * (ib & 1))) & 15) << 24);
286    } else {   // IQ4_NL
287        w[0] = r[0]; w[1] = r[1]; w[2] = r[2]; w[3] = r[3]; w[4] = r[4];
288    }
289}
290
291// 8 nibbles through a 16-entry int8 table (4 words): the low nibbles' values in lo, the high ones' in hi
292__device__ __forceinline__ void i8_table16(uint32_t q4, const uint32_t (&t)[4], uint32_t& lo, uint32_t& hi) {
293    uint32_t tmp[2];
294    const uint32_t sel = 0x32103210u | ((q4 & 0x88888888u) >> 1);
295#pragma unroll
296    for (int i = 0; i < 2; ++i) {
297        const uint32_t sh = 16 * i;
298        const uint32_t l = __byte_perm(t[0], t[1], q4 >> sh), h = __byte_perm(t[2], t[3], q4 >> sh);
299        tmp[i] = __byte_perm(l, h, sel >> sh);
300    }
301    lo = __byte_perm(tmp[0], tmp[1], 0x6420);
302    hi = __byte_perm(tmp[0], tmp[1], 0x7531);
303}
304
305// 8 grid bytes with a sign pattern applied: t = {byte mask of the 4 low values, byte mask of the 4 high values} (the +1 of a negated byte is its mask's low bit); per byte
306// (g ^ 0xFF) + 1 = 256 - g = -g for a negated value (g in 1..127, so no carry), g itself otherwise
307__device__ __forceinline__ void i8_signed8t(uint32_t gx, uint32_t gy, const uint2 t, uint32_t& qx, uint32_t& qy) {
308    qx = (gx ^ t.x) + (t.x & 0x01010101u);
309    qy = (gy ^ t.y) + (t.y & 0x01010101u);
310}
311
312// the sub-block as 8 words of 4 int8 (natural order), the integer scales of its values 0-15 (m0) and 16-31 (m1), and the float base
313// scale: value = base * m * q.  sg = the sign table (shared memory) of the sign formats.
314template <int T>
315__device__ __forceinline__ void i8_convert(const uint32_t (&w)[I8NW<T>], const uint32_t* grid, const uint2* sg, const uint32_t (&kv)[4], uint32_t (&q)[8],
316                                           int& m0, int& m1, float& base, int ib = 0, float* minv = nullptr) {
317    // (the K-quants and Q5_1: ib = the sub-block's index in its 256-value super-block, minv = the float minimum of the (row, sub-block): Q4_K / Q5_K -dmin * m, Q5_1 +m)
318    if constexpr (T == 12 || T == 13) {   // Q4_K / Q5_K: code = nibble (ib & 1: high), plus the 5th bit (bit ib of the qh bytes) << 4 for Q5_K
319#pragma unroll
320        for (int k = 0; k < 8; ++k) {
321            uint32_t v = (w[k] >> (4 * (ib & 1))) & 0x0F0F0F0Fu;
322            if constexpr (T == 13) v |= ((w[8 + k] >> ib) & 0x01010101u) << 4;
323            q[k] = v;
324        }
325        constexpr int D = T == 12 ? 8 : 16;   // the word holding d | dmin << 16 and the word holding sc | m << 8
326        m0 = m1 = (int) (w[D + 1] & 255u);
327        base = i8_half(w[D]);
328        if (minv) *minv = -i8_half(w[D] >> 16) * (float) (w[D + 1] >> 8);
329    } else if constexpr (T == 14) {   // Q6_K: (4 low bits | 2 high bits << 4) - 32; sub-block ib = 4 h + k: the low bits are the nibble (k >> 1), the high bits are bits 2 k of qh
330        const int k4 = ib & 3;
331#pragma unroll
332        for (int k = 0; k < 8; ++k) {
333            const uint32_t lo = (w[k] >> (4 * (k4 >> 1))) & 0x0F0F0F0Fu, hi = ((w[8 + k] >> (2 * k4)) & 0x03030303u) << 4;
334            q[k] = (((lo | hi) | 0x80808080u) - 0x20202020u) ^ 0x80808080u;
335        }
336        m0 = (int) (int8_t) (w[16] & 255u);
337        m1 = (int) (int8_t) ((w[16] >> 8) & 255u);
338        base = i8_half(w[17]);
339    } else if constexpr (T == 7) {   // Q5_1: nibble | 5th bit << 4 (the qh bits as in Q5_0), no offset; value = d q + m
340#pragma unroll
341        for (int p = 0; p < 4; ++p) {
342            const uint32_t bl = ((((w[4] >> (4 * p)) & 15u) * 0x00204081u) & 0x01010101u) << 4;
343            const uint32_t bh = ((((w[4] >> (16 + 4 * p)) & 15u) * 0x00204081u) & 0x01010101u) << 4;
344            q[p] = (w[p] & 0x0F0F0F0Fu) | bl;
345            q[4 + p] = ((w[p] >> 4) & 0x0F0F0F0Fu) | bh;
346        }
347        m0 = m1 = 1;
348        base = i8_half(w[5]);
349        if (minv) *minv = i8_half(w[5] >> 16);
350    } else if constexpr (T == 23) {   // IQ4_XS: the IQ4_NL codes, integer scale ls - 32
351#pragma unroll
352        for (int k = 0; k < 4; ++k) i8_table16(w[k], kv, q[k], q[4 + k]);
353        m0 = m1 = (int) (w[4] >> 16) - 32;
354        base = i8_half(w[4]);
355    } else if constexpr (T == 29) {   // IQ1_M: 8 (g - 1 +- 1/8) = 8 g - 7 or 8 g - 9 per byte; g (0..2) is a nibble of the grid word, so 8 g + 121 (or 119) has no carry between bytes
356#pragma unroll
357        for (int l = 0; l < 4; ++l) {
358            const uint32_t n = (w[1] >> (4 * l)) & 15u;
359            const uint32_t e = grid[((w[0] >> (8 * l)) & 255u) | ((n & 7u) << 8)];
360            const uint32_t K = (n & 8u) ? 0x77777777u : 0x79797979u;
361            q[2 * l] = (((e & 0x0F0F0F0Fu) << 3) + K) ^ 0x80808080u;
362            q[2 * l + 1] = ((((e >> 4) & 0x0F0F0F0Fu) << 3) + K) ^ 0x80808080u;
363        }
364        m0 = (int) ((w[2] >> 16) & 255u);
365        m1 = (int) (w[2] >> 24);
366        base = i8_half(w[2]) * 0.125f;
367    } else if constexpr (T == 6) {   // Q5_0: (nibble | 5th bit << 4) - 16 per byte, values 0-15 from the low nibbles (qh bits 4p..), 16-31 from the high ones (qh bits 16 + 4p..)
368#pragma unroll
369        for (int p = 0; p < 4; ++p) {
370            const uint32_t bl = ((((w[4] >> (4 * p)) & 15u) * 0x00204081u) & 0x01010101u) << 4;
371            const uint32_t bh = ((((w[4] >> (16 + 4 * p)) & 15u) * 0x00204081u) & 0x01010101u) << 4;
372            q[p] = ((((w[p] & 0x0F0F0F0Fu) | bl) | 0x80808080u) - 0x10101010u) ^ 0x80808080u;
373            q[4 + p] = (((((w[p] >> 4) & 0x0F0F0F0Fu) | bh) | 0x80808080u) - 0x10101010u) ^ 0x80808080u;
374        }
375        m0 = m1 = 1;
376        base = i8_half(w[5]);
377    } else if constexpr (T == 8) {   // Q8_0: the code bytes as they are
378#pragma unroll
379        for (int k = 0; k < 8; ++k) q[k] = w[k];
380        m0 = m1 = 1;
381        base = i8_half(w[8]);
382    } else if constexpr (T == 16) {
383        const uint2* g = (const uint2*) grid;
384#pragma unroll
385        for (int l = 0; l < 4; ++l) {
386            const uint2 e = g[(w[0] >> (8 * l)) & 255];
387            i8_signed8t(e.x, e.y, sg[(w[1] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]);
388        }
389        m0 = m1 = (int) ((w[1] >> 27) | 1);
390        base = i8_half(w[2]) * 0.125f;
391    } else if constexpr (T == 17) {
392        const uint2* g = (const uint2*) grid;
393#pragma unroll
394        for (int l = 0; l < 4; ++l) {
395            const uint32_t c = (w[l >> 1] >> (16 * (l & 1))) & 0xFFFF;
396            const uint2 e = g[c & 511];
397            i8_signed8t(e.x, e.y, sg[c >> 9], q[2 * l], q[2 * l + 1]);
398        }
399        const uint32_t sc = w[2] >> 16;
400        m0 = (int) (2 * (sc & 15) + 1);
401        m1 = (int) (2 * ((sc >> 4) & 15) + 1);
402        base = i8_half(w[2]) * 0.125f;
403    } else if constexpr (T == 22) {
404        const uint2* g = (const uint2*) grid;
405        const uint32_t qh = (w[2] >> 16) & 255;
406#pragma unroll
407        for (int l = 0; l < 4; ++l) {
408            const uint2 e = g[((w[0] >> (8 * l)) & 255) | ((qh << (8 - 2 * l)) & 0x300)];
409            i8_signed8t(e.x, e.y, sg[(w[1] >> (8 * l)) & 255], q[2 * l], q[2 * l + 1]);
410        }
411        const uint32_t sc = w[2] >> 24;
412        m0 = (int) (2 * (sc & 15) + 1);
413        m1 = (int) (2 * (sc >> 4) + 1);
414        base = i8_half(w[2]) * 0.125f;
415    } else if constexpr (T == 18) {
416#pragma unroll
417        for (int l = 0; l < 4; ++l) {
418            const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255;
419            i8_signed8t(grid[i0], grid[i1], sg[(w[2] >> (7 * l)) & 127], q[2 * l], q[2 * l + 1]);
420        }
421        m0 = m1 = (int) (2 * (w[2] >> 28) + 1);
422        base = i8_half(w[3]) * 0.25f;
423    } else if constexpr (T == 21) {
424        const uint32_t qh = (w[3] >> 16) & 255;
425#pragma unroll
426        for (int l = 0; l < 4; ++l) {
427            const uint32_t i0 = (w[l >> 1] >> (16 * (l & 1))) & 255, i1 = (w[l >> 1] >> (16 * (l & 1) + 8)) & 255;
428            i8_signed8t(grid[i0 | ((qh << (8 - 2 * l)) & 256)], grid[i1 | ((qh << (7 - 2 * l)) & 256)], sg[(w[2] >> (8 * l)) & 255], q[2 * l],
429                        q[2 * l + 1]);
430        }
431        m0 = m1 = (int) (1 + 2 * (w[3] >> 24));
432        base = i8_half(w[3]);
433    } else if constexpr (T == 20) {
434#pragma unroll
435        for (int k = 0; k < 4; ++k) i8_table16(w[k], kv, q[k], q[4 + k]);
436        m0 = m1 = 1;
437        base = i8_half(w[4]);
438    } else {   // Q2_0: code - 1 through the byte table {-1, 0, 1, 2}
439#pragma unroll
440        for (int h = 0; h < 4; ++h) {
441            const uint32_t c = (w[h >> 1] >> (16 * (h & 1))) & 0xFFFF;
442            const uint32_t qe = __byte_perm(0x020100FFu, 0x020100FFu, c & 0x7777);
443            const uint32_t qo = __byte_perm(0x020100FFu, 0x020100FFu, (c >> 2) & 0x7777);
444            q[2 * h] = __byte_perm(qe, qo, 0x5140);
445            q[2 * h + 1] = __byte_perm(qe, qo, 0x7362);
446        }
447        m0 = m1 = 1;
448        base = i8_half(w[2]);
449    }
450}
451
452template <int T>
453__device__ __forceinline__ const uint32_t* i8_grid_src() {
454    if constexpr (T == 16) return (const uint32_t*) iq2xxs_grid;
455    else if constexpr (T == 17) return (const uint32_t*) iq2xs_grid;
456    else if constexpr (T == 22) return (const uint32_t*) iq2s_grid;
457    else if constexpr (T == 18) return (const uint32_t*) iq3xxs_grid;
458    else if constexpr (T == 21) return (const uint32_t*) iq3s_grid;
459    else if constexpr (T == 29) return (const uint32_t*) iq1s_grid_gpu;   // 2048 words: 8 values of 2 bits' worth in nibbles, as the other IQ1_M kernels read it
460    else return nullptr;
461}
462
463// shared memory of an instance, in dwords: grid | sign table | stage weights x2 | stage activations x2 | scale records x2 |
464// activation scales x2 | source rows
465template <int T, int TM>
466struct I8Smem {
467    static constexpr int BM = 16 * TM;
468    static constexpr int GW = (i8_grid_words(T) + 3) / 4 * 4;
469    static constexpr int SG = i8_sign_type(T) ? 512 : 0;
470    static constexpr int SZ_W = 64 * I8_LD, SZ_A = BM * I8_LD, SZ_R = 64 * I8_RS, SZ_D = BM * 4, SZ_S = i8_min_type(T) ? BM * 4 : 0;   // SZ_S: the activation sums of the minimum formats
471    static constexpr int o_sg = GW, o_w = o_sg + SG, o_a = o_w + 2 * SZ_W, o_r = o_a + 2 * SZ_A, o_d = o_r + 2 * SZ_R, o_s = o_d + 2 * SZ_D, o_src = o_s + 2 * SZ_S,
472                         total = (o_s + 2 * SZ_S + 3) / 4 * 4;   // (the source rows s_src: in the pad words of s_r, see i8_kernel)
473    static constexpr size_t bytes = (size_t) total * 4;
474};
475
476// The smallest tile (TM 2) of every covered format fits 48 KB of shared memory per block, the limit of Pascal cards (49,152 bytes on the P100: no opt-in above
477// it).  A format whose decode tables grow past it fails the build here, not on a card nobody has at hand.
478constexpr size_t I8_SMEM_48K = 48 * 1024;
479static_assert(I8Smem<16, 2>::bytes <= I8_SMEM_48K && I8Smem<17, 2>::bytes <= I8_SMEM_48K && I8Smem<18, 2>::bytes <= I8_SMEM_48K &&
480              I8Smem<21, 2>::bytes <= I8_SMEM_48K && I8Smem<22, 2>::bytes <= I8_SMEM_48K && I8Smem<23, 2>::bytes <= I8_SMEM_48K &&
481              I8Smem<29, 2>::bytes <= I8_SMEM_48K && I8Smem<20, 2>::bytes <= I8_SMEM_48K && I8Smem<42, 2>::bytes <= I8_SMEM_48K &&
482              I8Smem<6, 2>::bytes <= I8_SMEM_48K && I8Smem<8, 2>::bytes <= I8_SMEM_48K && I8Smem<12, 2>::bytes <= I8_SMEM_48K && I8Smem<13, 2>::bytes <= I8_SMEM_48K &&
483              I8Smem<14, 2>::bytes <= I8_SMEM_48K && I8Smem<7, 2>::bytes <= I8_SMEM_48K,
484              "the TM 2 tile of a covered format must fit 48 KB of shared memory per block");
485
486__global__ void __launch_bounds__(256) i8_tiles_kernel(const int32_t* __restrict__ grp_start, const int32_t* __restrict__ n_groups, int bm,
487                                                       int32_t* __restrict__ tile_off) {
488    __shared__ int s[256];
489    const int ng = *n_groups, tid = threadIdx.x;
490    const int per = (ng + 255) / 256;
491    const int g0 = min(ng, tid * per), g1 = min(ng, g0 + per);
492    int sum = 0;
493    for (int g = g0; g < g1; ++g) sum += (grp_start[g + 1] - grp_start[g] + bm - 1) / bm;
494    s[tid] = sum;
495    __syncthreads();
496    for (int o = 1; o < 256; o <<= 1) {
497        const int v = tid >= o ? s[tid - o] : 0;
498        __syncthreads();
499        s[tid] += v;
500        __syncthreads();
501    }
502    int run = s[tid] - sum;
503    for (int g = g0; g < g1; ++g) {
504        tile_off[g] = run;
505        run += (grp_start[g + 1] - grp_start[g] + bm - 1) / bm;
506    }
507    if (tid == 255) tile_off[ng] = s[255];
508}
509
510// The per-(row, entry) dot of one 32-value sub-block pair, the arithmetic of the tile kernel's inner loop: t = integer scale x integer sum (exact), added to the
511// accumulator by one fmaf in the caller.  Used by the NR variant (8-entry slices); the original loop keeps its own copy of the same expressions.
512template <int T>
513__device__ __forceinline__ int i8_row_t(const uint4 (&w)[2], const uint4& rc, const uint4& a0, const uint4& a1) {
514    int s0 = i8_dot0((int) w[0].x, (int) a0.x);
515    s0 = ggml_cuda_dp4a((int) w[0].y, (int) a0.y, s0);
516    s0 = ggml_cuda_dp4a((int) w[0].z, (int) a0.z, s0);
517    s0 = ggml_cuda_dp4a((int) w[0].w, (int) a0.w, s0);
518    if constexpr (i8_two_scales(T)) {
519        int s1 = i8_dot0((int) w[1].x, (int) a1.x);
520        s1 = ggml_cuda_dp4a((int) w[1].y, (int) a1.y, s1);
521        s1 = ggml_cuda_dp4a((int) w[1].z, (int) a1.z, s1);
522        s1 = ggml_cuda_dp4a((int) w[1].w, (int) a1.w, s1);
523        return __mul24(s1, (int) rc.y) + __mul24(s0, (int) rc.x);
524    } else {
525        s0 = ggml_cuda_dp4a((int) w[1].x, (int) a1.x, s0);
526        s0 = ggml_cuda_dp4a((int) w[1].y, (int) a1.y, s0);
527        s0 = ggml_cuda_dp4a((int) w[1].z, (int) a1.z, s0);
528        s0 = ggml_cuda_dp4a((int) w[1].w, (int) a1.w, s0);
529        if constexpr (i8_unit_scale(T)) return s0;
530        else if constexpr (i8_wide_scale(T)) return s0 * (int) rc.x;
531        else return __mul24(s0, (int) rc.x);
532    }
533}
534
535// NR = variant "N8" (tile 2 by default, STRATA_I8_N8=1 for tiles 2-4, 0 for none; i8_n8_takes): the entry slices are 8 entries wide instead of 16.  A thread owns 2 weight rows (the row pair `half` = ty / 8:
536// rows tx + 16 (2 half + i2)) and one entry of each 8-entry slice (entry ty % 8 + 8 js), so a block with 6 entries runs one slice with all 256 threads busy
537// where the 16-entry slice left 10 of 16 entry rows computing nothing.  Every (row, entry) accumulates the same terms in the same order: bit-identical output.
538// The gate/up epilogue needs the gate (row pair 0) and up (row pair 1) values of one entry together: the up half hands them over through shared memory.
539template <int T, bool GU, int TM, bool NR>
540__global__ void __launch_bounds__(I8_NT)
541i8_kernel(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, const int32_t* __restrict__ n_groups,
542          const int32_t* __restrict__ tile_off, const int32_t* __restrict__ ent_idx, const block_q8_1* __restrict__ A,
543          block_q8_1* __restrict__ hq, float* __restrict__ out, NativeExpertLayout L, int bisect) {
544    using SM = I8Smem<T, TM>;
545    constexpr int BM = SM::BM;
546    extern __shared__ uint4 i8_dyn[];
547    uint32_t* const smem = (uint32_t*) i8_dyn;
548    uint32_t* const s_grid = smem;
549    uint32_t* const s_sg = smem + SM::o_sg;
550    uint32_t* const s_w = smem + SM::o_w;
551    uint32_t* const s_a = smem + SM::o_a;
552    uint32_t* const s_r = smem + SM::o_r;
553    float* const s_ad = (float*) (smem + SM::o_d);
554    float* const s_as = (float*) (smem + SM::o_s);   // the minimum formats only: d_x * sum of the 32 activation codes, per (entry, block)
555    // the BM source rows of the tile: word (i & 3) of the pad (words 16..19) of row i / 4 of the first record buffer (the records fill words 0..15 of a row)
556    auto s_src = [&](int i) -> int& { return *(int*) (s_r + (i >> 2) * I8_RS + 16 + (i & 3)); };
557
558    const int ng = *n_groups;
559    const int ti = blockIdx.x;
560    if (ti >= tile_off[ng]) return;
561    int lo = 0, hi = ng - 1;
562    while (lo < hi) {   // the largest group whose first tile is <= ti
563        const int mid = (lo + hi + 1) >> 1;
564        if (tile_off[mid] <= ti) lo = mid; else hi = mid - 1;
565    }
566    const int g = lo;
567    const int e_lo = grp_start[g] + (ti - tile_off[g]) * BM;
568    const int e_hi = min(grp_start[g + 1], e_lo + BM);
569    const int nv = e_hi - e_lo;   // entries of this tile (the rest of the tile is empty)
570    I8P blob = i8_uniform(I8_GPTR(grp_ptr[g]));
571    const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4;
572#if defined(STRATA_I8_DBG)
573    if (tid == 0 && blockIdx.y == 0 && ti < 3)
574        printf("i8 dbg T=%d GU=%d TM=%d ti=%d ng=%d total=%d g=%d e_lo=%d e_hi=%d blob=%p A=%p hq=%p out=%p tok=%p\n", T, (int) GU, TM, ti, ng,
575               tile_off[ng], g, e_lo, e_hi, (const void*) blob, (const void*) A, (const void*) hq, (const void*) out, (const void*) ent_idx);
576#endif
577    if (bisect == 1) return;   // research (STRATA_I8_BISECT = n): return at point n, uniform over the block (the HIP fault hunt)
578    const int K = GU ? (int) L.n_embd : (int) L.n_ff;
579    const int ns = K / I8_KS;
580    const size_t wrb = GU ? L.gu_row : L.d_row;
581
582    if constexpr (i8_grid_words(T) > 4) {
583        const uint32_t* src = i8_grid_src<T>();
584        for (int i = tid; i < i8_grid_words(T); i += I8_NT) s_grid[i] = src[i];
585    }
586    if constexpr (i8_sign_type(T)) {   // entry b = tid: the 8 sign bits (the ksigns formats: 7 bits and their parity), as byte masks and +1s
587        const uint32_t b = (uint32_t) tid;
588        uint32_t sb = b;
589        if constexpr (T != 21 && T != 22) sb = (b & 127u) | (((uint32_t) __popc(b & 127u) & 1u) << 7);
590        uint32_t mlo = 0, mhi = 0;
591#pragma unroll
592        for (int k = 0; k < 4; ++k) {
593            mlo |= ((sb >> k) & 1u) ? (0xFFu << (8 * k)) : 0u;
594            mhi |= ((sb >> (4 + k)) & 1u) ? (0xFFu << (8 * k)) : 0u;
595        }
596        *(uint2*) (s_sg + 2 * b) = make_uint2(mlo, mhi);
597    }
598    uint32_t kv[4] = {0, 0, 0, 0};
599    if constexpr (T == 20 || T == 23) {
600        const uint32_t* t = (const uint32_t*) kvalues_iq4nl;
601#pragma unroll
602        for (int i = 0; i < 4; ++i) kv[i] = t[i];
603    }
604    if (bisect == 2) return;
605    if (tid < BM) s_src(tid) = (e_lo + tid < e_hi) ? (GU ? ent_idx[e_lo + tid] : e_lo + tid) : -1;
606    __syncthreads();
607    if (bisect == 3) return;
608
609    // the weight sub-block of this thread: row wr of the tile, 32 values wp of each stage
610    const int wr = tid >> 2, wp = tid & 3;
611    uint32_t row_off;
612    if constexpr (GU) row_off = (uint32_t) ((wr >= 32 ? L.up_off : (size_t) 0) + (size_t) (blockIdx.y * 32 + (wr & 31)) * wrb);
613    else row_off = (uint32_t) (L.down_off + (size_t) (blockIdx.y * 64 + wr) * wrb);
614    const I8Off woff = i8_offs<T>(row_off, wp);
615    // the activation blocks of this thread (the first 4 BM threads, a whole number of waves): q8_1 block (tid & 3) of row (tid >> 2) of the tile, 9 dwords
616    I8P const abase = I8_GPTR(A);
617    const bool a_thr = tid < 4 * BM;
618    uint32_t a_vo = 0;
619    if (a_thr) {
620        const int src = s_src(tid >> 2);
621        a_vo = (uint32_t) ((size_t) (src >= 0 ? src : 0) * (size_t) ((K / 32) * 36) + (size_t) (tid & 3) * 36);
622    }
623
624    auto load_w = [&](int st, uint32_t (&r)[I8NR<T>]) { i8_load<T>(blob, woff, st, r); };
625    auto store_w = [&](int b, int st, const uint32_t (&r)[I8NR<T>]) {
626        uint32_t q[8], w[I8NW<T>];
627        int m0, m1;
628        float base, minv = 0.0f;
629        const int ibs = (st * 4 + wp) & 7;
630        i8_pack<T>(r, ibs, w);   // (ib of a 256-value super-block; the K-quants and IQ3_S read it)
631        i8_convert<T>(w, s_grid, (const uint2*) s_sg, kv, q, m0, m1, base, ibs, &minv);
632        uint4* dst = (uint4*) (s_w + b * SM::SZ_W + wr * I8_LD + wp * 8);
633        dst[0] = make_uint4(q[0], q[1], q[2], q[3]);
634        dst[1] = make_uint4(q[4], q[5], q[6], q[7]);
635        *(uint4*) (s_r + b * SM::SZ_R + wr * I8_RS + wp * 4) = make_uint4((uint32_t) m0, (uint32_t) m1, __float_as_uint(base), __float_as_uint(minv));
636    };
637    auto load_a = [&](int st, uint32_t (&ar)[9]) {
638        if (a_thr) {
639            I8P p = abase + (size_t) st * 144 + a_vo;
640#pragma unroll
641            for (int k = 0; k < 9; ++k) ar[k] = i8_ldw(p + 4 * k);
642        }
643    };
644    auto store_a = [&](int b, const uint32_t (&ar)[9]) {
645        if (a_thr) {
646            uint4* d = (uint4*) (s_a + b * SM::SZ_A + (tid >> 2) * I8_LD + (tid & 3) * 8);
647            d[0] = make_uint4(ar[1], ar[2], ar[3], ar[4]);
648            d[1] = make_uint4(ar[5], ar[6], ar[7], ar[8]);
649            s_ad[b * SM::SZ_D + tid] = __uint_as_float(ar[0]);
650            if constexpr (i8_min_type(T)) {   // d_x * the sum of the block's 32 codes (exact integer sum, then one float multiply)
651                int sum = ggml_cuda_dp4a((int) ar[1], 0x01010101, 0);
652#pragma unroll
653                for (int k = 2; k < 9; ++k) sum = ggml_cuda_dp4a((int) ar[k], 0x01010101, sum);
654                s_as[b * SM::SZ_D + tid] = __uint_as_float(ar[0]) * (float) sum;
655            }
656        }
657    };
658
659    constexpr int NJ = NR ? 2 * TM : TM, NI = NR ? 2 : 4;   // slices of this thread, rows of this thread
660    const int half = ty >> 3, ey = ty & 7;                  // NR: the row pair and the entry within a slice (a warp holds two ty of one half)
661    float acc[NJ][NI];
662#pragma unroll
663    for (int j = 0; j < NJ; ++j)
664#pragma unroll
665        for (int i = 0; i < NI; ++i) acc[j][i] = 0.0f;
666
667    uint32_t wraw[I8NR<T>], ar[9];
668#pragma unroll
669    for (int k = 0; k < 9; ++k) ar[k] = 0;
670    load_w(0, wraw);
671    if (bisect == 4) { if (wraw[0] == 0x12345678u) out[0] = 0.0f; return; }
672    load_a(0, ar);
673    if (bisect == 5) { if (wraw[0] + ar[0] == 0x12345678u) out[0] = 0.0f; return; }
674    store_w(0, 0, wraw);
675    if (bisect == 6) return;
676    store_a(0, ar);
677    __syncthreads();
678    if (bisect == 7) return;
679    for (int st = 0; st < ns; ++st) {
680        const int b = st & 1;
681        if (st + 1 < ns) { load_w(st + 1, wraw); load_a(st + 1, ar); }
682        const uint32_t* const W = s_w + b * SM::SZ_W;
683        const uint32_t* const Ab = s_a + b * SM::SZ_A;
684        const uint32_t* const Rb = s_r + b * SM::SZ_R;
685        const float* const Db = s_ad + b * SM::SZ_D;
686        const float* const Sb = s_as + b * SM::SZ_D;   // (the minimum formats' activation sums; unused otherwise)
687        if constexpr (NR) {
688            I8_PRAGMA_UNROLL(I8_BLK_UNROLL)
689            for (int blk = 0; blk < 4; ++blk) {
690                uint4 rc[2], wv[2][2];
691#pragma unroll
692                for (int i = 0; i < 2; ++i) {
693                    const int row = tx + 16 * (2 * half + i);
694                    rc[i] = *(const uint4*) (Rb + row * I8_RS + blk * 4);
695                    wv[i][0] = *(const uint4*) (W + row * I8_LD + blk * 8);
696                    wv[i][1] = *(const uint4*) (W + row * I8_LD + blk * 8 + 4);
697                }
698#pragma unroll
699                for (int j = 0; j < NJ; ++j) {
700                    if (8 * j >= nv) break;   // uniform: the 8-entry slices at and beyond nv hold no entry of this tile
701                    const int arow = ey + 8 * j;
702                    const float ax = Db[arow * 4 + blk];
703                    const uint4 a0 = *(const uint4*) (Ab + arow * I8_LD + blk * 8);
704                    const uint4 a1 = *(const uint4*) (Ab + arow * I8_LD + blk * 8 + 4);
705#pragma unroll
706                    for (int i = 0; i < 2; ++i) {
707                        const int t = i8_row_t<T>(wv[i], rc[i], a0, a1);
708                        acc[j][i] = fmaf((float) t, __uint_as_float(rc[i].z) * ax, acc[j][i]);
709                        if constexpr (i8_min_type(T)) acc[j][i] = fmaf(__uint_as_float(rc[i].w), Sb[arow * 4 + blk], acc[j][i]);
710                    }
711                }
712            }
713        } else {
714        I8_PRAGMA_UNROLL(I8_BLK_UNROLL)
715        for (int blk = 0; blk < 4; ++blk) {
716            uint4 rc[4], wv[4][2];
717#pragma unroll
718            for (int i = 0; i < 4; ++i) {
719                const int row = tx + 16 * i;
720                rc[i] = *(const uint4*) (Rb + row * I8_RS + blk * 4);
721                wv[i][0] = *(const uint4*) (W + row * I8_LD + blk * 8);
722                wv[i][1] = *(const uint4*) (W + row * I8_LD + blk * 8 + 4);
723            }
724#pragma unroll
725            for (int j = 0; j < TM; ++j) {
726                if (16 * j >= nv) break;   // uniform: the 16-entry slices at and beyond nv hold no entry of this tile (the loop is unrolled: a forward branch)
727                const int arow = ty + 16 * j;
728                const float ax = Db[arow * 4 + blk];
729                const uint4 a0 = *(const uint4*) (Ab + arow * I8_LD + blk * 8);
730                const uint4 a1 = *(const uint4*) (Ab + arow * I8_LD + blk * 8 + 4);
731#pragma unroll
732                for (int i = 0; i < 4; ++i) {
733                    int s0 = i8_dot0((int) wv[i][0].x, (int) a0.x);
734                    s0 = ggml_cuda_dp4a((int) wv[i][0].y, (int) a0.y, s0);
735                    s0 = ggml_cuda_dp4a((int) wv[i][0].z, (int) a0.z, s0);
736                    s0 = ggml_cuda_dp4a((int) wv[i][0].w, (int) a0.w, s0);
737                    int t;
738                    if constexpr (i8_two_scales(T)) {
739                        int s1 = i8_dot0((int) wv[i][1].x, (int) a1.x);
740                        s1 = ggml_cuda_dp4a((int) wv[i][1].y, (int) a1.y, s1);
741                        s1 = ggml_cuda_dp4a((int) wv[i][1].z, (int) a1.z, s1);
742                        s1 = ggml_cuda_dp4a((int) wv[i][1].w, (int) a1.w, s1);
743                        t = __mul24(s1, (int) rc[i].y) + __mul24(s0, (int) rc[i].x);   // |s * m| < 8.0e6 < 2^23 for every format (IQ3_XXS: 32 x 62 x 127 x 31): exact; v_mul_i32_i24 + v_mad_i32_i24
744                    } else {
745                        s0 = ggml_cuda_dp4a((int) wv[i][1].x, (int) a1.x, s0);
746                        s0 = ggml_cuda_dp4a((int) wv[i][1].y, (int) a1.y, s0);
747                        s0 = ggml_cuda_dp4a((int) wv[i][1].z, (int) a1.z, s0);
748                        s0 = ggml_cuda_dp4a((int) wv[i][1].w, (int) a1.w, s0);
749                        if constexpr (i8_unit_scale(T)) t = s0;
750                        else if constexpr (i8_wide_scale(T)) t = s0 * (int) rc[i].x;
751                        else t = __mul24(s0, (int) rc[i].x);
752                    }
753                    acc[j][i] = fmaf((float) t, __uint_as_float(rc[i].z) * ax, acc[j][i]);
754                    if constexpr (i8_min_type(T)) acc[j][i] = fmaf(__uint_as_float(rc[i].w), Sb[arow * 4 + blk], acc[j][i]);
755                }
756            }
757        }
758        }
759        if (st + 1 < ns) { store_w(b ^ 1, st + 1, wraw); store_a(b ^ 1, ar); }
760        __syncthreads();
761    }
762
763    // epilogues
764    if constexpr (NR) {
765        if constexpr (GU) {
766            // the up half (row pair 1: up rows of features tx, tx + 16) hands its sums to the gate half (row pair 0) of the same entry: after the loop's last
767            // barrier the weight stage buffers are free
768            float* const ex = (float*) s_w;   // [slice][entry ey][tx][2]
769#pragma unroll
770            for (int j = 0; j < NJ; ++j) {
771                if (8 * j >= nv) break;   // uniform
772                if (half == 1) *(float2*) (ex + ((j * 8 + ey) * 16 + tx) * 2) = make_float2(acc[j][0], acc[j][1]);
773            }
774            __syncthreads();
775            if (half == 0) {
776                const int nb = (int) (L.n_ff / 32);
777#pragma unroll
778                for (int j = 0; j < NJ; ++j) {
779                    if (8 * j >= nv) break;   // uniform
780                    const int e = e_lo + ey + 8 * j;
781                    const float2 u = *(const float2*) (ex + ((j * 8 + ey) * 16 + tx) * 2);
782                    const float g0 = acc[j][0], g1 = acc[j][1];
783                    const float h0 = (g0 / (1.0f + __expf(-g0))) * u.x;
784                    const float h1 = (g1 / (1.0f + __expf(-g1))) * u.y;
785                    float amax = fmaxf(fabsf(h0), fabsf(h1));
786#pragma unroll
787                    for (int o = 8; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
788                    if (e < e_hi) {
789                        const float d_inv = 127.0f / amax;
790                        block_q8_1* hb = hq + (size_t) e * nb + blockIdx.y;
791                        hb->qs[tx] = i8_code(h0, d_inv, amax);
792                        hb->qs[tx + 16] = i8_code(h1, d_inv, amax);
793                        if (tx == 0) i8_put_scale(hb, amax, d_inv);
794                    }
795                }
796            }
797        } else {
798#pragma unroll
799            for (int j = 0; j < NJ; ++j) {
800                const int e = e_lo + ey + 8 * j;
801                if (e < e_hi) {
802                    float* o = out + (size_t) ent_idx[e] * L.n_embd + (size_t) blockIdx.y * 64 + tx + 32 * half;
803#pragma unroll
804                    for (int i = 0; i < 2; ++i) o[16 * i] = acc[j][i];
805                }
806            }
807        }
808    } else
809    if constexpr (GU) {
810        // thread rows i = 0, 1: gate features tx, tx + 16 of the tile; i = 2, 3: the up rows of the same features
811        const int nb = (int) (L.n_ff / 32);
812#pragma unroll
813        for (int j = 0; j < TM; ++j) {
814            if (16 * j >= nv) break;   // uniform
815            const int e = e_lo + ty + 16 * j;
816            const float g0 = acc[j][0], g1 = acc[j][1];
817            const float h0 = (g0 / (1.0f + __expf(-g0))) * acc[j][2];
818            const float h1 = (g1 / (1.0f + __expf(-g1))) * acc[j][3];
819            float amax = fmaxf(fabsf(h0), fabsf(h1));
820#pragma unroll
821            for (int o = 8; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
822            if (e < e_hi) {
823                const float d_inv = 127.0f / amax;
824                block_q8_1* hb = hq + (size_t) e * nb + blockIdx.y;
825                hb->qs[tx] = i8_code(h0, d_inv, amax);
826                hb->qs[tx + 16] = i8_code(h1, d_inv, amax);
827                if (tx == 0) i8_put_scale(hb, amax, d_inv);
828            }
829        }
830    } else {
831#pragma unroll
832        for (int j = 0; j < TM; ++j) {
833            const int e = e_lo + ty + 16 * j;
834            if (e < e_hi) {
835                float* o = out + (size_t) ent_idx[e] * L.n_embd + (size_t) blockIdx.y * 64 + tx;
836#pragma unroll
837                for (int i = 0; i < 4; ++i) o[16 * i] = acc[j][i];
838            }
839        }
840    }
841}
842
843// ---------------------------------------------------------------- variant B (tile code 8): 128 weight rows x 128 entries, 4 rows x 16 entries per thread
844// Iteration 5.  Iteration 4 cut the instructions of the dot loop by a quarter and the 20K time by 3 %: the loop is limited by the shared-memory reads
845// (a b128 read takes 4 cycles of the LDS pipe whatever the lanes read; the 4 x 4 register tile needs 16 of them per 128 dots).  Here a lane owns 4 weight
846// rows (lane + 32 i: a wave covers 32 rows with full 16-byte reads) and a wave owns 16 entries, which every lane of the wave reads from the same address
847// (one request): 8 + 32 b128 reads per 512 dots instead of 4 x 16 = 64 (and half the scale reads).  The arithmetic per (row, entry) is the one of the
848// other tiles in the same order (so the output is bit-identical); the stage is 64 values (two sub-blocks) because 128 rows x 128 values would not fit.
849// Per stage: thread (row tid / 2, sub-block tid % 2) decodes one sub-block, thread (entry tid / 2, q8_1 block tid % 2) stages one activation block.
850constexpr int I8B_BM = 128, I8B_LD = 20, I8B_KS = 64;
851template <int T>
852struct I8BSmem {
853    static constexpr int GW = (i8_grid_words(T) + 3) / 4 * 4;
854    static constexpr int SG = i8_sign_type(T) ? 512 : 0;
855    static constexpr int SZ_W = 128 * I8B_LD, SZ_A = 128 * I8B_LD, SZ_R = 2 * 128 * 4, SZ_D = 2 * 128;
856    static constexpr int o_sg = GW, o_w = o_sg + SG, o_a = o_w + 2 * SZ_W, o_r = o_a + 2 * SZ_A, o_d = o_r + 2 * SZ_R, o_src = o_d + 2 * SZ_D,
857                         total = (o_src + I8B_BM + 3) / 4 * 4;
858    static constexpr size_t bytes = (size_t) total * 4;
859};
860// the raw pieces of sub-block `ib` of the block at bp (one load per piece, see i8_load for the stage-uniform form used by the other tiles)
861template <int T>
862__device__ __forceinline__ void i8_load_bp(I8P bp, int ib, uint32_t (&r)[I8NR<T>]) {
863    if constexpr (T == 23) {
864        r[0] = i8_ld32(bp + 8 + 16 * ib); r[1] = i8_ld32(bp + 12 + 16 * ib); r[2] = i8_ld32(bp + 16 + 16 * ib); r[3] = i8_ld32(bp + 20 + 16 * ib);
865        r[4] = i8_ld32(bp); r[5] = i8_ld32(bp + 4);
866    } else if constexpr (T == 29) {
867        r[0] = i8_ld32(bp + 4 * ib); r[1] = i8_ld16(bp + 32 + 2 * ib); r[2] = i8_ld32(bp + 48); r[3] = i8_ld32(bp + 52);
868    } else if constexpr (T == 6) {
869        r[0] = i8_ld32(bp + 6); r[1] = i8_ld32(bp + 10); r[2] = i8_ld32(bp + 14); r[3] = i8_ld32(bp + 18); r[4] = i8_ld32(bp + 2); r[5] = i8_ld16(bp);
870    } else if constexpr (T == 8) {
871#pragma unroll
872        for (int k = 0; k < 8; ++k) r[k] = i8_ld32(bp + 2 + 4 * k);
873        r[8] = i8_ld16(bp);
874    } else if constexpr (T == 16 || T == 17 || T == 42) {
875        r[0] = i8_ld32(bp + 2 + 8 * ib); r[1] = i8_ld32(bp + 6 + 8 * ib); r[2] = i8_ld16(bp);
876        if constexpr (T == 17) r[3] = i8_ld8(bp + 66 + ib);
877    } else if constexpr (T == 22) {
878        r[0] = i8_ld32(bp + 2 + 4 * ib); r[1] = i8_ld32(bp + 34 + 4 * ib);
879        r[2] = i8_ld16(bp); r[3] = i8_ld8(bp + 66 + ib); r[4] = i8_ld8(bp + 74 + ib);
880    } else if constexpr (T == 18) {
881        r[0] = i8_ld32(bp + 2 + 8 * ib); r[1] = i8_ld32(bp + 6 + 8 * ib); r[2] = i8_ld32(bp + 66 + 4 * ib); r[3] = i8_ld16(bp);
882    } else if constexpr (T == 21) {
883        r[0] = i8_ld32(bp + 2 + 8 * ib); r[1] = i8_ld32(bp + 6 + 8 * ib); r[2] = i8_ld32(bp + 74 + 4 * ib);
884        r[3] = i8_ld16(bp); r[4] = i8_ld8(bp + 66 + ib); r[5] = i8_ld8(bp + 106 + ib / 2);
885    } else {   // IQ4_NL
886#pragma unroll
887        for (int k = 0; k < 4; ++k) r[k] = i8_ld32(bp + 2 + 4 * k);
888        r[4] = i8_ld16(bp);
889    }
890}
891
892template <int T, bool GU>
893__global__ void __launch_bounds__(I8_NT)
894i8b_kernel(const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, const int32_t* __restrict__ n_groups,
895           const int32_t* __restrict__ tile_off, const int32_t* __restrict__ ent_idx, const block_q8_1* __restrict__ A,
896           block_q8_1* __restrict__ hq, float* __restrict__ out, NativeExpertLayout L, int bisect) {
897    using SM = I8BSmem<T>;
898    extern __shared__ uint4 i8_dyn[];
899    uint32_t* const smem = (uint32_t*) i8_dyn;
900    uint32_t* const s_grid = smem;
901    uint32_t* const s_sg = smem + SM::o_sg;
902    uint32_t* const s_w = smem + SM::o_w;
903    uint32_t* const s_a = smem + SM::o_a;
904    uint32_t* const s_r = smem + SM::o_r;
905    float* const s_ad = (float*) (smem + SM::o_d);
906    int* const s_src = (int*) (smem + SM::o_src);
907
908    const int ng = *n_groups;
909    const int ti = blockIdx.x;
910    if (ti >= tile_off[ng]) return;
911    int lo = 0, hi = ng - 1;
912    while (lo < hi) {
913        const int mid = (lo + hi + 1) >> 1;
914        if (tile_off[mid] <= ti) lo = mid; else hi = mid - 1;
915    }
916    const int g = lo;
917    const int e_lo = grp_start[g] + (ti - tile_off[g]) * I8B_BM;
918    const int e_hi = min(grp_start[g + 1], e_lo + I8B_BM);
919    const int nv = e_hi - e_lo;
920    I8P blob = i8_uniform(I8_GPTR(grp_ptr[g]));
921    const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
922    const int K = GU ? (int) L.n_embd : (int) L.n_ff;
923    const int ns = K / I8B_KS;
924    const size_t wrb = GU ? L.gu_row : L.d_row;
925
926    if constexpr (i8_grid_words(T) > 4) {
927        const uint32_t* src = i8_grid_src<T>();
928        for (int i = tid; i < i8_grid_words(T); i += I8_NT) s_grid[i] = src[i];
929    }
930    if constexpr (i8_sign_type(T)) {
931        const uint32_t b = (uint32_t) tid;
932        uint32_t sb = b;
933        if constexpr (T != 21 && T != 22) sb = (b & 127u) | (((uint32_t) __popc(b & 127u) & 1u) << 7);
934        uint32_t mlo = 0, mhi = 0;
935#pragma unroll
936        for (int k = 0; k < 4; ++k) {
937            mlo |= ((sb >> k) & 1u) ? (0xFFu << (8 * k)) : 0u;
938            mhi |= ((sb >> (4 + k)) & 1u) ? (0xFFu << (8 * k)) : 0u;
939        }
940        *(uint2*) (s_sg + 2 * b) = make_uint2(mlo, mhi);
941    }
942    uint32_t kv[4] = {0, 0, 0, 0};
943    if constexpr (T == 20 || T == 23) {
944        const uint32_t* t = (const uint32_t*) kvalues_iq4nl;
945#pragma unroll
946        for (int i = 0; i < 4; ++i) kv[i] = t[i];
947    }
948    if (tid < I8B_BM) s_src[tid] = (e_lo + tid < e_hi) ? (GU ? ent_idx[e_lo + tid] : e_lo + tid) : -1;
949    __syncthreads();
950
951    // weights: thread = (tile row wr, sub-block wp of the stage's two); the tile's rows 0..63 are gate features, 64..127 up features (GU), or 128 down rows
952    const int wr = tid >> 1, wp = tid & 1;
953    size_t row_off;
954    if constexpr (GU) row_off = (wr >= 64 ? L.up_off : (size_t) 0) + (size_t) (blockIdx.y * 64 + (wr & 63)) * wrb;
955    else row_off = L.down_off + (size_t) (blockIdx.y * 128 + wr) * wrb;
956    I8P const wrowb = blob + row_off;
957    // activations: thread = (entry ea, q8_1 block ba of the stage's two)
958    const int ea = tid >> 1, ba = tid & 1;
959    I8P const abase = I8_GPTR(A);
960    uint32_t a_vo;
961    {
962        const int src = s_src[ea];
963        a_vo = (uint32_t) ((size_t) (src >= 0 ? src : 0) * (size_t) ((K / 32) * 36) + (size_t) ba * 36);
964    }
965
966    auto load_w = [&](int st, uint32_t (&r)[I8NR<T>]) {
967        const int sb = 2 * st + wp;
968        int bi, ib;
969        if constexpr (i8_block_vals(T) == 256) { bi = sb >> 3; ib = sb & 7; }
970        else if constexpr (i8_block_vals(T) == 64) { bi = sb >> 1; ib = sb & 1; }
971        else { bi = sb; ib = 0; }
972        i8_load_bp<T>(wrowb + (size_t) bi * i8_block_bytes(T), ib, r);
973    };
974    auto store_w = [&](int b, int st, const uint32_t (&r)[I8NR<T>]) {
975        uint32_t q[8], w[I8NW<T>];
976        int m0, m1;
977        float base;
978        i8_pack<T>(r, (2 * st + wp) & 7, w);
979        i8_convert<T>(w, s_grid, (const uint2*) s_sg, kv, q, m0, m1, base);
980        uint4* dst = (uint4*) (s_w + b * SM::SZ_W + wr * I8B_LD + wp * 8);
981        dst[0] = make_uint4(q[0], q[1], q[2], q[3]);
982        dst[1] = make_uint4(q[4], q[5], q[6], q[7]);
983        *(uint4*) (s_r + b * SM::SZ_R + (wp * 128 + wr) * 4) = make_uint4((uint32_t) m0, (uint32_t) m1, __float_as_uint(base), 0u);
984    };
985    auto load_a = [&](int st, uint32_t (&ar)[9]) {
986        I8P p = abase + (size_t) st * 72 + a_vo;
987#pragma unroll
988        for (int k = 0; k < 9; ++k) ar[k] = i8_ldw(p + 4 * k);
989    };
990    auto store_a = [&](int b, const uint32_t (&ar)[9]) {
991        uint4* d = (uint4*) (s_a + b * SM::SZ_A + ea * I8B_LD + ba * 8);
992        d[0] = make_uint4(ar[1], ar[2], ar[3], ar[4]);
993        d[1] = make_uint4(ar[5], ar[6], ar[7], ar[8]);
994        s_ad[b * SM::SZ_D + ba * 128 + ea] = __uint_as_float(ar[0]);
995    };
996
997    float acc[16][4];
998#pragma unroll
999    for (int j = 0; j < 16; ++j)
1000#pragma unroll
1001        for (int i = 0; i < 4; ++i) acc[j][i] = 0.0f;
1002
1003    uint32_t wraw[I8NR<T>], ar[9];
1004    load_w(0, wraw);
1005    load_a(0, ar);
1006    store_w(0, 0, wraw);
1007    store_a(0, ar);
1008    __syncthreads();
1009    const int ebase = 16 * wave;
1010    for (int st = 0; st < ns; ++st) {
1011        const int b = st & 1;
1012        if (st + 1 < ns) { load_w(st + 1, wraw); load_a(st + 1, ar); }
1013        const uint32_t* const W = s_w + b * SM::SZ_W;
1014        const uint32_t* const Ab = s_a + b * SM::SZ_A;
1015        const uint32_t* const Rb = s_r + b * SM::SZ_R;
1016        const float* const Db = s_ad + b * SM::SZ_D;
1017#pragma unroll 1
1018        for (int blk = 0; blk < 2; ++blk) {
1019            uint4 rc[4], wv[4][2];
1020#pragma unroll
1021            for (int i = 0; i < 4; ++i) {
1022                const int row = lane + 32 * i;
1023                rc[i] = *(const uint4*) (Rb + blk * 512 + row * 4);
1024                wv[i][0] = *(const uint4*) (W + row * I8B_LD + blk * 8);
1025                wv[i][1] = *(const uint4*) (W + row * I8B_LD + blk * 8 + 4);
1026            }
1027#pragma unroll
1028            for (int j = 0; j < 16; ++j) {
1029                if (ebase + j < nv) {   // uniform per wave: no entry of this tile from here on otherwise
1030                const int e = ebase + j;
1031                const float ax = Db[blk * 128 + e];
1032                const uint4 a0 = *(const uint4*) (Ab + e * I8B_LD + blk * 8);
1033                const uint4 a1 = *(const uint4*) (Ab + e * I8B_LD + blk * 8 + 4);
1034#pragma unroll
1035                for (int i = 0; i < 4; ++i) {
1036                    int s0 = i8_dot0((int) wv[i][0].x, (int) a0.x);
1037                    s0 = ggml_cuda_dp4a((int) wv[i][0].y, (int) a0.y, s0);
1038                    s0 = ggml_cuda_dp4a((int) wv[i][0].z, (int) a0.z, s0);
1039                    s0 = ggml_cuda_dp4a((int) wv[i][0].w, (int) a0.w, s0);
1040                    int t;
1041                    if constexpr (i8_two_scales(T)) {
1042                        int s1 = i8_dot0((int) wv[i][1].x, (int) a1.x);
1043                        s1 = ggml_cuda_dp4a((int) wv[i][1].y, (int) a1.y, s1);
1044                        s1 = ggml_cuda_dp4a((int) wv[i][1].z, (int) a1.z, s1);
1045                        s1 = ggml_cuda_dp4a((int) wv[i][1].w, (int) a1.w, s1);
1046                        t = __mul24(s1, (int) rc[i].y) + __mul24(s0, (int) rc[i].x);
1047                    } else {
1048                        s0 = ggml_cuda_dp4a((int) wv[i][1].x, (int) a1.x, s0);
1049                        s0 = ggml_cuda_dp4a((int) wv[i][1].y, (int) a1.y, s0);
1050                        s0 = ggml_cuda_dp4a((int) wv[i][1].z, (int) a1.z, s0);
1051                        s0 = ggml_cuda_dp4a((int) wv[i][1].w, (int) a1.w, s0);
1052                        if constexpr (i8_unit_scale(T)) t = s0;
1053                        else if constexpr (i8_wide_scale(T)) t = s0 * (int) rc[i].x;
1054                        else t = __mul24(s0, (int) rc[i].x);
1055                    }
1056                    acc[j][i] = fmaf((float) t, __uint_as_float(rc[i].z) * ax, acc[j][i]);
1057                }
1058            }}
1059        }
1060        if (st + 1 < ns) { store_w(b ^ 1, st + 1, wraw); store_a(b ^ 1, ar); }
1061        __syncthreads();
1062    }
1063
1064    if constexpr (GU) {
1065        // lane = feature; thread rows i = 0, 1: gate features lane, lane + 32; i = 2, 3: up features of the same; the 32 lanes of a wave are one q8_1 block of H
1066        const int nb = (int) (L.n_ff / 32);
1067#pragma unroll
1068        for (int j = 0; j < 16; ++j) {
1069            if (ebase + j < nv) {   // uniform
1070            const int e = e_lo + ebase + j;
1071#pragma unroll
1072            for (int half = 0; half < 2; ++half) {
1073                const float g0 = acc[j][half], u0 = acc[j][2 + half];
1074                const float h0 = (g0 / (1.0f + __expf(-g0))) * u0;
1075                float amax = fabsf(h0);
1076#pragma unroll
1077                for (int o = 16; o > 0; o >>= 1) amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
1078                const float d_inv = 127.0f / amax;
1079                block_q8_1* hb = hq + (size_t) e * nb + 2 * blockIdx.y + half;
1080                hb->qs[lane] = i8_code(h0, d_inv, amax);
1081                if (lane == 0) i8_put_scale(hb, amax, d_inv);
1082            }
1083            }}
1084    } else {
1085#pragma unroll
1086        for (int j = 0; j < 16; ++j) {
1087            if (ebase + j < nv) {
1088            const int e = e_lo + ebase + j;
1089            float* o = out + (size_t) ent_idx[e] * L.n_embd + (size_t) blockIdx.y * 128 + lane;
1090#pragma unroll
1091            for (int i = 0; i < 4; ++i) o[32 * i] = acc[j][i];
1092        }}
1093    }
1094}
1095
1096// ---------------------------------------------------------------- host side
1097struct I8Args {
1098    const unsigned long long* grp_ptr;
1099    const int32_t *grp_start, *n_groups, *tile_off, *ent_tok, *ent_dst;
1100    const block_q8_1* x;
1101    block_q8_1* hq;
1102    float* out;
1103    NativeExpertLayout L;
1104    int64_t tiles_ub;
1105    int bisect;
1106    bool n8 = false;     // tile codes 2-4: 8-entry slices with two weight rows per thread (see i8_kernel, NR)
1107};
1108
1109// what the last native_expert_i8 call asked its two launches for (the tile code, the dynamic shared memory in bytes passed as the launch's third argument, and
1110// the launch's own status, read without clearing it): native_expert_i8_last_launch, printed by the bench
1111struct I8LastLaunch {
1112    int tile = 0, gu_err = 0, down_err = 0;
1113    size_t gu_bytes = 0, down_bytes = 0;
1114};
1115I8LastLaunch g_i8_last;
1116void i8_note_launch(bool gu, int tile, size_t bytes) {
1117    const int e = (int) cudaPeekAtLastError();
1118    g_i8_last.tile = tile;
1119    if (gu) { g_i8_last.gu_bytes = bytes; g_i8_last.gu_err = e; }
1120    else { g_i8_last.down_bytes = bytes; g_i8_last.down_err = e; }
1121}
1122
1123template <int T, bool GU, int TM>
1124void i8_launch_tm(const I8Args& a, cudaStream_t s) {
1125    constexpr size_t smem = I8Smem<T, TM>::bytes;
1126#if !defined(__HIPCC__)
1127    if (smem > 48 * 1024) {
1128        cudaFuncSetAttribute(i8_kernel<T, GU, TM, false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem);
1129        cudaFuncSetAttribute(i8_kernel<T, GU, TM, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem);
1130    }
1131#endif
1132    const dim3 grid((unsigned) a.tiles_ub, (unsigned) (GU ? a.L.n_ff / 32 : a.L.n_embd / 64));
1133    if (a.n8) {   // 8-entry slices (i8_n8_takes)
1134        if constexpr (GU)
1135            i8_kernel<T, true, TM, true><<<grid, I8_NT, smem, s>>>(a.grp_ptr, a.grp_start, a.n_groups, a.tile_off, a.ent_tok, a.x, a.hq, a.out, a.L, a.bisect);
1136        else
1137            i8_kernel<T, false, TM, true><<<grid, I8_NT, smem, s>>>(a.grp_ptr, a.grp_start, a.n_groups, a.tile_off, a.ent_dst, a.hq, nullptr, a.out, a.L, a.bisect);
1138    } else {
1139        if constexpr (GU)
1140            i8_kernel<T, true, TM, false><<<grid, I8_NT, smem, s>>>(a.grp_ptr, a.grp_start, a.n_groups, a.tile_off, a.ent_tok, a.x, a.hq, a.out, a.L, a.bisect);
1141        else
1142            i8_kernel<T, false, TM, false><<<grid, I8_NT, smem, s>>>(a.grp_ptr, a.grp_start, a.n_groups, a.tile_off, a.ent_dst, a.hq, nullptr, a.out, a.L, a.bisect);
1143    }
1144    i8_note_launch(GU, TM, smem);
1145}
1146template <int T, bool GU>
1147void i8b_launch(const I8Args& a, cudaStream_t s) {
1148    constexpr size_t smem = I8BSmem<T>::bytes;
1149#if !defined(__HIPCC__)
1150    if (smem > 48 * 1024) cudaFuncSetAttribute(i8b_kernel<T, GU>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem);
1151#endif
1152    const dim3 grid((unsigned) a.tiles_ub, (unsigned) (GU ? a.L.n_ff / 64 : a.L.n_embd / 128));
1153    if constexpr (GU)
1154        i8b_kernel<T, true><<<grid, I8_NT, smem, s>>>(a.grp_ptr, a.grp_start, a.n_groups, a.tile_off, a.ent_tok, a.x, a.hq, a.out, a.L, a.bisect);
1155    else
1156        i8b_kernel<T, false><<<grid, I8_NT, smem, s>>>(a.grp_ptr, a.grp_start, a.n_groups, a.tile_off, a.ent_dst, a.hq, nullptr, a.out, a.L, a.bisect);
1157    i8_note_launch(GU, 8, smem);
1158}
1159// shared memory of the instances of a gate/up and a down type for tile code tm (2, 3, 4: rows of 16 entries; 8: variant B), and the device's limit per block
1160template <int T>
1161size_t i8_sm(int tm) {
1162    return tm == 8 ? I8BSmem<T>::bytes : tm <= 2 ? I8Smem<T, 2>::bytes : tm == 3 ? I8Smem<T, 3>::bytes : I8Smem<T, 4>::bytes;
1163}
1164size_t i8_smem_bytes(int gu, int dt, int tm) {
1165    const size_t a = gu == 16 ? i8_sm<16>(tm) : gu == 17 ? i8_sm<17>(tm) : gu == 18 ? i8_sm<18>(tm) : gu == 21 ? i8_sm<21>(tm) : gu == 23 ? i8_sm<23>(tm) :
1166                     gu == 29 ? i8_sm<29>(tm) : gu == 42 ? i8_sm<42>(tm) : gu == 12 ? i8_sm<12>(tm) : gu == 13 ? i8_sm<13>(tm) : gu == 14 ? i8_sm<14>(tm) : gu == 8 ? i8_sm<8>(tm) : i8_sm<22>(tm);
1167    const size_t b = dt == 20 ? i8_sm<20>(tm) : dt == 6 ? i8_sm<6>(tm) : dt == 8 ? i8_sm<8>(tm) : dt == 7 ? i8_sm<7>(tm) : dt == 13 ? i8_sm<13>(tm) : dt == 14 ? i8_sm<14>(tm) : i8_sm<42>(tm);
1168    return a > b ? a : b;
1169}
1170int i8_env_int(const char* name, int dflt);
1171#if !defined(__HIPCC__)
1172// Diagnostic only (native_expert_i8_probe_launch, used by native_i8_parity): does a launch of an empty kernel with this much dynamic shared memory run?  The
1173// attribute call is made first and its refusal ignored (the launch decides, as in the real launch path); every failed attempt is read and cleared at once and an
1174// accepted launch is waited for, so the probe leaves the context clean.  Nothing in the engine's path calls it.
1175__global__ void i8_smem_probe_kernel() {
1176    extern __shared__ uint4 i8_probe_dyn[];
1177    if (threadIdx.x == 0xFFFFu) i8_probe_dyn[0] = make_uint4(0, 0, 0, 0);
1178}
1179bool i8_smem_launches(size_t bytes) {
1180    cudaGetLastError();
1181    if (bytes > 48 * 1024 && cudaFuncSetAttribute(i8_smem_probe_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) bytes) != cudaSuccess) cudaGetLastError();
1182    i8_smem_probe_kernel<<<1, 1, bytes>>>();
1183    if (cudaGetLastError() != cudaSuccess) return false;
1184    if (cudaDeviceSynchronize() != cudaSuccess) {
1185        cudaGetLastError();
1186        return false;
1187    }
1188    return true;
1189}
1190#endif
1191size_t i8_smem_limit() {
1192    int dev = 0, v = 0;
1193    size_t lim = 48 * 1024;
1194    if (cudaGetDevice(&dev) == cudaSuccess && cudaDeviceGetAttribute(&v, cudaDevAttrMaxSharedMemoryPerBlockOptin, dev) == cudaSuccess && v > 0) lim = (size_t) v;
1195    const int o = i8_env_int("STRATA_I8_SMEM_LIMIT", 0);   // research / the parity test: pretend a smaller device
1196    return o > 0 && (size_t) o < lim ? (size_t) o : lim;
1197}
1198template <int T, bool GU>
1199void i8_launch(int tm, const I8Args& a, cudaStream_t s) {
1200    if constexpr (i8_tile8_type(T)) {
1201        if (tm == 8) { i8b_launch<T, GU>(a, s); return; }
1202    }
1203    if (tm <= 2) i8_launch_tm<T, GU, 2>(a, s);
1204    else if (tm == 3) i8_launch_tm<T, GU, 3>(a, s);
1205    else i8_launch_tm<T, GU, 4>(a, s);
1206}
1207
1208int i8_env_int(const char* name, int dflt) {
1209    const char* v = std::getenv(name);
1210    return v != nullptr && v[0] != '\0' ? std::atoi(v) : dflt;
1211}