okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
393.0 KiB7382 linesraw
1// src/kernels/cuda/iq_kernels.cu - see include/strata/kernels/iq_kernels.hpp.
2//
3// The dot products (vec_dot_*_q8_1), the dequantizers and the q8_1 quantizer are transcribed from llama.cpp
4// (ggml/src/ggml-cuda/vecdotq.cuh, dequantize.cuh, quantize.cu at the commit in third_party/ggml/VERSION.txt;
5// MIT license, third_party/ggml/LICENSE).  The block structs and codebook grids come from its ggml-common.h,
6// included unchanged.
7#include "strata/kernels/iq_kernels.hpp"
8#include "strata/core/defaults_026.hpp"
9#include "strata/core/expert_nibble.hpp"
10#include "strata/core/sm75_series.hpp"
11#include "strata/core/sm120_series.hpp"
12#include "strata/core/dispatch_stats.hpp"
13#include "strata/kernels/gfx_arch.hpp"
14#include "strata/kernels/i8_expert_rule.hpp"
15#include "strata/kernels/dp4a.hpp"
16#include "strata/kernels/q8_1_finite.hpp"
17#include "s26_tsum.cuh"
18
19#include <cuda_fp16.h>
20#include <cuda_runtime.h>
21
22#define GGML_COMMON_DECL_CUDA
23#define GGML_COMMON_IMPL_CUDA
24#include "ggml-common.h"
25#include "ggml-common-tq.h"   // APR trellis types (agention llama.cpp fork)
26#include "tq_lut_i8.cuh"       // int8 copy of the trellis codebook (one global scale) for the dp4a dot
27
28#include <algorithm>
29#include <atomic>
30#include <cmath>
31#include <cstdio>
32#include <utility>
33#include <cstdlib>
34#include <map>
35#include <mutex>
36#include <tuple>
37#include <type_traits>
38
39namespace strata::kernels {
40namespace {
41
42void check(const char* what) {
43    const cudaError_t e = cudaGetLastError();
44    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e)); std::exit(1); }
45}
46
47// ---------------------------------------------------------------- llama.cpp helpers (vecdotq.cuh)
48__device__ __forceinline__ int get_int_b2(const void* x, const int& i32) {
49    const uint16_t* x16 = (const uint16_t*) x;
50    int x32 = x16[2 * i32 + 0] << 0;
51    x32 |= x16[2 * i32 + 1] << 16;
52    return x32;
53}
54__device__ __forceinline__ int get_int_b4(const void* x, const int& i32) { return ((const int*) x)[i32]; }
55__device__ __forceinline__ uint32_t unpack_ksigns(const uint8_t v) {
56    const uint32_t p = __popc(v) & 1;
57    const uint32_t s = v ^ p << 7;
58    return s * 0x01010101;
59}
60__device__ __forceinline__ int2 get_int_from_table_16(const int& q4, const int8_t* table) {
61#if defined(STRATA_HIP_GFX906)
62    // AMD: llama.cpp's HIP lookup (vecdotq.cuh) - v_perm_b32 takes 3-bit byte indices, so the low and high halves
63    // of the table are looked up and the index MSB picks between them: 4 perms per 8 values.
64    const uint32_t* v32 = reinterpret_cast<const uint32_t*>(table);
65    const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;
66    const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);
67    const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);
68    const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);
69    const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);
70    return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),
71                     (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));
72#else
73    const uint32_t* table32 = (const uint32_t*) table;
74    uint32_t tmp[2];
75    const uint32_t low_high_selection_indices = (0x32103210 | ((q4 & 0x88888888) >> 1));
76#pragma unroll
77    for (uint32_t i = 0; i < 2; ++i) {
78        const uint32_t shift = 16 * i;
79        const uint32_t low = __byte_perm(table32[0], table32[1], q4 >> shift);
80        const uint32_t high = __byte_perm(table32[2], table32[3], q4 >> shift);
81        tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift);
82    }
83    return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531));
84#endif
85}
86#define ggml_cuda_dp4a(a, b, c) STRATA_DP4A((a), (b), (c))
87
88// ---------------------------------------------------------------- the dot products (vecdotq.cuh)
89__device__ __forceinline__ float vec_dot_q2_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
90                                                   const int& kbx, const int& iqs) {
91    const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx;
92    const float d2 = bq2_0->d;
93    const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4;
94    const block_q8_1* bq8_1_chunk = bq8_1 + iqs;
95    int sumi = 0;
96#pragma unroll
97    for (int j = 0; j < 4; ++j) {
98        const int q = qs[j];
99        const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0);
100        const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1);
101        const int qe = __byte_perm(0x020100FF, 0x020100FF, q >> 0);
102        const int qo = __byte_perm(0x020100FF, 0x020100FF, q >> 2);
103        const int qx = __byte_perm(qe, qo, 0x5140);
104        const int qy = __byte_perm(qe, qo, 0x7362);
105        sumi = ggml_cuda_dp4a(u, qx, sumi);
106        sumi = ggml_cuda_dp4a(v, qy, sumi);
107    }
108    const float d8 = __low2float(bq8_1_chunk->ds);
109    return d2 * d8 * sumi;
110}
111
112__device__ __forceinline__ float vec_dot_iq2_xxs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
113                                                      const int& kbx, const int& iqs) {
114    const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx;
115    const int q2 = get_int_b2(bq2->qs, iqs);
116    const uint8_t* aux8 = (const uint8_t*) &q2;
117    const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1);
118    int sumi = 0;
119#pragma unroll
120    for (int k0 = 0; k0 < 8; k0 += 2) {
121        const uint2 grid_pos = ((const uint2*) iq2xxs_grid)[aux8[k0 / 2]];
122        const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2));
123        const int signs0 = __vcmpne4(signs & 0x08040201, 0);
124        const int grid0 = __vsub4(grid_pos.x ^ signs0, signs0);
125        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 0);
126        sumi = ggml_cuda_dp4a(grid0, u0, sumi);
127        const int signs1 = __vcmpne4(signs & 0x80402010, 0);
128        const int grid1 = __vsub4(grid_pos.y ^ signs1, signs1);
129        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 1);
130        sumi = ggml_cuda_dp4a(grid1, u1, sumi);
131    }
132    const int ls = aux32 >> 27 | 1;
133    sumi = sumi * ls / 8;
134    const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);
135    return d * sumi;
136}
137
138__device__ __forceinline__ float vec_dot_iq2_xs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
139                                                     const int& kbx, const int& iqs) {
140    const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx;
141    const int2 q2_packed = make_int2(get_int_b2(bq2->qs, iqs + 0), get_int_b2(bq2->qs, iqs + 1));
142    const uint16_t* q2 = (const uint16_t*) &q2_packed;
143    const int ls0 = bq2->scales[iqs / 2] & 0x0F;
144    const int ls1 = bq2->scales[iqs / 2] >> 4;
145    int sumi0 = 0, sumi1 = 0;
146#pragma unroll
147    for (int l0 = 0; l0 < 8; l0 += 2) {
148        const uint2 grid_pos = ((const uint2*) iq2xs_grid)[q2[l0 / 2] & 0x1FF];
149        const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9);
150        const int signs0 = __vcmpne4(signs & 0x08040201, 0);
151        const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
152        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
153        const int signs1 = __vcmpne4(signs & 0x80402010, 0);
154        const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
155        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
156        if (l0 < 4) {
157            sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0);
158            sumi0 = ggml_cuda_dp4a(grid_h, u1, sumi0);
159        } else {
160            sumi1 = ggml_cuda_dp4a(grid_l, u0, sumi1);
161            sumi1 = ggml_cuda_dp4a(grid_h, u1, sumi1);
162        }
163    }
164    const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;
165    const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);
166    return d * sumi;
167}
168
169__device__ __forceinline__ float vec_dot_iq2_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
170                                                    const int& kbx, const int& iqs) {
171    const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;
172    const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
173    const uint8_t* qs = (const uint8_t*) &qs_packed;
174    const int qh = bq2->qh[iqs / 2];
175    const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
176    const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
177    const int ls0 = bq2->scales[iqs / 2] & 0x0F;
178    const int ls1 = bq2->scales[iqs / 2] >> 4;
179    int sumi0 = 0, sumi1 = 0;
180#pragma unroll
181    for (int l0 = 0; l0 < 8; l0 += 2) {
182        const int* grid_pos = (const int*) (iq2s_grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
183        const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
184        const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
185        const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0);
186        const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1);
187        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
188        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
189        if (l0 < 4) {
190            sumi0 = ggml_cuda_dp4a(grid_l, u0, sumi0);
191            sumi0 = ggml_cuda_dp4a(grid_h, u1, sumi0);
192        } else {
193            sumi1 = ggml_cuda_dp4a(grid_l, u0, sumi1);
194            sumi1 = ggml_cuda_dp4a(grid_h, u1, sumi1);
195        }
196    }
197    const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;
198    const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);
199    return d * sumi;
200}
201
202__device__ __forceinline__ float vec_dot_iq3_xxs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
203                                                      const int& kbx, const int& iqs) {
204    const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
205    const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
206    const uint8_t* q3 = (const uint8_t*) &q3_packed;
207    const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
208    int sumi = 0;
209#pragma unroll
210    for (int l0 = 0; l0 < 8; l0 += 2) {
211        const int2 grid_pos = make_int2(iq3xxs_grid[q3[l0 + 0]], iq3xxs_grid[q3[l0 + 1]]);
212        const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
213        const int signs0 = __vcmpne4(signs & 0x08040201, 0);
214        const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
215        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
216        const int signs1 = __vcmpne4(signs & 0x80402010, 0);
217        const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
218        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
219        sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
220        sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
221    }
222    const int ls = aux32 >> 28;
223    sumi = (ls * sumi + sumi / 2) / 2;
224    const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
225    return d * sumi;
226}
227
228__device__ __forceinline__ float vec_dot_iq3_s_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
229                                                    const int& kbx, const int& iqs) {
230    const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
231    const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
232    const uint8_t* qs = (const uint8_t*) &qs_packed;
233    const int qh = bq3->qh[iqs / 2];
234    const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
235    const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
236    int sumi = 0;
237#pragma unroll
238    for (int l0 = 0; l0 < 8; l0 += 2) {
239        const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
240                                        iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
241        const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
242        const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
243        const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
244        const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
245        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
246        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
247        sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
248        sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
249    }
250    sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
251    const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
252    return d * sumi;
253}
254
255__device__ __forceinline__ float vec_dot_iq1_m_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
256                                                    const int& kbx, const int& iqs) {
257    const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx;
258    const int qs_packed = get_int_b4(bq1->qs, iqs);
259    const uint8_t* qs = (const uint8_t*) &qs_packed;
260    int sumi[2] = {0, 0};
261    float sumf[2] = {0.0f, 0.0f};
262#pragma unroll
263    for (int l0 = 0; l0 < 8; l0 += 2) {
264        const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2));
265        const int grid = iq1s_grid_gpu[qs[l0 / 2] | ((qhl & 0x07) << 8)];
266        const int grid0 = (grid >> 0) & 0x0F0F0F0F;
267        const int grid1 = (grid >> 4) & 0x0F0F0F0F;
268        const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0);
269        const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1);
270        sumi[l0 / 4] = ggml_cuda_dp4a(grid0, u0, sumi[l0 / 4]);
271        sumi[l0 / 4] = ggml_cuda_dp4a(grid1, u1, sumi[l0 / 4]);
272        const float delta = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08);
273        int sumy = 0;
274        sumy = ggml_cuda_dp4a(u0, 0x01010101, sumy);
275        sumy = ggml_cuda_dp4a(u1, 0x01010101, sumy);
276        sumf[l0 / 4] += delta * sumy;
277    }
278    const uint16_t* sc = (const uint16_t*) bq1->scales;
279    iq1m_scale_t scale;
280    scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000);
281    const float d = __half2float(scale.f16) * __low2float(bq8_1[iqs].ds);
282    const int tmp = sc[iqs / 2] >> (6 * (iqs % 2));
283    const int sc0 = 2 * ((tmp >> 0) & 0x07) + 1;
284    const int sc1 = 2 * ((tmp >> 3) & 0x07) + 1;
285    return d * ((sumi[0] + sumf[0]) * sc0 + (sumi[1] + sumf[1]) * sc1);
286}
287
288__device__ __forceinline__ float vec_dot_iq4_nl_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
289                                                     const int& kbx, const int& iqs) {
290    const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;
291    const int* q8 = (const int*) bq8_1->qs + iqs;
292    int sumi = 0;
293#pragma unroll
294    for (int l = 0; l < 2; ++l) {
295        const int aux_q4 = get_int_b2(bq4->qs, iqs + l);
296        const int2 v = get_int_from_table_16(aux_q4, kvalues_iq4nl);
297        sumi = ggml_cuda_dp4a(v.x, q8[l + 0], sumi);
298        sumi = ggml_cuda_dp4a(v.y, q8[l + 4], sumi);
299    }
300    const float d = __half2float(bq4->d) * __low2float(bq8_1->ds);
301    return d * sumi;
302}
303
304// IQ4_XS: 256 values as 8 sub-blocks of 32 (6-bit scale each); one call covers one sub-block (iqs = 4 * sub-block),
305// and `bq8_1` is the super-block's first q8_1 block, so the call's activation is bq8_1[iqs / 4].  The GSQ-RCO IQ3_S
306// file keeps one layer's routed gate/up experts in this format.
307__device__ __forceinline__ float vec_dot_iq4_xs_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
308                                                     const int& kbx, const int& iqs) {
309    const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx;
310    int sumi = 0;
311#pragma unroll
312    for (int j = 0; j < 4; ++j) {
313        const int aux_q4 = get_int_b4(bq4->qs, iqs + j);
314        const int2 v = get_int_from_table_16(aux_q4, kvalues_iq4nl);
315        const int u0 = get_int_b4(bq8_1[iqs / 4].qs, j + 0);
316        const int u1 = get_int_b4(bq8_1[iqs / 4].qs, j + 4);
317        sumi = ggml_cuda_dp4a(v.x, u0, sumi);
318        sumi = ggml_cuda_dp4a(v.y, u1, sumi);
319    }
320    const int ls = ((bq4->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0F) | (((bq4->scales_h >> (iqs / 2)) & 0x03) << 4);
321    sumi *= ls - 32;
322    const float d = __half2float(bq4->d) * __low2float(bq8_1[iqs / 4].ds);
323    return d * sumi;
324}
325
326// ---------------------------------------------------------------- Unsloth's UD-Q4_K_XL experts
327// Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down: llama.cpp's vec_dot_*_q8_1 (vecdotq.cuh, VDR 2 each), transcribed; the
328// Q5_1 min term is the one departure (below).  Via eddoursul/Strata 8029fa9 (iq_dot.cuh) and #255 (Q8_0,
329// gopinath87607), which agree with llama.cpp and with each other.
330constexpr int VDR_Q4_K = 2, VDR_Q5_K = 2, VDR_Q5_1 = 2, VDR_Q5_0 = 2, VDR_Q4_1 = 2, VDR_Q4_0 = 2, VDR_Q8_0 = 2, VDR_Q6_K = 1;
331
332__device__ __forceinline__ float vec_dot_q4_K_q8_1_impl_vmmq(const int* __restrict__ v, const int* __restrict__ u,
333                                                             const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m,
334                                                             const half2& dm4, const float* __restrict__ d8) {
335    float sumf_d = 0.0f;
336    float sumf_m = 0.0f;
337#pragma unroll
338    for (int i = 0; i < QR4_K; ++i) {
339        const int v0i = (v[0] >> (4 * i)) & 0x0F0F0F0F;
340        const int v1i = (v[1] >> (4 * i)) & 0x0F0F0F0F;
341        const int dot1 = ggml_cuda_dp4a(v1i, u[2 * i + 1], ggml_cuda_dp4a(v0i, u[2 * i + 0], 0));
342        const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 1], ggml_cuda_dp4a(0x01010101, u[2 * i + 0], 0));
343        sumf_d += d8[i] * (dot1 * sc[i]);
344        sumf_m += d8[i] * (dot2 * m[i]);   // the min times the sum of the QUANTIZED activations
345    }
346    const float2 dm4f = __half22float2(dm4);
347    return dm4f.x * sumf_d - dm4f.y * sumf_m;
348}
349__device__ __forceinline__ float vec_dot_q5_K_q8_1_impl_vmmq(const int* __restrict__ vl, const int* __restrict__ vh,
350                                                             const int* __restrict__ u, const uint8_t* __restrict__ sc,
351                                                             const uint8_t* __restrict__ m, const half2& dm5,
352                                                             const float* __restrict__ d8) {
353    float sumf_d = 0.0f;
354    float sumf_m = 0.0f;
355#pragma unroll
356    for (int i = 0; i < QR5_K; ++i) {
357        const int vl0i = (vl[0] >> (4 * i)) & 0x0F0F0F0F;
358        const int vl1i = (vl[1] >> (4 * i)) & 0x0F0F0F0F;
359        const int vh0i = ((vh[0] >> i) << 4) & 0x10101010;
360        const int vh1i = ((vh[1] >> i) << 4) & 0x10101010;
361        const int v0i = vl0i | vh0i;
362        const int v1i = vl1i | vh1i;
363        const int dot1 = ggml_cuda_dp4a(v0i, u[2 * i + 0], ggml_cuda_dp4a(v1i, u[2 * i + 1], 0));
364        const int dot2 = ggml_cuda_dp4a(0x01010101, u[2 * i + 0], ggml_cuda_dp4a(0x01010101, u[2 * i + 1], 0));
365        sumf_d += d8[i] * (dot1 * sc[i]);
366        sumf_m += d8[i] * (dot2 * m[i]);
367    }
368    const float2 dm5f = __half22float2(dm5);
369    return dm5f.x * sumf_d - dm5f.y * sumf_m;
370}
371// the 6-bit scales and mins of the 32-value group pair bq8_offset / 2, branchless (llama.cpp; shared by Q4_K, Q5_K)
372__device__ __forceinline__ void k_scale_min(const uint8_t* scales8, int bq8_offset, uint16_t aux[2]) {
373    const uint16_t* scales = (const uint16_t*) scales8;
374    const int j = bq8_offset / 2;
375    const int jm = j & 1;
376    const uint32_t s0 = scales[jm + 0];
377    const uint32_t s2 = scales[jm + 2];
378    const uint32_t s4 = scales[jm + 4];
379    const uint32_t hi = (uint32_t) -(int32_t) (j >= 2);
380    aux[0] = (uint16_t) (((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
381    aux[1] = (uint16_t) (((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
382}
383__device__ __forceinline__ float vec_dot_q4_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
384                                                   const int& kbx, const int& iqs) {
385    const block_q4_K* bq4_K = (const block_q4_K*) vbq + kbx;
386    int v[2];
387    int u[2 * QR4_K];
388    float d8[QR4_K];
389    const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
390    const int* q4 = (const int*) (bq4_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
391    v[0] = q4[0];
392    v[1] = q4[4];
393    uint16_t aux[2];
394    k_scale_min(bq4_K->scales, bq8_offset, aux);
395    const uint8_t* sc = (const uint8_t*) aux;
396    const uint8_t* m = sc + 2;
397#pragma unroll
398    for (int i = 0; i < QR4_K; ++i) {
399        const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
400        d8[i] = __low2float(bq8i->ds);
401        const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
402        u[2 * i + 0] = q8[0];
403        u[2 * i + 1] = q8[4];
404    }
405    return vec_dot_q4_K_q8_1_impl_vmmq(v, u, sc, m, bq4_K->dm, d8);
406}
407__device__ __forceinline__ float vec_dot_q5_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
408                                                   const int& kbx, const int& iqs) {
409    const block_q5_K* bq5_K = (const block_q5_K*) vbq + kbx;
410    int vl[2];
411    int vh[2];
412    int u[2 * QR5_K];
413    float d8[QR5_K];
414    const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
415    const int* ql = (const int*) (bq5_K->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
416    const int* qh = (const int*) (bq5_K->qh + 4 * ((iqs / 2) % 4));
417    vl[0] = ql[0];
418    vl[1] = ql[4];
419    vh[0] = qh[0] >> bq8_offset;
420    vh[1] = qh[4] >> bq8_offset;
421    uint16_t aux[2];
422    k_scale_min(bq5_K->scales, bq8_offset, aux);
423    const uint8_t* sc = (const uint8_t*) aux;
424    const uint8_t* m = sc + 2;
425#pragma unroll
426    for (int i = 0; i < QR5_K; ++i) {
427        const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
428        d8[i] = __low2float(bq8i->ds);
429        const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
430        u[2 * i + 0] = q8[0];
431        u[2 * i + 1] = q8[4];
432    }
433    return vec_dot_q5_K_q8_1_impl_vmmq(vl, vh, u, sc, m, bq5_K->dm, d8);
434}
435
436// Q3_K gate/up: llama.cpp's vec_dot_q3_K_q8_1 (vecdotq.cuh), the mmvq variant with VDR = 2: each call reads TWO
437// qs words (vl[0] = word iqs, vl[1] = word iqs+1) and the matching two hmask words, against QR3_K=4 q8_1 blocks.
438// The three shifted scale ints carry the 6-bit signed scales (sc-32).  Fmt<11> calls this with iqs = 0, 2, .., 14
439// (QI3_K = QK_K/(4*QR3_K) = 16, QI8_1 = 8, ipb = QI3_K/VDR = 8, step = 2), so the two words of every call span all
440// 16 qs words of the 256-value block.  The previous VDR = 1 body read ONE word per call and therefore only the even
441// words (half of every block) - exactly the wrong-output bug this replaces.
442constexpr int VDR_Q3_K = 2;
443__device__ __forceinline__ float vec_dot_q3_K_q8_1_impl_mmvq(const int* __restrict__ vl, const int* __restrict__ vh,
444                                                             const int* __restrict__ u, const int* __restrict__ scales,
445                                                             const float& d3, const float* __restrict__ d8) {
446    float sumf = 0.0f;
447#pragma unroll
448    for (int i = 0; i < QR3_K; ++i) {
449        const int sc_low  = (scales[i / 2] >> (16 * (i % 2))) & 0x0F;
450        const int sc_high = (scales[2] >> (16 * (i % 2) + 2 * (i / 2))) & 0x03;
451        const int sc = (sc_low | (sc_high << 4)) - 32;              // 6-bit signed
452        int sumi = 0;
453#pragma unroll
454        for (int j = 0; j < VDR_Q3_K; ++j) {
455            const int vil = (vl[j] >> (2 * i)) & 0x03030303;        // 2 low bits per value
456            const int vih = ((vh[j] >> i) << 2) & 0x04040404;       // high bit -> 4
457            sumi = ggml_cuda_dp4a(vil | vih,  u[VDR_Q3_K * i + j], sumi);
458            sumi = ggml_cuda_dp4a((int) 0xFCFCFCFC, u[VDR_Q3_K * i + j], sumi);   // -4 per value
459        }
460        sumf += d8[i] * (sumi * sc);
461    }
462    return d3 * sumf;
463}
464__device__ __forceinline__ float vec_dot_q3_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
465                                                   const int& kbx, const int& iqs) {
466    const block_q3_K* bq3_K = (const block_q3_K*) vbq + kbx;
467    const int bq8_offset = QR3_K * (iqs / (QI3_K / 2));
468    const int iqs8 = iqs % QI8_1;
469    const float d = bq3_K->d;
470    int vl[VDR_Q3_K];
471    int vh[VDR_Q3_K];
472#pragma unroll
473    for (int j = 0; j < VDR_Q3_K; ++j) {
474        vl[j] = get_int_b2(bq3_K->qs, iqs + j);
475        vh[j] = get_int_b2(bq3_K->hmask, iqs8 + j) >> bq8_offset;
476    }
477    const int sc_shift = 8 * (iqs8 / (QI8_1 / 2)) + 4 * (iqs / (QI3_K / 2));
478    int scales[3];
479#pragma unroll
480    for (int l = 0; l < 3; ++l) scales[l] = get_int_b2(bq3_K->scales, l) >> sc_shift;
481    int u[VDR_Q3_K * QR3_K];
482    float d8[QR3_K];
483#pragma unroll
484    for (int i = 0; i < QR3_K; ++i) {
485#pragma unroll
486        for (int j = 0; j < VDR_Q3_K; ++j) {
487            u[VDR_Q3_K * i + j] = get_int_b4(bq8_1[bq8_offset + i].qs, iqs8 + j);
488        }
489        d8[i] = __low2float(bq8_1[bq8_offset + i].ds);
490    }
491    return vec_dot_q3_K_q8_1_impl_mmvq(vl, vh, u, scales, d, d8);
492}
493
494// Q5_1: llama.cpp's integer chain, but the min term multiplies the sum of the QUANTIZED activations (dp4a with
495// 0x01010101, times d8) instead of the q8_1 block's `ds.y`, which our quantizer (like llama.cpp's) fills with the sum
496// of the ORIGINAL activations.  That is ggml-cpu's convention (its q8_1 `s` is d * sum(q)) and the one the K-quant
497// mins above use; the scaled and the min term then see the same activation (eddoursul/Strata measured 1.1-1.2%
498// against 1.9% relative error per expert).  Result: sumi * (d5 * d8) + sumu * (m5 * d8).
499// Q5_0: llama.cpp's integer chain (vecdotq.cuh vec_dot_q5_0_q8_1_impl), but the constant -16 per-weight offset multiplies
500// the sum of the QUANTIZED activations (dp4a with 0x01010101, times d8), like the Q5_1 and Q4_0 paths and ggml-cpu's q8_0
501// dot, instead of the q8_1 block's `ds.y` (the sum of the ORIGINAL activations, upstream CUDA).  Round 0214 (owner's yes,
502// 11-05): the original sum does not see the activations' rounding, which the experts' SwiGLU outputs (not zero-mean)
503// make large: the whole-expert error with Q5_0 down was 2.1e-2 .. 3.1e-2 against 1.2e-2 for every other down type, and the
504// GPU now agrees with the CPU path (UD-IQ4_XS, UD-Q3_K_XL).  Result: d5 * d8 * (sumi - 16 * sumu).
505__device__ __forceinline__ float vec_dot_q5_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
506                                                   const int& kbx, const int& iqs) {
507    const block_q5_0* bq5_0 = (const block_q5_0*) vbq + kbx;
508    int sumi = 0, sumu = 0;
509#pragma unroll
510    for (int i = 0; i < VDR_Q5_0; ++i) {
511        const int vl = get_int_b2(bq5_0->qs, iqs + i);
512        const int vh = get_int_b2(bq5_0->qh, 0) >> (4 * (iqs + i));
513        const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_0);
514        int vi0 = (vl >> 0) & 0x0F0F0F0F;
515        vi0 |= (vh << 4) & 0x00000010;
516        vi0 |= (vh << 11) & 0x00001000;
517        vi0 |= (vh << 18) & 0x00100000;
518        vi0 |= (vh << 25) & 0x10000000;
519        sumi = ggml_cuda_dp4a(vi0, u0, sumi);
520        int vi1 = (vl >> 4) & 0x0F0F0F0F;
521        vi1 |= (vh >> 12) & 0x00000010;
522        vi1 |= (vh >> 5) & 0x00001000;
523        vi1 |= (vh << 2) & 0x00100000;
524        vi1 |= (vh << 9) & 0x10000000;
525        sumi = ggml_cuda_dp4a(vi1, u1, sumi);
526        sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
527    }
528    const float d5 = __half2float(bq5_0->d);
529    const float d8 = __low2float(bq8_1->ds);
530    return d5 * d8 * (float) (sumi - 16 * sumu);
531}
532// Q4_0 (plain llama-quantize Q4_0 files, e.g. bartowski's: gate/up and most down projections): the codes are centred
533// (q - 8 as signed bytes) before the dot, the exact integer form ggml-cpu's q4_0 x q8_0 dot uses, rather than
534// llama.cpp's CUDA chain (uncentred codes minus 8 x the q8_1 block's float sum `ds.y`).  On a real Q4_0 expert
535// (2560 x 640) the CUDA chain measured 1.4e-2 relative error against the float product, the centred form 5.3e-3;
536// with the CUDA chain native_expert_parity failed its 3e-2 limit on two layers of a Q4_0 Flash-Next file.  The
537// centring is the same idea as the Q5_1 min term above: the offset is applied to the activations' own int8 codes.
538__device__ __forceinline__ int q4_0_centred(const int v) {
539    // Unsigned: (b & 0x08080808) * 0x1E reaches 0xF0F0F0F0, which overflows a signed int - undefined behaviour the
540    // sm_60 build (no __dp4a, strata_dp4a fallback) optimised into a wrong value (native_expert_parity gpu rel 1.7e4).
541    const uint32_t b = (uint32_t) v ^ 0x08080808u;   // per byte: 0..15 -> (q - 8) as a 4-bit two's complement value
542    return (int) (b | ((b & 0x08080808u) * 0x1Eu));  // sign-extend each nibble into its byte (0x08 * 0x1E = 0xF0)
543}
544__device__ __forceinline__ float vec_dot_q4_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
545                                                   const int& kbx, const int& iqs) {
546    const block_q4_0* bq4 = (const block_q4_0*) vbq + kbx;
547    int sumi = 0;
548#pragma unroll
549    for (int i = 0; i < VDR_Q4_0; ++i) {
550        const int v = get_int_b2(bq4->qs, iqs + i);
551        sumi = ggml_cuda_dp4a(q4_0_centred((v >> 0) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i), sumi);
552        sumi = ggml_cuda_dp4a(q4_0_centred((v >> 4) & 0x0F0F0F0F), get_int_b4(bq8_1->qs, iqs + i + QI4_0), sumi);
553    }
554    return __half2float(bq4->d) * __low2float(bq8_1->ds) * sumi;
555}
556// Q4_1 (llama-quantize puts it on a few down projections of its Q4_0 files): the Q5_1 chain above without the fifth
557// bit, the same min-term choice (the activations' own int8 codes): sumi * (d4 * d8) + sumu * (m4 * d8).
558__device__ __forceinline__ float vec_dot_q4_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
559                                                   const int& kbx, const int& iqs) {
560    const block_q4_1* bq4_1 = (const block_q4_1*) vbq + kbx;
561    int sumi = 0, sumu = 0;
562#pragma unroll
563    for (int i = 0; i < VDR_Q4_1; ++i) {
564        const int v = get_int_b4(bq4_1->qs, iqs + i);
565        const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI4_1);
566        sumi = ggml_cuda_dp4a((v >> 0) & 0x0F0F0F0F, u0, sumi);
567        sumi = ggml_cuda_dp4a((v >> 4) & 0x0F0F0F0F, u1, sumi);
568        sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
569    }
570    const float2 dm4 = __half22float2(bq4_1->dm);
571    const float d8 = __low2float(bq8_1->ds);
572    return sumi * (dm4.x * d8) + sumu * (dm4.y * d8);
573}
574__device__ __forceinline__ float vec_dot_q5_1_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
575                                                   const int& kbx, const int& iqs) {
576    const block_q5_1* bq5_1 = (const block_q5_1*) vbq + kbx;
577    int sumi = 0, sumu = 0;
578#pragma unroll
579    for (int i = 0; i < VDR_Q5_1; ++i) {
580        const int vl = get_int_b4(bq5_1->qs, iqs + i);
581        const int vh = get_int_b4(bq5_1->qh, 0) >> (4 * (iqs + i));
582        const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1);
583        int vi0 = (vl >> 0) & 0x0F0F0F0F;
584        vi0 |= (vh << 4) & 0x00000010;
585        vi0 |= (vh << 11) & 0x00001000;
586        vi0 |= (vh << 18) & 0x00100000;
587        vi0 |= (vh << 25) & 0x10000000;
588        sumi = ggml_cuda_dp4a(vi0, u0, sumi);
589        int vi1 = (vl >> 4) & 0x0F0F0F0F;
590        vi1 |= (vh >> 12) & 0x00000010;
591        vi1 |= (vh >> 5) & 0x00001000;
592        vi1 |= (vh << 2) & 0x00100000;
593        vi1 |= (vh << 9) & 0x10000000;
594        sumi = ggml_cuda_dp4a(vi1, u1, sumi);
595        sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
596    }
597    const float2 dm5 = __half22float2(bq5_1->dm);
598    const float d8 = __low2float(bq8_1->ds);
599    return sumi * (dm5.x * d8) + sumu * (dm5.y * d8);
600}
601// Q6_K: llama.cpp's integer chain verbatim (vecdotq.cuh vec_dot_q6_K_q8_1_impl_mmvq / vec_dot_q6_K_q8_1) -- signed
602// per-16-element scales, the -32 offset folded into the per-byte value, the q8_1 block's ds.low for the scales,
603// upstream exactly as pulled (no min-term choice exists: Q6_K has no learned min).
604__device__ __forceinline__ float vec_dot_q6_K_q8_1_impl_mmvq(const int vl, const int vh, const int* __restrict__ u,
605                                                             const int8_t* __restrict__ scales, const float d,
606                                                             const float* __restrict__ d8) {
607    float sumf = 0.0f;
608#pragma unroll
609    for (int i = 0; i < QR6_K; ++i) {
610        const int sc = scales[4 * i];
611        const int vil = (vl >> (4 * i)) & 0x0F0F0F0F;
612        const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;
613        const int vi = __vsubss4(vil | vih, 0x20202020);   // vi = (vil | vih) - 32
614        sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);
615    }
616    return d * sumf;
617}
618__device__ __forceinline__ float vec_dot_q6_K_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
619                                                   const int& kbx, const int& iqs) {
620    const block_q6_K* bq6_K = (const block_q6_K*) vbq + kbx;
621    const int bq8_offset = 2 * QR6_K * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 4);
622    const int scale_offset = (QI6_K / 4) * (iqs / (QI6_K / 2)) + (iqs % (QI6_K / 2)) / (QI6_K / 8);
623    const int vh_shift = 2 * ((iqs % (QI6_K / 2)) / (QI6_K / 4));
624    const int vl = get_int_b2(bq6_K->ql, iqs);
625    const int vh = get_int_b2(bq6_K->qh, (QI6_K / 4) * (iqs / (QI6_K / 2)) + iqs % (QI6_K / 4)) >> vh_shift;
626    const int8_t* scales = bq6_K->scales + scale_offset;
627    int u[QR6_K];
628    float d8[QR6_K];
629#pragma unroll
630    for (int i = 0; i < QR6_K; ++i) {
631        u[i] = get_int_b4(bq8_1[bq8_offset + 2 * i].qs, iqs % QI8_1);
632        d8[i] = __low2float(bq8_1[bq8_offset + 2 * i].ds);
633    }
634    return vec_dot_q6_K_q8_1_impl_mmvq(vl, vh, u, scales, __half2float(bq6_K->d), d8);
635}
636__device__ __forceinline__ float vec_dot_q8_0_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
637                                                   const int& kbx, const int& iqs) {
638    const block_q8_0* bq8_0 = (const block_q8_0*) vbq + kbx;
639    int sumi = 0;
640#pragma unroll
641    for (int i = 0; i < VDR_Q8_0; ++i)
642        sumi = ggml_cuda_dp4a(get_int_b2(bq8_0->qs, iqs + i), get_int_b4(bq8_1->qs, iqs + i), sumi);
643    const float d8_0 = __half2float(bq8_0->d), d8_1 = __low2float(bq8_1->ds);
644    return d8_0 * d8_1 * ((float) sumi);
645}
646// NVFP4 (ModelOpt): 64 values = 4 sub-blocks of 16, one UE4M3 scale each, E2M1 codes split-half like Q4_0.
647// kvalues_fp4 holds the E2M1 values doubled (0, 1, 2, 3, 4, 6, 8, 12), so the scale is halved here - exactly
648// ggml's ggml_cuda_ue4m3_to_fp32, decoded in software so the GPU and ggml-cpu agree bit for bit (NaN -> 0).
649__device__ __forceinline__ float ue4m3_to_f32_half(uint8_t x) {
650    // The same value as ldexpf(1 + man/8, exp - 7) * 0.5 (ldexpf(man, -9) * 0.5 for exp 0), built from its bits: every
651    // such value is exact in FP32, so this is equal for all 256 inputs - without the ldexpf and the branches it cost
652    // in the decode experts' inner loop.  Normal: 2^(exp-8) * (1 + man/8) = exponent field exp + 119, mantissa man<<20.
653    if (x == 0 || x == 0x7F) return 0.0f;
654    const uint32_t exp = (x >> 3) & 0xF, man = x & 0x7;
655    return exp == 0 ? (float) man * 0.0009765625f : __uint_as_float(((exp + 119u) << 23) | (man << 20));
656}
657
658// One call = two sub-blocks (32 values); `bq8_1` is the block's first q8_1 block (two per 64 values).
659__device__ __forceinline__ float vec_dot_nvfp4_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
660                                                    const int& kbx, const int& iqs) {
661    const block_nvfp4* bq4 = (const block_nvfp4*) vbq + kbx;
662    float sum = 0.0f;
663#pragma unroll
664    for (int i = 0; i < 2; i++) {
665        const int iqs0 = iqs + 2 * i, iqs1 = iqs0 + 1, is = iqs0 >> 1;
666        const int2 v0 = get_int_from_table_16(get_int_b4(bq4->qs, iqs0), kvalues_fp4);
667        const int2 v1 = get_int_from_table_16(get_int_b4(bq4->qs, iqs1), kvalues_fp4);
668        const block_q8_1* bq8 = bq8_1 + (is >> 1);
669        const int i8 = (is & 1) << 2;
670        int sumi = ggml_cuda_dp4a(v0.x, get_int_b4(bq8->qs, i8 + 0), 0);
671        sumi = ggml_cuda_dp4a(v0.y, get_int_b4(bq8->qs, i8 + 2), sumi);
672        sumi = ggml_cuda_dp4a(v1.x, get_int_b4(bq8->qs, i8 + 1), sumi);
673        sumi = ggml_cuda_dp4a(v1.y, get_int_b4(bq8->qs, i8 + 3), sumi);
674        sum += ue4m3_to_f32_half(bq4->d[is]) * __low2float(bq8->ds) * (float) sumi;
675    }
676    return sum;
677}
678
679// ---------------------------------------------------------------- APR trellis types (ggml 144 TQ2_T, 145 TQK6, 146 TQK7)
680// Transcribed from the agention llama.cpp fork's ggml-cuda/tq.cuh (6d3f2b1b8; format in ggml-common-tq.h).  A
681// 128-value block is 8 lanes of 4 trellis steps (16 values); the dot of lane l reads q8_1 block l/2, ints 4(l&1)..
682template<int TY> struct TqInfo;
683template<> struct TqInfo<144> { using block_t = block_tq2_t; };   // byte-aligned, no K
684template<> struct TqInfo<145> { using block_t = block_tqk6; static constexpr int K = 6; };
685template<> struct TqInfo<146> { using block_t = block_tqk7; static constexpr int K = 7; };
686// Gyro-L: pair trellis (64 steps x K bits, 2 weights per step), the TQ2_T codebook's first pair
687template<> struct TqInfo<147> { using block_t = block_tqp5; static constexpr int K = 5; };
688template<> struct TqInfo<148> { using block_t = block_tqp6; static constexpr int K = 6; };
689template<> struct TqInfo<149> { using block_t = block_tqp7; static constexpr int K = 7; };
690__device__ __forceinline__ float tq_h2f(uint32_t bits) { return __half2float(__ushort_as_half((unsigned short) bits)); }
691// the four unscaled weights of the step with state s: (a.x, a.y, b.x, b.y)
692__device__ __forceinline__ void tq_step(uint32_t s, float2& a, float2& b) {
693    const uint32_t* lut = (const uint32_t*) tq_lut_f16;
694    const uint32_t x = (s & TQ_STATE_MASK) * 0x9e3779b1u;
695    const uint32_t pa = lut[x >> 21], pb = lut[(x >> 10) & 2047u];
696    a = make_float2(tq_h2f(pa & 0xFFFFu), tq_h2f(pa >> 16));
697    b = make_float2(tq_h2f(pb & 0xFFFFu), tq_h2f(pb >> 16));
698}
699// the states of steps 4l..4l+3 of one block (qs is 2-byte aligned: every trellis block has an even size)
700// Compute capability 6.0 (Tesla P100): the block's words are read with ld.global.nc (the weights are read-only; a generic
701// pointer made these LD.E), and TQK6's lane window needs only three words (34 bits from a bit offset of 0 or 8), TQK7's
702// four.  The same bits either way.
703#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610
704#define STRATA_TQ_LD16(p) ((uint32_t) __ldg((const unsigned short*) (p)))
705#else
706#define STRATA_TQ_LD16(p) ((uint32_t) *(p))
707#endif
708template<int TY>
709__device__ __forceinline__ void tq_states4(const uint8_t* qs, int l, uint32_t s[4]) {
710    const uint16_t* qs16 = (const uint16_t*) qs;
711    if constexpr (TY == 144) {   // s_t = qs[(t + 31) % 32] << 8 | qs[t]
712        const uint32_t w01 = STRATA_TQ_LD16(qs16 + 2 * l + 0), w23 = STRATA_TQ_LD16(qs16 + 2 * l + 1);
713        const uint32_t prev = qs[(4 * l + 31) & 31];
714        const uint32_t b0 = w01 & 0xFF, b1 = w01 >> 8, b2 = w23 & 0xFF, b3 = w23 >> 8;
715        s[0] = (prev << 8) | b0;
716        s[1] = (b0 << 8) | b1;
717        s[2] = (b1 << 8) | b2;
718        s[3] = (b2 << 8) | b3;
719    } else {
720        // step t's state: the 16 stream bits from bit (31 - t)*K, circular over 2K u16 words; steps 4l..4l+3 all
721        // lie in the four words from (28 - 4l)*K >> 4
722        constexpr int K = TqInfo<TY>::K, nwords = 2 * K;
723        const int off3 = (28 - 4 * l) * K, wb = off3 >> 4, r = off3 & 15;
724        const int wi1 = wb + 1 >= nwords ? wb + 1 - nwords : wb + 1;
725        const int wi2 = wb + 2 >= nwords ? wb + 2 - nwords : wb + 2;
726        const int wi3 = wb + 3 >= nwords ? wb + 3 - nwords : wb + 3;
727        uint64_t v = (uint64_t) STRATA_TQ_LD16(qs16 + wb) | ((uint64_t) STRATA_TQ_LD16(qs16 + wi1) << 16) |
728                     ((uint64_t) STRATA_TQ_LD16(qs16 + wi2) << 32);
729#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 610
730        if constexpr (K == 6) {   // r is 0 or 8 here: bits r .. r + 33 < 48, the fourth word is never read
731        } else
732#endif
733        v |= (uint64_t) STRATA_TQ_LD16(qs16 + wi3) << 48;
734#pragma unroll
735        for (int i = 0; i < 4; ++i) s[i] = (uint32_t) (v >> (r + (3 - i) * K)) & 0xFFFFu;
736    }
737}
738// lane iqs/4 of block kbx against the q8_1 blocks aligned with the block's start (4 per trellis block).  Split in
739// two, like the IQ types' decode-once kernels below: tq_load decodes the lane's 16 codebook values (weight side only),
740// tq_apply does the activation side.  vec_dot_tq_q8_1 is apply(load()), and the decode-once kernels call tq_load once
741// per weight part and tq_apply per entry: the same integer and float operations in the same order, so the two kernel
742// families are bitwise equal to EACH OTHER (native_expert_parity: "decode-once vs per-entry kernels").  Neither is
743// bitwise equal to a float decode of the weights, see Numerics.
744// The lane's 16 codebook values as 4 ints of packed int8: a trellis step's 4 weights are two 2-byte entries = one
745// int, so the apply side is 4 dp4a instead of 16 int8->float + 16 FMAs, and a decoded lane takes 5 registers
746// instead of 17.
747//
748// Numerics.  Decode (these kernels) reads the int8 codebook tq_lut_i8: one global scale TQ_LUT_I8_SCALE, relative
749// RMS error 0.85% of the codebook std, far below the trellis quantization error.  The prompt path decodes the
750// trellis otherwise: the FP16 path (dq_tq below) through the fp16 codebook tq_lut_f16, which is what ggml's to_float
751// reads, and the MMQ path through the GGML fork's tile loader (the int8 codebook too on the fork's main since
752// 2026-10-03; the fp16 codebook requantized to int8 per 16 weights before that and with GGML_CUDA_TQ_F32_DOT).
753// Decode and prompt therefore agree within tolerance, not bitwise.  native_expert_parity bounds this path: one
754// expert (int8 codebook, q8_1 activations) against ggml's float dequantizer and a float SwiGLU, relative L1 error
755// sum|gpu - ref| / sum|ref| < 3e-2 (the bound every expert type's CPU and GPU paths get there); the prompt path's
756// fp16 dequantizers against to_float at < 1e-6, their fp16 output equal to the fp16 of the float one.
757struct TqLane { int q[4]; float d; };
758// STAGED: the int8 codebook is read from shared memory (s_lut: the 2048 u16 of tq_lut_i8, copied by stage_iq_grid)
759// instead of the global table.  The same 16-bit entries, so the same weights.
760template<int TY, bool STAGED = false>
761__device__ __forceinline__ TqLane tq_load(const void* __restrict__ vbq, int kbx, int iqs, const uint16_t* __restrict__ s_lut = nullptr) {
762    const auto* b = (const typename TqInfo<TY>::block_t*) vbq + kbx;
763    uint32_t s[4];
764    tq_states4<TY>(b->qs, iqs / 4, s);
765    TqLane r;
766    const uint16_t* lut = STAGED ? s_lut : tq_lut_i8;
767#pragma unroll
768    for (int i = 0; i < 4; ++i) {
769        const uint32_t x = (s[i] & TQ_STATE_MASK) * 0x9e3779b1u;
770        r.q[i] = (int) ((uint32_t) lut[x >> 21] | ((uint32_t) lut[(x >> 10) & 2047u] << 16));
771    }
772    r.d = tq_h2f(STRATA_TQ_LD16(&b->d));
773    return r;
774}
775__device__ __forceinline__ float tq_apply(const TqLane& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
776    const int l = iqs / 4;
777    const block_q8_1* b8 = bq8_1 + l / 2;
778    const int* q8 = (const int*) b8->qs + 4 * (l & 1);
779    int sumi = 0;
780#pragma unroll
781    for (int i = 0; i < 4; ++i) sumi = ggml_cuda_dp4a(r.q[i], q8[i], sumi);
782    return r.d * (__low2float(b8->ds) * TQ_LUT_I8_SCALE) * (float) sumi;
783}
784template<int TY>
785__device__ __forceinline__ float vec_dot_tq_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
786                                                 const int& kbx, const int& iqs) {
787    return tq_apply(tq_load<TY>(vbq, kbx, iqs), bq8_1, iqs);
788}
789
790// ---- TQP (Gyro-L): 64 trellis steps of 2 weights; a lane is 8 steps (16 values).
791// State of step t: the 16 stream bits from bit (63 - t)*K, LSB-first, circular over 64*K bits
792// (tqp_state in the fork's ggml-common.h). The step's 2 weights are tq2t_lut_f16[2*hyb(2*s)+j],
793// i.e. the FIRST pair of TQ2_T state s = tq_lut_i8[x >> 21] (tq_lut_i8 holds the pair as two int8).
794// A lane's 8 states are the 16-bit fields at bit i*K of the bit stream starting at its 8th-to-last
795// step, so the whole lane needs K + 2 bytes (7, 8 or 9 for K = 5, 6, 7): one byte-built 64-bit
796// window plus one byte for K = 7's first state (which ends at bit 65), then eight shifts.  That is
797// 7-9 loads per lane instead of 24.  The bytes are loaded (not one u64) because a block's qs array
798// is only 2-byte aligned (block strides are 42/50/58 bytes).
799template<int TY>
800__device__ __forceinline__ void tqp_states8(const uint8_t* __restrict__ qs, int lane, uint32_t s[8]) {
801    constexpr int K = TqInfo<TY>::K, NB = 8 * K, NW = K + 2 < 8 ? K + 2 : 8;
802    const int pidx = (7 - lane) * K;          // the lane's first byte, always < NB
803    uint64_t w = 0;                           // bits pidx*8 .. pidx*8+63
804#pragma unroll
805    for (int j = 0; j < NW; ++j) {
806        const int idx0 = pidx + j;
807        w |= (uint64_t) qs[idx0 < NB ? idx0 : idx0 - NB] << (8 * j);
808    }
809    const int i8 = pidx + 8;
810    const uint32_t hi = K == 7 ? (uint32_t) qs[i8 < NB ? i8 : i8 - NB] : 0u;   // the 65th bit
811#pragma unroll
812    for (int i = 0; i < 8; ++i) {
813        const int sh = (7 - i) * K;                               // 0 .. 7K (<= 49)
814        const uint32_t lo = (uint32_t) (w >> sh);
815        const uint32_t top = sh > 48 ? (uint32_t) (hi << (64 - sh)) : 0u;
816        s[i] = (lo | top) & 0xFFFFu;
817    }
818}
819// The per-state form: 3 byte loads and a shift, no window.  Used by dq_tqp (the f16 expert uploads), which
820// benches faster with it than with the window (the window's register pressure costs the copy kernels).
821template<int TY>
822__device__ __forceinline__ void tqp_states8_cheap(const uint8_t* __restrict__ qs, int lane, uint32_t s[8]) {
823    constexpr int K = TqInfo<TY>::K, NB = 8 * K;
824#pragma unroll
825    for (int i = 0; i < 8; ++i) {
826        const uint32_t off = (uint32_t) (63 - (8 * lane + i)) * (uint32_t) K;
827        const uint32_t i0 = off >> 3;
828        const uint32_t i1 = i0 + 1 < (uint32_t) NB ? i0 + 1 : 0;
829        const uint32_t i2 = i1 + 1 < (uint32_t) NB ? i1 + 1 : 0;
830        const uint32_t w = (uint32_t) qs[i0] | ((uint32_t) qs[i1] << 8) | ((uint32_t) qs[i2] << 16);
831        s[i] = (w >> (off & 7)) & 0xFFFFu;
832    }
833}
834template<int TY>
835__device__ __forceinline__ TqLane tq_load_tqp(const void* __restrict__ vbq, int kbx, int iqs) {
836    const auto* b = (const typename TqInfo<TY>::block_t*) vbq + kbx;
837    uint32_t s[8];
838    tqp_states8<TY>(b->qs, iqs / 4, s);
839    TqLane r;
840#pragma unroll
841    for (int i = 0; i < 4; ++i) {   // two steps (2+2 weights) per int
842        const uint32_t x0 = (s[2 * i] & TQ_STATE_MASK) * 0x9e3779b1u;
843        const uint32_t x1 = (s[2 * i + 1] & TQ_STATE_MASK) * 0x9e3779b1u;
844        r.q[i] = (int) ((uint32_t) tq_lut_i8[x0 >> 21] | ((uint32_t) tq_lut_i8[x1 >> 21] << 16));
845    }
846    r.d = tq_h2f(b->d);
847    return r;
848}
849template<int TY>
850__device__ __forceinline__ float vec_dot_tqp_q8_1(const void* __restrict__ vbq, const block_q8_1* __restrict__ bq8_1,
851                                                  const int& kbx, const int& iqs) {
852    return tq_apply(tq_load_tqp<TY>(vbq, kbx, iqs), bq8_1, iqs);
853}
854
855// ---------------------------------------------------------------- the formats
856// qk = values per block, ipb = dot calls per block (qi / vdr), step = the iqs stride between calls.
857template<int TY> struct Fmt;
858template<> struct Fmt<16> { static constexpr int qk = 256, ipb = 8, step = 2;
859    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xxs_q8_1(v, y, kbx, iqs); } };
860template<> struct Fmt<17> { static constexpr int qk = 256, ipb = 8, step = 2;
861    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_xs_q8_1(v, y, kbx, iqs); } };
862template<> struct Fmt<18> { static constexpr int qk = 256, ipb = 8, step = 2;
863    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq3_xxs_q8_1(v, y, kbx, iqs); } };
864template<> struct Fmt<20> { static constexpr int qk = 32, ipb = 2, step = 2;
865    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq4_nl_q8_1(v, y, kbx, iqs); } };
866template<> struct Fmt<21> { static constexpr int qk = 256, ipb = 8, step = 2;
867    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq3_s_q8_1(v, y, kbx, iqs); } };
868template<> struct Fmt<23> { static constexpr int qk = 256, ipb = 8, step = 4;
869    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq4_xs_q8_1(v, y, kbx, iqs); } };
870template<> struct Fmt<22> { static constexpr int qk = 256, ipb = 8, step = 2;
871    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq2_s_q8_1(v, y, kbx, iqs); } };
872template<> struct Fmt<29> { static constexpr int qk = 256, ipb = 8, step = 1;
873    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_iq1_m_q8_1(v, y, kbx, iqs); } };
874template<> struct Fmt<42> { static constexpr int qk = 64, ipb = 2, step = 1;
875    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q2_0_q8_1(v, y, kbx, iqs); } };
876template<> struct Fmt<12> { static constexpr int qk = 256, ipb = QI4_K / VDR_Q4_K, step = VDR_Q4_K;
877    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_K_q8_1(v, y, kbx, iqs); } };
878template<> struct Fmt<13> { static constexpr int qk = 256, ipb = QI5_K / VDR_Q5_K, step = VDR_Q5_K;
879    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_K_q8_1(v, y, kbx, iqs); } };
880template<> struct Fmt<11> { static constexpr int qk = 256, ipb = QI3_K / VDR_Q3_K, step = VDR_Q3_K;
881    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q3_K_q8_1(v, y, kbx, iqs); } };
882template<> struct Fmt<14> { static constexpr int qk = 256, ipb = QI6_K / VDR_Q6_K, step = VDR_Q6_K;
883    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q6_K_q8_1(v, y, kbx, iqs); } };
884template<> struct Fmt<7> { static constexpr int qk = 32, ipb = QI5_1 / VDR_Q5_1, step = VDR_Q5_1;
885    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_1_q8_1(v, y, kbx, iqs); } };
886template<> struct Fmt<2> { static constexpr int qk = 32, ipb = QI4_0 / VDR_Q4_0, step = VDR_Q4_0;
887    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_0_q8_1(v, y, kbx, iqs); } };
888template<> struct Fmt<3> { static constexpr int qk = 32, ipb = QI4_1 / VDR_Q4_1, step = VDR_Q4_1;
889    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q4_1_q8_1(v, y, kbx, iqs); } };
890template<> struct Fmt<6> { static constexpr int qk = 32, ipb = QI5_0 / VDR_Q5_0, step = VDR_Q5_0;
891    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q5_0_q8_1(v, y, kbx, iqs); } };
892template<> struct Fmt<8> { static constexpr int qk = 32, ipb = QI8_0 / VDR_Q8_0, step = VDR_Q8_0;
893    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_q8_0_q8_1(v, y, kbx, iqs); } };
894// APR trellis types: 8 lanes of 4 steps per 128-value block, iqs = 4 * lane
895template<> struct Fmt<144> { static constexpr int qk = 128, ipb = 8, step = 4;
896    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tq_q8_1<144>(v, y, kbx, iqs); } };
897template<> struct Fmt<145> { static constexpr int qk = 128, ipb = 8, step = 4;
898    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tq_q8_1<145>(v, y, kbx, iqs); } };
899template<> struct Fmt<146> { static constexpr int qk = 128, ipb = 8, step = 4;
900    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tq_q8_1<146>(v, y, kbx, iqs); } };
901// Gyro-L pair trellis: 8 lanes of 8 steps (16 values) per 128-value block
902#define STRATA_TQP_FMT(T) template<> struct Fmt<T> { static constexpr int qk = 128, ipb = 8, step = 4; \
903    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_tqp_q8_1<T>(v, y, kbx, iqs); } };
904STRATA_TQP_FMT(147)
905STRATA_TQP_FMT(148)
906STRATA_TQP_FMT(149)
907#undef STRATA_TQP_FMT
908
909// The formats of each role, one list each so a type cannot be in one switch and missing from another.  Every
910// entry is a kernel template for each CUDA architecture of the build, hence two lists rather than one.
911#ifdef STRATA_Q6K_EXPERTS   // opt-in build (-DSTRATA_Q6K_EXPERTS=ON): one more instance per kernel, loaded at start
912#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(11) X(12) X(13) X(14) X(6) X(2) X(3) X(8) X(40) X(144) X(145) X(147) X(148) X(149)
913#else
914#define STRATA_GU_FMTS(X) X(16) X(17) X(18) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(6) X(2) X(3) X(8) X(40) X(144) X(145) X(147) X(148) X(149)
915#endif
916// Q5_K / Q6_K downs: Qwen3.6-35B-A3B (FF 512, whole 256-blocks per row); Flash-Next's FF 640 never selects them
917#ifdef STRATA_Q6K_EXPERTS
918#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(14) X(40) X(144) X(146) X(147) X(148) X(149)
919#else
920#define STRATA_D_FMTS(X) X(20) X(23) X(42) X(7) X(6) X(2) X(3) X(8) X(13) X(40) X(144) X(146) X(147) X(148) X(149)
921#endif
922#define STRATA_MMVQ_FMTS(X) X(16) X(17) X(18) X(20) X(21) X(22) X(23) X(29) X(42) X(12) X(13) X(7) X(6) X(2) X(3) X(8) X(40) X(144) X(145) X(146) X(147) X(148) X(149)
923template<> struct Fmt<40> { static constexpr int qk = 64, ipb = 2, step = 4;     // NVFP4: 2 calls of 32 values
924    __device__ static float dot(const void* v, const block_q8_1* y, int kbx, int iqs) { return vec_dot_nvfp4_q8_1(v, y, kbx, iqs); } };
925
926__device__ __forceinline__ float warp_sum(float v) {
927#pragma unroll
928    for (int o = 16; o > 0; o >>= 1) v += __shfl_xor_sync(0xffffffffu, v, o);
929    return v;
930}
931
932// One row against one q8_1 activation, the whole warp: call k = (block, part) is lane-strided.
933template<int TY>
934__device__ __forceinline__ float row_dot(const uint8_t* row, const block_q8_1* x, int nb, int lane) {
935    using F = Fmt<TY>;
936    float s = 0.0f;
937    for (int k = lane; k < nb * F::ipb; k += 32) {
938        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
939        s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs);
940    }
941    return warp_sum(s);
942}
943
944template<int TY>
945__global__ void __launch_bounds__(128) mmvq_kernel(const uint8_t* __restrict__ w, size_t row_bytes,
946                                                   const block_q8_1* __restrict__ x, float* __restrict__ y, int n_in,
947                                                   int n_out, int ncols) {
948    const int row = blockIdx.x * 4 + threadIdx.y;
949    if (row >= n_out) return;
950    const int lane = threadIdx.x;
951    const int nb = n_in / Fmt<TY>::qk;
952    const uint8_t* wr = w + (size_t) row * row_bytes;
953    for (int c = 0; c < ncols; ++c) {
954        const float s = row_dot<TY>(wr, x + (size_t) c * (n_in / 32), nb, lane);
955        if (lane == 0) y[(size_t) c * n_out + row] = s;
956    }
957}
958
959// ---------------------------------------------------------------- decode once, apply to every column
960// The kernels above call Fmt<TY>::dot once per (call, column): each column re-reads the weight words and redoes
961// the grid lookups and sign unpacking.  Here each dot is split, as native_mmvq.cu's multi-column traits are, into
962// `load` (everything that depends only on the weight: the signed grid words, the integer scales, the fp16 block
963// scale as a float) and `apply` (the activation loads, the dp4a chain in the same order, the same integer scale
964// step and the same float expression).  `apply(load(...))` does the dot's integer and float operations in the same
965// order on the same values, so a column of the kernels below is BITWISE equal to the same column of mmvq_kernel /
966// native_gu_kernel / native_down_kernel (iq_multi_parity checks it; STRATA_OLD_IQ_MMVQ=1 keeps the old kernels).
967template<int TY> struct Split;
968// Formats with a Split below take the decode-once kernels; the others (Q4_K, Q5_K, Q5_1, Q8_0: UD-Q4_K_XL) the
969// per-entry ones, which call Fmt<TY>::dot per column exactly as before #242 (the launchers test kSplit at compile
970// time, so the multi kernels are never instantiated for a type without a Split).
971template<int TY> inline constexpr bool kSplit = false;
972// The K-quant / Q8_0 / Q5_1 formats (UD-Q4_K_XL) have Split traits (SplitK below), but their decode-once multi kernels
973// run only with STRATA_KQ_SPLIT=1 until the A/B on the measured cards decides (bitwise the old kernels either way).
974template<int TY> inline constexpr bool kq_type = (TY == 12 || TY == 13 || TY == 8);   // not Q5_1: its Split apply is not bitwise the old dot (FMA contraction), see notes-151-amd
975inline bool g_kq_split = [] { const char* v = std::getenv("STRATA_KQ_SPLIT"); return v != nullptr && v[0] == '1'; }();
976template<int TY> inline bool split_off() { return kq_type<TY> && !g_kq_split; }
977template<int TY> inline constexpr bool kTqType = (TY == 144 || TY == 145 || TY == 146);
978// the trellis types stage their int8 codebook (4 KB) too, but only where it pays: tq_stage_on() below (compute capability 6.0)
979template<int TY> inline constexpr bool kStageIqGrid = (TY == 16 || TY == 17 || TY == 18 || TY == 21 || TY == 22 || TY == 29 || kTqType<TY>);
980
981// LDS-only barrier (#3259, bsorensen110): the staging barriers of the grid / activation tables need the shared-memory stores to be
982// visible, not a global-memory fence; on gfx12 __syncthreads() is s_wait_loadcnt_dscnt 0; s_barrier; global_inv scope:SCOPE_SE.
983__device__ __forceinline__ void iq_sync_lds() {
984#if defined(__gfx1200__) || defined(__gfx1201__)
985    asm volatile("s_wait_dscnt 0x0\n\ts_barrier_signal -1\n\ts_barrier_wait -1" ::: "memory");
986#else
987    __syncthreads();   // every other target keeps the full barrier (the other HIP targets were not run for this change)
988#endif
989}
990
991template<> inline constexpr bool kSplit<16> = true;
992template<> struct Split<16> {   // IQ2_XXS
993    struct W { int g[8]; int ls; float dw; };
994    template<bool STAGE_GRID = false>
995    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
996        const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx;
997        const int q2 = get_int_b2(bq2->qs, iqs);
998        const uint8_t* aux8 = (const uint8_t*) &q2;
999        const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1);
1000        const uint2* grid_lut;
1001        if constexpr (STAGE_GRID) grid_lut = (const uint2*) s_grid;
1002        else grid_lut = (const uint2*) iq2xxs_grid;
1003        W r;
1004#pragma unroll
1005        for (int k0 = 0; k0 < 8; k0 += 2) {
1006            const uint2 grid_pos = grid_lut[aux8[k0 / 2]];
1007            const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2));
1008            const int signs0 = __vcmpne4(signs & 0x08040201, 0);
1009            r.g[k0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
1010            const int signs1 = __vcmpne4(signs & 0x80402010, 0);
1011            r.g[k0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
1012        }
1013        r.ls = aux32 >> 27 | 1;
1014        r.dw = __half2float(bq2->d);
1015        return r;
1016    }
1017    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1018        int sumi = 0;
1019#pragma unroll
1020        for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi);
1021        sumi = sumi * r.ls / 8;
1022        const float d = r.dw * __low2float(bq8_1[iqs / 2].ds);
1023        return d * sumi;
1024    }
1025    // `apply` with the q8_1 block already in registers: u = its 8 words, d8 = __low2float(ds).  Same operations in
1026    // the same order (the EXPDEC kernels, see expdec below).
1027    __device__ static float apply_u(const W& r, const int (&u)[8], float d8) {
1028        int sumi = 0;
1029#pragma unroll
1030        for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], u[j], sumi);
1031        sumi = sumi * r.ls / 8;
1032        const float d = r.dw * d8;
1033        return d * sumi;
1034    }
1035};
1036// IQ2_XS and IQ2_S share the apply: two half sums, two 4-bit scales
1037struct SplitLs2 {
1038    struct W { int g[8]; int ls0, ls1; float dw; };
1039    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1040        int sumi0 = 0, sumi1 = 0;
1041#pragma unroll
1042        for (int j = 0; j < 4; ++j) sumi0 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi0);
1043#pragma unroll
1044        for (int j = 4; j < 8; ++j) sumi1 = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi1);
1045        const int sumi = (sumi0 * r.ls0 + sumi1 * r.ls1 + (sumi0 + sumi1) / 2) / 4;
1046        const float d = r.dw * __low2float(bq8_1[iqs / 2].ds);
1047        return d * sumi;
1048    }
1049    __device__ static float apply_u(const W& r, const int (&u)[8], float d8) {
1050        int sumi0 = 0, sumi1 = 0;
1051#pragma unroll
1052        for (int j = 0; j < 4; ++j) sumi0 = ggml_cuda_dp4a(r.g[j], u[j], sumi0);
1053#pragma unroll
1054        for (int j = 4; j < 8; ++j) sumi1 = ggml_cuda_dp4a(r.g[j], u[j], sumi1);
1055        const int sumi = (sumi0 * r.ls0 + sumi1 * r.ls1 + (sumi0 + sumi1) / 2) / 4;
1056        const float d = r.dw * d8;
1057        return d * sumi;
1058    }
1059};
1060template<> inline constexpr bool kSplit<17> = true;
1061template<> struct Split<17> : SplitLs2 {   // IQ2_XS
1062    template<bool STAGE_GRID = false>
1063    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1064        const block_iq2_xs* bq2 = (const block_iq2_xs*) vbq + kbx;
1065        const int2 q2_packed = make_int2(get_int_b2(bq2->qs, iqs + 0), get_int_b2(bq2->qs, iqs + 1));
1066        const uint16_t* q2 = (const uint16_t*) &q2_packed;
1067        const uint2* grid_lut;
1068        if constexpr (STAGE_GRID) grid_lut = (const uint2*) s_grid;
1069        else grid_lut = (const uint2*) iq2xs_grid;
1070        W r;
1071        r.ls0 = bq2->scales[iqs / 2] & 0x0F;
1072        r.ls1 = bq2->scales[iqs / 2] >> 4;
1073#pragma unroll
1074        for (int l0 = 0; l0 < 8; l0 += 2) {
1075            const uint2 grid_pos = grid_lut[q2[l0 / 2] & 0x1FF];
1076            const uint32_t signs = unpack_ksigns(q2[l0 / 2] >> 9);
1077            const int signs0 = __vcmpne4(signs & 0x08040201, 0);
1078            r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
1079            const int signs1 = __vcmpne4(signs & 0x80402010, 0);
1080            r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
1081        }
1082        r.dw = __half2float(bq2->d);
1083        return r;
1084    }
1085};
1086template<> inline constexpr bool kSplit<22> = true;
1087template<> struct Split<22> : SplitLs2 {   // IQ2_S
1088    template<bool STAGE_GRID = false>
1089    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1090        const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;
1091        const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
1092        const uint8_t* qs = (const uint8_t*) &qs_packed;
1093        const int qh = bq2->qh[iqs / 2];
1094        const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
1095        const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
1096        const uint64_t* grid_lut;
1097        if constexpr (STAGE_GRID) grid_lut = (const uint64_t*) s_grid;
1098        else grid_lut = iq2s_grid;
1099        W r;
1100        r.ls0 = bq2->scales[iqs / 2] & 0x0F;
1101        r.ls1 = bq2->scales[iqs / 2] >> 4;
1102#pragma unroll
1103        for (int l0 = 0; l0 < 8; l0 += 2) {
1104            const int* grid_pos = (const int*) (grid_lut + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
1105            const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
1106            const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
1107            r.g[l0 + 0] = __vsub4(grid_pos[0] ^ signs0, signs0);
1108            r.g[l0 + 1] = __vsub4(grid_pos[1] ^ signs1, signs1);
1109        }
1110        r.dw = __half2float(bq2->d);
1111        return r;
1112    }
1113};
1114template<> inline constexpr bool kSplit<18> = true;
1115template<> struct Split<18> {   // IQ3_XXS
1116    struct W { int g[8]; int ls; float dw; };
1117    template<bool STAGE_GRID = false>
1118    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1119        const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
1120        const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
1121        const uint8_t* q3 = (const uint8_t*) &q3_packed;
1122        const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
1123        const uint32_t* grid = STAGE_GRID ? s_grid : iq3xxs_grid;
1124        W r;
1125#pragma unroll
1126        for (int l0 = 0; l0 < 8; l0 += 2) {
1127            const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]);
1128            if constexpr (STAGE_GRID) {
1129                // The staged tables hold one mask per 7-bit sign field; bit 7 of the field is the next group's
1130                // first sign, which unpack_ksigns cancels, so masking it off is the same value.
1131                const uint32_t v = (aux32 >> (7 * l0 / 2)) & 0x7f;
1132                const uint32_t ml = s_grid[256 + v], mh = s_grid[384 + v];
1133                r.g[l0 + 0] = (int) ((grid_pos.x ^ ml) + (ml & 0x01010101u));
1134                r.g[l0 + 1] = (int) ((grid_pos.y ^ mh) + (mh & 0x01010101u));
1135            } else {
1136                const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
1137                const int signs0 = __vcmpne4(signs & 0x08040201, 0);
1138                r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
1139                const int signs1 = __vcmpne4(signs & 0x80402010, 0);
1140                r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
1141            }
1142        }
1143        r.ls = aux32 >> 28;
1144        r.dw = __half2float(bq3->d);
1145        return r;
1146    }
1147    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1148        int sumi = 0;
1149#pragma unroll
1150        for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi);
1151        sumi = (r.ls * sumi + sumi / 2) / 2;
1152        const float d = r.dw * __low2float(bq8_1[iqs / 2].ds);
1153        return d * sumi;
1154    }
1155    __device__ static float apply_u(const W& r, const int (&u)[8], float d8) {
1156        int sumi = 0;
1157#pragma unroll
1158        for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], u[j], sumi);
1159        sumi = (r.ls * sumi + sumi / 2) / 2;
1160        const float d = r.dw * d8;
1161        return d * sumi;
1162    }
1163};
1164template<> inline constexpr bool kSplit<21> = true;
1165template<> struct Split<21> {   // IQ3_S
1166    struct W { int g[8]; int ls; float dw; };
1167    template<bool STAGE_GRID = false>
1168    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1169        const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
1170        const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
1171        const uint8_t* qs = (const uint8_t*) &qs_packed;
1172        const int qh = bq3->qh[iqs / 2];
1173        const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
1174        const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
1175        const uint32_t* grid = STAGE_GRID ? s_grid : iq3s_grid;
1176        W r;
1177#pragma unroll
1178        for (int l0 = 0; l0 < 8; l0 += 2) {
1179            const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
1180                                            grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
1181            if constexpr (STAGE_GRID) {
1182                // The staged tables hold the byte masks of a sign byte's bits 0-3 and 4-7; every iq3s_grid byte is
1183                // odd, so (g ^ mask) + (mask & 0x01010101) negates the masked bytes with no carry into the next.
1184                const uint32_t ml = s_grid[512 + signs_packed_8[l0 / 2]], mh = s_grid[768 + signs_packed_8[l0 / 2]];
1185                r.g[l0 + 0] = (int) (((uint32_t) grid_pos.x ^ ml) + (ml & 0x01010101u));
1186                r.g[l0 + 1] = (int) (((uint32_t) grid_pos.y ^ mh) + (mh & 0x01010101u));
1187            } else {
1188                const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
1189                const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
1190                r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
1191                r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
1192            }
1193        }
1194        r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
1195        r.dw = __half2float(bq3->d);
1196        return r;
1197    }
1198    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1199        int sumi = 0;
1200#pragma unroll
1201        for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], get_int_b4(bq8_1[iqs / 2].qs, j), sumi);
1202        sumi *= r.ls;
1203        const float d = r.dw * __low2float(bq8_1[iqs / 2].ds);
1204        return d * sumi;
1205    }
1206    __device__ static float apply_u(const W& r, const int (&u)[8], float d8) {
1207        int sumi = 0;
1208#pragma unroll
1209        for (int j = 0; j < 8; ++j) sumi = ggml_cuda_dp4a(r.g[j], u[j], sumi);
1210        sumi *= r.ls;
1211        const float d = r.dw * d8;
1212        return d * sumi;
1213    }
1214};
1215template<> inline constexpr bool kSplit<29> = true;
1216template<> struct Split<29> {   // IQ1_M
1217    struct W { int g[8]; float delta[4]; int sc0, sc1; float dw; };
1218    template<bool STAGE_GRID = false>
1219    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1220        const block_iq1_m* bq1 = (const block_iq1_m*) vbq + kbx;
1221        const int qs_packed = get_int_b4(bq1->qs, iqs);
1222        const uint8_t* qs = (const uint8_t*) &qs_packed;
1223        const uint32_t* grid_lut;
1224        if constexpr (STAGE_GRID) grid_lut = s_grid;
1225        else grid_lut = iq1s_grid_gpu;
1226        W r;
1227#pragma unroll
1228        for (int l0 = 0; l0 < 8; l0 += 2) {
1229            const int qhl = bq1->qh[2 * iqs + l0 / 4] >> (4 * ((l0 / 2) % 2));
1230            const int grid = grid_lut[qs[l0 / 2] | ((qhl & 0x07) << 8)];
1231            r.g[l0 + 0] = (grid >> 0) & 0x0F0F0F0F;
1232            r.g[l0 + 1] = (grid >> 4) & 0x0F0F0F0F;
1233            r.delta[l0 / 2] = -1.0f + IQ1M_DELTA - (qhl & 0x08) * (2.0f * IQ1M_DELTA / 0x08);
1234        }
1235        const uint16_t* sc = (const uint16_t*) bq1->scales;
1236        iq1m_scale_t scale;
1237        scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00F0) | ((sc[2] >> 4) & 0x0F00) | (sc[3] & 0xF000);
1238        r.dw = __half2float(scale.f16);
1239        const int tmp = sc[iqs / 2] >> (6 * (iqs % 2));
1240        r.sc0 = 2 * ((tmp >> 0) & 0x07) + 1;
1241        r.sc1 = 2 * ((tmp >> 3) & 0x07) + 1;
1242        return r;
1243    }
1244    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1245        int sumi[2] = {0, 0};
1246        float sumf[2] = {0.0f, 0.0f};
1247#pragma unroll
1248        for (int l0 = 0; l0 < 8; l0 += 2) {
1249            const int u0 = get_int_b4(bq8_1[iqs].qs, l0 + 0);
1250            const int u1 = get_int_b4(bq8_1[iqs].qs, l0 + 1);
1251            sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 0], u0, sumi[l0 / 4]);
1252            sumi[l0 / 4] = ggml_cuda_dp4a(r.g[l0 + 1], u1, sumi[l0 / 4]);
1253            int sumy = 0;
1254            sumy = ggml_cuda_dp4a(u0, 0x01010101, sumy);
1255            sumy = ggml_cuda_dp4a(u1, 0x01010101, sumy);
1256            sumf[l0 / 4] += r.delta[l0 / 2] * sumy;
1257        }
1258        const float d = r.dw * __low2float(bq8_1[iqs].ds);
1259        return d * ((sumi[0] + sumf[0]) * r.sc0 + (sumi[1] + sumf[1]) * r.sc1);
1260    }
1261};
1262template<> inline constexpr bool kSplit<20> = true;
1263template<> struct Split<20> {   // IQ4_NL
1264    struct W { int2 v[2]; float dw; };
1265    template<bool STAGE_GRID = false>
1266    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1267        const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;
1268        W r;
1269#pragma unroll
1270        for (int l = 0; l < 2; ++l) r.v[l] = get_int_from_table_16(get_int_b2(bq4->qs, iqs + l), kvalues_iq4nl);
1271        r.dw = __half2float(bq4->d);
1272        return r;
1273    }
1274    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1275        const int* q8 = (const int*) bq8_1->qs + iqs;
1276        int sumi = 0;
1277#pragma unroll
1278        for (int l = 0; l < 2; ++l) {
1279            sumi = ggml_cuda_dp4a(r.v[l].x, q8[l + 0], sumi);
1280            sumi = ggml_cuda_dp4a(r.v[l].y, q8[l + 4], sumi);
1281        }
1282        const float d = r.dw * __low2float(bq8_1->ds);
1283        return d * sumi;
1284    }
1285    // `apply` with the block's words in registers: p0 = words iqs, iqs + 1; p1 = words iqs + 4, iqs + 5; d8 = __low2float(ds)
1286    __device__ static float apply_u(const W& r, int2 p0, int2 p1, float d8) {
1287        int sumi = 0;
1288        sumi = ggml_cuda_dp4a(r.v[0].x, p0.x, sumi);
1289        sumi = ggml_cuda_dp4a(r.v[0].y, p1.x, sumi);
1290        sumi = ggml_cuda_dp4a(r.v[1].x, p0.y, sumi);
1291        sumi = ggml_cuda_dp4a(r.v[1].y, p1.y, sumi);
1292        const float d = r.dw * d8;
1293        return d * sumi;
1294    }
1295};
1296template<> inline constexpr bool kSplit<23> = true;
1297template<> struct Split<23> {   // IQ4_XS
1298    struct W { int2 v[4]; int ls; float dw; };
1299    template<bool STAGE_GRID = false>
1300    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1301        const block_iq4_xs* bq4 = (const block_iq4_xs*) vbq + kbx;
1302        W r;
1303#pragma unroll
1304        for (int j = 0; j < 4; ++j) r.v[j] = get_int_from_table_16(get_int_b4(bq4->qs, iqs + j), kvalues_iq4nl);
1305        r.ls = ((bq4->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0F) | (((bq4->scales_h >> (iqs / 2)) & 0x03) << 4);
1306        r.dw = __half2float(bq4->d);
1307        return r;
1308    }
1309    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1310        int sumi = 0;
1311#pragma unroll
1312        for (int j = 0; j < 4; ++j) {
1313            const int u0 = get_int_b4(bq8_1[iqs / 4].qs, j + 0);
1314            const int u1 = get_int_b4(bq8_1[iqs / 4].qs, j + 4);
1315            sumi = ggml_cuda_dp4a(r.v[j].x, u0, sumi);
1316            sumi = ggml_cuda_dp4a(r.v[j].y, u1, sumi);
1317        }
1318        sumi *= r.ls - 32;
1319        const float d = r.dw * __low2float(bq8_1[iqs / 4].ds);
1320        return d * sumi;
1321    }
1322};
1323template<> inline constexpr bool kSplit<42> = true;
1324template<> struct Split<42> {   // Q2_0
1325    struct W { int qx[4], qy[4]; float d2; };
1326    template<bool STAGE_GRID = false>
1327    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1328        const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx;
1329        W r;
1330        r.d2 = bq2_0->d;
1331        const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4;
1332#pragma unroll
1333        for (int j = 0; j < 4; ++j) {
1334            const int q = qs[j];
1335            const int qe = __byte_perm(0x020100FF, 0x020100FF, q >> 0);
1336            const int qo = __byte_perm(0x020100FF, 0x020100FF, q >> 2);
1337            r.qx[j] = __byte_perm(qe, qo, 0x5140);
1338            r.qy[j] = __byte_perm(qe, qo, 0x7362);
1339        }
1340        return r;
1341    }
1342    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1343        const block_q8_1* bq8_1_chunk = bq8_1 + iqs;
1344        int sumi = 0;
1345#pragma unroll
1346        for (int j = 0; j < 4; ++j) {
1347            const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0);
1348            const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1);
1349            sumi = ggml_cuda_dp4a(u, r.qx[j], sumi);
1350            sumi = ggml_cuda_dp4a(v, r.qy[j], sumi);
1351        }
1352        const float d8 = __low2float(bq8_1_chunk->ds);
1353        return r.d2 * d8 * sumi;
1354    }
1355    // `apply` with the q8_1 block (2 kbx + iqs) in registers: u = its 8 words, d8 = __low2float(ds)
1356    __device__ static float apply_u(const W& r, const int (&u)[8], float d8) {
1357        int sumi = 0;
1358#pragma unroll
1359        for (int j = 0; j < 4; ++j) {
1360            sumi = ggml_cuda_dp4a(u[j * 2 + 0], r.qx[j], sumi);
1361            sumi = ggml_cuda_dp4a(u[j * 2 + 1], r.qy[j], sumi);
1362        }
1363        return r.d2 * d8 * sumi;
1364    }
1365};
1366template<int TY> struct S27;
1367template<> struct S27<12> {   // Q4_K
1368    struct W { int v[2]; uint16_t aux[2]; half2 dm; };
1369    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
1370        const block_q4_K* b = (const block_q4_K*) vbq + kbx;
1371        W r;
1372        const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
1373        const int* q4 = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
1374        r.v[0] = q4[0];
1375        r.v[1] = q4[4];
1376        k_scale_min(b->scales, bq8_offset, r.aux);
1377        r.dm = b->dm;
1378        return r;
1379    }
1380    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1381        const int bq8_offset = QR4_K * ((iqs / 2) / (QI8_1 / 2));
1382        int u[2 * QR4_K];
1383        float d8[QR4_K];
1384#pragma unroll
1385        for (int i = 0; i < QR4_K; ++i) {
1386            const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
1387            d8[i] = __low2float(bq8i->ds);
1388            const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
1389            u[2 * i + 0] = q8[0];
1390            u[2 * i + 1] = q8[4];
1391        }
1392        const uint8_t* sc = (const uint8_t*) r.aux;
1393        const uint8_t* m = sc + 2;
1394        return vec_dot_q4_K_q8_1_impl_vmmq(r.v, u, sc, m, r.dm, d8);
1395    }
1396};
1397template<> struct S27<13> {   // Q5_K
1398    struct W { int vl[2]; int vh[2]; uint16_t aux[2]; half2 dm; };
1399    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
1400        const block_q5_K* b = (const block_q5_K*) vbq + kbx;
1401        W r;
1402        const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
1403        const int* ql = (const int*) (b->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
1404        const int* qh = (const int*) (b->qh + 4 * ((iqs / 2) % 4));
1405        r.vl[0] = ql[0];
1406        r.vl[1] = ql[4];
1407        r.vh[0] = qh[0] >> bq8_offset;
1408        r.vh[1] = qh[4] >> bq8_offset;
1409        k_scale_min(b->scales, bq8_offset, r.aux);
1410        r.dm = b->dm;
1411        return r;
1412    }
1413    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1414        const int bq8_offset = QR5_K * ((iqs / 2) / (QI8_1 / 2));
1415        int u[2 * QR5_K];
1416        float d8[QR5_K];
1417#pragma unroll
1418        for (int i = 0; i < QR5_K; ++i) {
1419            const block_q8_1* bq8i = bq8_1 + bq8_offset + i;
1420            d8[i] = __low2float(bq8i->ds);
1421            const int* q8 = (const int*) bq8i->qs + ((iqs / 2) % 4);
1422            u[2 * i + 0] = q8[0];
1423            u[2 * i + 1] = q8[4];
1424        }
1425        const uint8_t* sc = (const uint8_t*) r.aux;
1426        const uint8_t* m = sc + 2;
1427        return vec_dot_q5_K_q8_1_impl_vmmq(r.vl, r.vh, u, sc, m, r.dm, d8);
1428    }
1429};
1430template<> struct S27<7> {   // Q5_1
1431    struct W { int vl[VDR_Q5_1]; int qh; half2 dm; };
1432    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
1433        const block_q5_1* b = (const block_q5_1*) vbq + kbx;
1434        W r;
1435#pragma unroll
1436        for (int i = 0; i < VDR_Q5_1; ++i) r.vl[i] = get_int_b4(b->qs, iqs + i);
1437        r.qh = get_int_b4(b->qh, 0);
1438        r.dm = b->dm;
1439        return r;
1440    }
1441    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1442        int sumi = 0, sumu = 0;
1443#pragma unroll
1444        for (int i = 0; i < VDR_Q5_1; ++i) {
1445            const int vl = r.vl[i];
1446            const int vh = r.qh >> (4 * (iqs + i));
1447            const int u0 = get_int_b4(bq8_1->qs, iqs + i), u1 = get_int_b4(bq8_1->qs, iqs + i + QI5_1);
1448            int vi0 = (vl >> 0) & 0x0F0F0F0F;
1449            vi0 |= (vh << 4) & 0x00000010;
1450            vi0 |= (vh << 11) & 0x00001000;
1451            vi0 |= (vh << 18) & 0x00100000;
1452            vi0 |= (vh << 25) & 0x10000000;
1453            sumi = ggml_cuda_dp4a(vi0, u0, sumi);
1454            int vi1 = (vl >> 4) & 0x0F0F0F0F;
1455            vi1 |= (vh >> 12) & 0x00000010;
1456            vi1 |= (vh >> 5) & 0x00001000;
1457            vi1 |= (vh << 2) & 0x00100000;
1458            vi1 |= (vh << 9) & 0x10000000;
1459            sumi = ggml_cuda_dp4a(vi1, u1, sumi);
1460            sumu = ggml_cuda_dp4a(0x01010101, u1, ggml_cuda_dp4a(0x01010101, u0, sumu));
1461        }
1462        const float2 dm5 = __half22float2(r.dm);
1463        const float d8 = __low2float(bq8_1->ds);
1464        return sumi * (dm5.x * d8) + sumu * (dm5.y * d8);
1465    }
1466};
1467template<> struct S27<8> {   // Q8_0
1468    struct W { int q[VDR_Q8_0]; float d; };
1469    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
1470        const block_q8_0* b = (const block_q8_0*) vbq + kbx;
1471        W r;
1472#pragma unroll
1473        for (int i = 0; i < VDR_Q8_0; ++i) r.q[i] = get_int_b2(b->qs, iqs + i);
1474        r.d = __half2float(b->d);
1475        return r;
1476    }
1477    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1478        int sumi = 0;
1479#pragma unroll
1480        for (int i = 0; i < VDR_Q8_0; ++i) sumi = ggml_cuda_dp4a(r.q[i], get_int_b4(bq8_1->qs, iqs + i), sumi);
1481        const float d8_1 = __low2float(bq8_1->ds);
1482        return r.d * d8_1 * ((float) sumi);
1483    }
1484};
1485// K-quants and Q5_1 / Q8_0 (UD-Q4_K_XL): the S27 load / apply (below the same file used them first for the V2K
1486// grouped kernels) as Split traits, so the generic multi-column kernels decode a weight once per call for these
1487// formats too.  Bitwise the old per-column Fmt<TY>::dot (the S27 apply is that dot's own expression; iq_multi_parity).
1488// STRATA_OLD_IQ_MMVQ=1 keeps the old kernels; STRATA_KQ_SPLIT=0 keeps them for these four formats only.
1489template<int TY> struct SplitK : S27<TY> {
1490    template<bool STAGE_GRID = false>
1491    __device__ static typename S27<TY>::W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1492        return S27<TY>::load(vbq, kbx, iqs);
1493    }
1494};
1495template<> inline constexpr bool kSplit<12> = true;
1496template<> inline constexpr bool kSplit<13> = true;
1497template<> inline constexpr bool kSplit<8> = true;
1498template<> struct Split<12> : SplitK<12> {};
1499template<> struct Split<13> : SplitK<13> {};
1500template<> struct Split<8> : SplitK<8> {};
1501template<> inline constexpr bool kSplit<40> = true;
1502template<> struct Split<40> {   // NVFP4: vec_dot_nvfp4_q8_1's two 16-value sub-blocks, weights decoded once per call
1503    struct W { int2 v0[2], v1[2]; float sc[2]; };
1504    template<bool STAGE_GRID = false>
1505    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1506        const block_nvfp4* bq4 = (const block_nvfp4*) vbq + kbx;
1507        W r;
1508#pragma unroll
1509        for (int i = 0; i < 2; i++) {
1510            const int iqs0 = iqs + 2 * i, iqs1 = iqs0 + 1, is = iqs0 >> 1;
1511            r.v0[i] = get_int_from_table_16(get_int_b4(bq4->qs, iqs0), kvalues_fp4);
1512            r.v1[i] = get_int_from_table_16(get_int_b4(bq4->qs, iqs1), kvalues_fp4);
1513            r.sc[i] = ue4m3_to_f32_half(bq4->d[is]);
1514        }
1515        return r;
1516    }
1517    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
1518        float sum = 0.0f;                              // the same operations, in the same order, as the dot
1519#pragma unroll
1520        for (int i = 0; i < 2; i++) {
1521            const int is = (iqs + 2 * i) >> 1;
1522            const block_q8_1* bq8 = bq8_1 + (is >> 1);
1523            const int i8 = (is & 1) << 2;
1524            int sumi = ggml_cuda_dp4a(r.v0[i].x, get_int_b4(bq8->qs, i8 + 0), 0);
1525            sumi = ggml_cuda_dp4a(r.v0[i].y, get_int_b4(bq8->qs, i8 + 2), sumi);
1526            sumi = ggml_cuda_dp4a(r.v1[i].x, get_int_b4(bq8->qs, i8 + 1), sumi);
1527            sumi = ggml_cuda_dp4a(r.v1[i].y, get_int_b4(bq8->qs, i8 + 3), sumi);
1528            sum += r.sc[i] * __low2float(bq8->ds) * (float) sumi;
1529        }
1530        return sum;
1531    }
1532};
1533// APR trellis types: the lane's 16 decoded codebook values (tq_load / tq_apply above)
1534template<> inline constexpr bool kSplit<144> = true;
1535template<> inline constexpr bool kSplit<145> = true;
1536template<> inline constexpr bool kSplit<146> = true;
1537template<int TY> struct SplitTq {
1538    using W = TqLane;
1539    template<bool STAGE_GRID = false>   // STAGE_GRID: the codebook in shared memory (s_grid, see stage_iq_grid)
1540    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ s_grid = nullptr) {
1541        return tq_load<TY, STAGE_GRID>(vbq, kbx, iqs, (const uint16_t*) s_grid);
1542    }
1543    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { return tq_apply(r, bq8_1, iqs); }
1544};
1545template<> struct Split<144> : SplitTq<144> {};
1546template<> struct Split<145> : SplitTq<145> {};
1547template<> struct Split<146> : SplitTq<146> {};
1548// Gyro-L TQP (147-149): the pair layout needs tq_load_tqp, not tq_load, so its split is its own trait.
1549// Until this existed the launchers took the per-entry mmvq/native kernels for TQP, and row_dot_multi's
1550// callers re-decoded the lane once per activation.
1551template<int TY> struct SplitTqp {
1552    using W = TqLane;
1553    template<bool STAGE_GRID = false>   // (no grid table to stage: the codebook is read where it is)
1554    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* __restrict__ = nullptr) {
1555        return tq_load_tqp<TY>(vbq, kbx, iqs);
1556    }
1557    __device__ static float apply(const W& r, const block_q8_1* __restrict__ bq8_1, int iqs) { return tq_apply(r, bq8_1, iqs); }
1558};
1559template<> inline constexpr bool kSplit<147> = true;
1560template<> inline constexpr bool kSplit<148> = true;
1561template<> inline constexpr bool kSplit<149> = true;
1562template<> struct Split<147> : SplitTqp<147> {};
1563template<> struct Split<148> : SplitTqp<148> {};
1564template<> struct Split<149> : SplitTqp<149> {};
1565
1566// One row against the n <= NC activations x + off[0..n) (n >= 1, warp-uniform; offsets in q8_1 blocks, 32-bit to
1567// spare registers), the whole warp.  Per activation this is row_dot: the same calls k, lane-strided the same way,
1568// summed in the same order, then the same warp_sum.  Only the weight side moves out of the per-activation loop.
1569template<int TY, int NC, bool EXACT_N = false, bool STAGE_GRID = false>
1570__device__ __forceinline__ void row_dot_multi(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n,
1571                                              int nb, int lane, float (&s)[NC], const uint32_t* __restrict__ s_grid = nullptr) {
1572    using F = Fmt<TY>;
1573    using S = Split<TY>;
1574#pragma unroll
1575    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
1576    for (int k = lane; k < nb * F::ipb; k += 32) {
1577        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1578        const typename S::W w = S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1579#pragma unroll
1580        for (int c = 0; c < NC; ++c)
1581            if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1582    }
1583#pragma unroll
1584    for (int c = 0; c < NC; ++c)
1585        if (EXACT_N || c < n) s[c] = warp_sum(s[c]);
1586}
1587
1588// 8-lane sub-warp row dot for K = nb * ipb == 40 (TD == 20, IQ4_NL with n_ff == 640):
1589// 4 rows per warp (32 rows per 256-thread block), 100% active lanes, bitwise identical addition tree to row_dot_multi.
1590template<int TY, int NC, bool EXACT_N = false, bool STAGE_GRID = false>
1591__device__ __forceinline__ void row_dot_40_sub8(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n,
1592                                                int t, float (&s)[NC], const uint32_t* __restrict__ s_grid = nullptr) {
1593    using F = Fmt<TY>;
1594    using S = Split<TY>;
1595#pragma unroll
1596    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
1597    for (int k = t; k < 40; k += 32) {
1598        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1599        const typename S::W w = S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1600#pragma unroll
1601        for (int c = 0; c < NC; ++c)
1602            if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1603    }
1604    {
1605        const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1606        const typename S::W w = S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1607#pragma unroll
1608        for (int c = 0; c < NC; ++c) {
1609            if (EXACT_N || c < n) {
1610                float s16 = 0.0f;
1611                s16 += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1612                s[c] = __fadd_rn(s[c], s16);
1613            }
1614        }
1615    }
1616    float s8[NC];
1617#pragma unroll
1618    for (int c = 0; c < NC; ++c) s8[c] = 0.0f;
1619    {
1620        const int k = t + 8, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1621        const typename S::W w = S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1622#pragma unroll
1623        for (int c = 0; c < NC; ++c)
1624            if (EXACT_N || c < n) s8[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1625    }
1626    {
1627        const int k = t + 24, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1628        const typename S::W w = S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1629#pragma unroll
1630        for (int c = 0; c < NC; ++c) {
1631            if (EXACT_N || c < n) {
1632                float s24 = 0.0f;
1633                s24 += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1634                s[c] = __fadd_rn(s[c], __fadd_rn(s8[c], s24));
1635            }
1636        }
1637    }
1638#pragma unroll
1639    for (int c = 0; c < NC; ++c) {
1640        if (EXACT_N || c < n) {
1641#pragma unroll
1642            for (int o = 4; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
1643        }
1644    }
1645}
1646
1647// 8-lane sub-warp row dot for K = nb * ipb == 20 (TD == 40, NVFP4 with n_ff == 640): 4 rows per warp (32 rows per
1648// 256-thread block).  Bitwise row_dot_multi's tree: warp_sum adds lane i + 16 (terms k and k + 16; lanes 20-31 hold
1649// +0) then i + 8, then 4, 2, 1 - so lane t here takes k = t (+ k = t + 16 for t < 4, else + 0) and k = t + 8 (+ 0).
1650template<int TY, int NC, bool EXACT_N = false>
1651__device__ __forceinline__ void row_dot_20_sub8(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n,
1652                                                int t, float (&s)[NC]) {
1653    using F = Fmt<TY>;
1654    using S = Split<TY>;
1655#pragma unroll
1656    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
1657    {
1658        const int k = t, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1659        const typename S::W w = S::load(row, kbx, iqs);
1660#pragma unroll
1661        for (int c = 0; c < NC; ++c)
1662            if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1663    }
1664    float s16[NC];
1665#pragma unroll
1666    for (int c = 0; c < NC; ++c) s16[c] = 0.0f;
1667    if (t < 4) {
1668        const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1669        const typename S::W w = S::load(row, kbx, iqs);
1670#pragma unroll
1671        for (int c = 0; c < NC; ++c)
1672            if (EXACT_N || c < n) s16[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1673    }
1674    float s8[NC];
1675#pragma unroll
1676    for (int c = 0; c < NC; ++c) s8[c] = 0.0f;
1677    {
1678        const int k = t + 8, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1679        const typename S::W w = S::load(row, kbx, iqs);
1680#pragma unroll
1681        for (int c = 0; c < NC; ++c)
1682            if (EXACT_N || c < n) s8[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1683    }
1684#pragma unroll
1685    for (int c = 0; c < NC; ++c) {
1686        if (EXACT_N || c < n) {
1687            s[c] = __fadd_rn(__fadd_rn(s[c], s16[c]), __fadd_rn(s8[c], 0.0f));
1688#pragma unroll
1689            for (int o = 4; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
1690        }
1691    }
1692}
1693
1694// 16-lane sub-warp row dot for K = nb * ipb == 20 (TD == 42, Q2_0, and TD == 40, NVFP4, with n_ff == 640):
1695// 2 rows per warp (16 rows per 256-thread block), bitwise identical addition tree to row_dot_multi.
1696template<int TY, int NC, bool EXACT_N = false>
1697__device__ __forceinline__ void row_dot_20_sub16(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n,
1698                                                 int t, float (&s)[NC]) {
1699    using F = Fmt<TY>;
1700    using S = Split<TY>;
1701#pragma unroll
1702    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
1703    {
1704        const int k = t, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1705        const typename S::W w = S::load(row, kbx, iqs);
1706#pragma unroll
1707        for (int c = 0; c < NC; ++c)
1708            if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1709    }
1710    float s16[NC];
1711#pragma unroll
1712    for (int c = 0; c < NC; ++c) s16[c] = 0.0f;
1713    if (t < 4) {
1714        const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1715        const typename S::W w = S::load(row, kbx, iqs);
1716#pragma unroll
1717        for (int c = 0; c < NC; ++c)
1718            if (EXACT_N || c < n) s16[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1719    }
1720#pragma unroll
1721    for (int c = 0; c < NC; ++c) {
1722        if (EXACT_N || c < n) {
1723            s[c] = __fadd_rn(s[c], s16[c]);
1724#pragma unroll
1725            for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
1726        }
1727    }
1728}
1729
1730// 16-lane sub-warp row dot for K = nb * ipb == 80 (all kSplit gate/up formats with n_embd == 2560):
1731// 2 rows per warp (16 rows per 256-thread block), 100% active lanes, bitwise identical addition tree to row_dot_multi.
1732template<int TY, int NC, bool EXACT_N = false, bool STAGE_GRID = false>
1733__device__ __forceinline__ void row_dot_80_sub16(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n,
1734                                                 int t, float (&s)[NC], const uint32_t* __restrict__ s_grid = nullptr) {
1735    using F = Fmt<TY>;
1736    using S = Split<TY>;
1737#pragma unroll
1738    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
1739    for (int k = t; k < 80; k += 32) {
1740        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1741        const typename S::W w = S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1742#pragma unroll
1743        for (int c = 0; c < NC; ++c)
1744            if (EXACT_N || c < n) s[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1745    }
1746    float s16[NC];
1747#pragma unroll
1748    for (int c = 0; c < NC; ++c) s16[c] = 0.0f;
1749    for (int k = t + 16; k < 64; k += 32) {
1750        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1751        const typename S::W w = S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1752#pragma unroll
1753        for (int c = 0; c < NC; ++c)
1754            if (EXACT_N || c < n) s16[c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1755    }
1756#pragma unroll
1757    for (int c = 0; c < NC; ++c) {
1758        if (EXACT_N || c < n) {
1759            s[c] = __fadd_rn(s[c], s16[c]);
1760#pragma unroll
1761            for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
1762        }
1763    }
1764}
1765
1766// 8-lane sub-warp row dot for K = nb * ipb == 160 (the APR trellis gate/up types at n_embd 2560): 4 rows per warp (32 per
1767// 256-thread block).  Bitwise row_dot_multi's tree: its lane L sums the calls k = L, L + 32, ... L + 128 in that order, then
1768// warp_sum adds lane + 16, then + 8, then 4, 2, 1.  Here lane t of 8 keeps the four sums of the lanes t, t + 8, t + 16 and
1769// t + 24 (v = 0..3) and adds them (v0 + v2) + (v1 + v3), which is what the first two steps give; 3 steps follow.  A trellis
1770// block is 8 lanes, so lane t always takes lane t of block v + 4 j: its bit offsets are the same for all 20 calls.
1771template<int TY, int NC, bool EXACT_N = false, bool STAGE_GRID = false>
1772__device__ __forceinline__ void row_dot_160_sub8(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n,
1773                                                 int t, float (&s)[NC], const uint32_t* __restrict__ s_grid = nullptr) {
1774    using F = Fmt<TY>;
1775    using S = Split<TY>;
1776    static_assert(F::ipb == 8 && F::step == 4, "one trellis block is 8 lanes of 4 steps");
1777    float p[4][NC];
1778#pragma unroll
1779    for (int v = 0; v < 4; ++v)
1780#pragma unroll
1781        for (int c = 0; c < NC; ++c) p[v][c] = 0.0f;
1782#pragma unroll
1783    for (int j = 0; j < 5; ++j) {
1784#pragma unroll
1785        for (int v = 0; v < 4; ++v) {
1786            const int kbx = v + 4 * j, iqs = F::step * t;
1787            const typename S::W w = S::template load<STAGE_GRID>(row, kbx, iqs, s_grid);
1788#pragma unroll
1789            for (int c = 0; c < NC; ++c)
1790                if (EXACT_N || c < n) p[v][c] += S::apply(w, x + off[c] + kbx * (F::qk / 32), iqs);
1791        }
1792    }
1793#pragma unroll
1794    for (int c = 0; c < NC; ++c) {
1795        if (EXACT_N || c < n) {
1796            s[c] = __fadd_rn(__fadd_rn(p[0][c], p[2][c]), __fadd_rn(p[1][c], p[3][c]));
1797#pragma unroll
1798            for (int o = 4; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
1799        }
1800    }
1801}
1802
1803// 147-verify: row_dot_80_sub16 for two rows (a gate row and its up row) at once, both rows' weight loads of a step issued
1804// before either is applied; each row's sums are row_dot_80_sub16's, in its order (the same bits).
1805template<int TY, int NC, bool EXACT_N = false, bool STAGE_GRID = false>
1806__device__ __forceinline__ void row_dot2_80_sub16(const uint8_t* ra, const uint8_t* rb, const block_q8_1* x, const int (&off)[NC],
1807                                                  int n, int t, float (&sa)[NC], float (&sb)[NC],
1808                                                  const uint32_t* __restrict__ s_grid = nullptr) {
1809    using F = Fmt<TY>;
1810    using S = Split<TY>;
1811#pragma unroll
1812    for (int c = 0; c < NC; ++c) { sa[c] = 0.0f; sb[c] = 0.0f; }
1813    for (int k = t; k < 80; k += 32) {
1814        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1815        const typename S::W wa = S::template load<STAGE_GRID>(ra, kbx, iqs, s_grid);
1816        const typename S::W wb = S::template load<STAGE_GRID>(rb, kbx, iqs, s_grid);
1817#pragma unroll
1818        for (int c = 0; c < NC; ++c)
1819            if (EXACT_N || c < n) {
1820                sa[c] += S::apply(wa, x + off[c] + kbx * (F::qk / 32), iqs);
1821                sb[c] += S::apply(wb, x + off[c] + kbx * (F::qk / 32), iqs);
1822            }
1823    }
1824    float a16[NC], b16[NC];
1825#pragma unroll
1826    for (int c = 0; c < NC; ++c) { a16[c] = 0.0f; b16[c] = 0.0f; }
1827    for (int k = t + 16; k < 64; k += 32) {
1828        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
1829        const typename S::W wa = S::template load<STAGE_GRID>(ra, kbx, iqs, s_grid);
1830        const typename S::W wb = S::template load<STAGE_GRID>(rb, kbx, iqs, s_grid);
1831#pragma unroll
1832        for (int c = 0; c < NC; ++c)
1833            if (EXACT_N || c < n) {
1834                a16[c] += S::apply(wa, x + off[c] + kbx * (F::qk / 32), iqs);
1835                b16[c] += S::apply(wb, x + off[c] + kbx * (F::qk / 32), iqs);
1836            }
1837    }
1838#pragma unroll
1839    for (int c = 0; c < NC; ++c) {
1840        if (EXACT_N || c < n) {
1841            sa[c] = __fadd_rn(sa[c], a16[c]);
1842            sb[c] = __fadd_rn(sb[c], b16[c]);
1843#pragma unroll
1844            for (int o = 8; o > 0; o >>= 1) {
1845                sa[c] += __shfl_xor_sync(0xffffffffu, sa[c], o);
1846                sb[c] += __shfl_xor_sync(0xffffffffu, sb[c], o);
1847            }
1848        }
1849    }
1850}
1851
1852// The sign-mask tables that follow the codebook words in a staged IQ3_XXS / IQ3_S table (see stage_iq_grid): the byte
1853// masks of every 7-bit sign field (IQ3_XXS, 2 x 128 words at +256) and of a sign byte's bits 0-3 and 4-7 (IQ3_S, 2 x 256
1854// words at +512).  Split<18>::load<true> and Split<21>::load<true> read them, so every kernel that stages these two
1855// codebooks (the default kernels through stage_iq_grid, the STRATA_EXPDEC window kernels through EdGrid) fills them too.
1856__device__ __forceinline__ void stage_iq3xxs_masks(uint32_t* s_buf, int tid, int nthreads) {
1857    for (int u = tid; u < 128; u += nthreads) {
1858        const uint32_t s = (uint32_t) u | ((__popc((uint32_t) u) & 1u) << 7);   // 8th sign = parity of the 7
1859        uint32_t ml = 0, mh = 0;
1860#pragma unroll
1861        for (int i = 0; i < 4; ++i) {
1862            ml |= ((s >> i) & 1u) * (0xffu << (8 * i));
1863            mh |= ((s >> (4 + i)) & 1u) * (0xffu << (8 * i));
1864        }
1865        s_buf[256 + u] = ml;
1866        s_buf[384 + u] = mh;
1867    }
1868}
1869__device__ __forceinline__ void stage_iq3s_masks(uint32_t* s_buf, int tid, int nthreads) {
1870    for (int u = tid; u < 256; u += nthreads) {
1871        uint32_t ml = 0, mh = 0;
1872#pragma unroll
1873        for (int i = 0; i < 4; ++i) {
1874            ml |= (((uint32_t) u >> i) & 1u) * (0xffu << (8 * i));
1875            mh |= (((uint32_t) u >> (4 + i)) & 1u) * (0xffu << (8 * i));
1876        }
1877        s_buf[512 + u] = ml;
1878        s_buf[768 + u] = mh;
1879    }
1880}
1881
1882template<int TY, bool STAGE_GRID = kStageIqGrid<TY>>
1883__device__ __forceinline__ const uint32_t* stage_iq_grid(uint32_t* s_buf, int tid, int nthreads) {
1884    if constexpr (!STAGE_GRID) {
1885        return nullptr;
1886    } else if constexpr (TY == 16) {
1887        uint2* dst = (uint2*) s_buf;
1888        const uint2* src = (const uint2*) iq2xxs_grid;
1889        for (int i = tid; i < 256; i += nthreads) dst[i] = src[i];
1890        iq_sync_lds();
1891        return s_buf;
1892    } else if constexpr (TY == 17) {
1893        uint2* dst = (uint2*) s_buf;
1894        const uint2* src = (const uint2*) iq2xs_grid;
1895        for (int i = tid; i < 512; i += nthreads) dst[i] = src[i];
1896        iq_sync_lds();
1897        return s_buf;
1898    } else if constexpr (TY == 22) {
1899        uint2* dst = (uint2*) s_buf;
1900        const uint2* src = (const uint2*) iq2s_grid;
1901        for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i];
1902        iq_sync_lds();
1903        return s_buf;
1904    } else if constexpr (TY == 29) {
1905        uint2* dst = (uint2*) s_buf;
1906        const uint2* src = (const uint2*) iq1s_grid_gpu;
1907        for (int i = tid; i < 1024; i += nthreads) dst[i] = src[i];
1908        iq_sync_lds();
1909        return s_buf;
1910    } else if constexpr (TY == 18) {
1911        // 256 codebook words, then two 128-word tables of the per-byte sign masks (signs 0-3, signs 4-7).  A
1912        // mask depends only on the 7 bits it is unpacked from, and iq3xxs_grid's bytes are all >= 4, so the
1913        // consumer applies it as (g ^ mask) + (mask & 0x01010101): a negate per set byte, with no carry into
1914        // the next.  One pass per block replaces the per-lookup unpack_ksigns / __vcmpne4 / __vsub4 chain.
1915        // Ported from shinbunbun/llama-cpp-p100-patches (MIT), patches 29 `mmvq-iq3xxs-grid-smem` and 30
1916        // `mmvq-ksigns-smem`, measured there on a Tesla P100 (sm_60).
1917        for (int i = tid; i < 256; i += nthreads) s_buf[i] = iq3xxs_grid[i];
1918        stage_iq3xxs_masks(s_buf, tid, nthreads);
1919        iq_sync_lds();
1920        return s_buf;
1921    } else if constexpr (kTqType<TY>) {
1922        // the trellis types' int8 codebook: 2048 u16 (4 KB), read by 8 random lookups per 16 weights
1923        const uint32_t* src = (const uint32_t*) tq_lut_i8;
1924        for (int i = tid; i < 1024; i += nthreads) s_buf[i] = src[i];
1925        __syncthreads();
1926        return s_buf;
1927    } else if constexpr (TY == 21) {
1928        // 512 codebook words, then two 256-word tables: the byte masks of a sign byte's bits 0-3 and of its bits
1929        // 4-7 (IQ3_S stores one sign byte per 8 values).  As for IQ3_XXS, one pass per block replaces the
1930        // per-lookup __vcmpne4 / __vsub4 chain, and the codebook reads leave global memory.
1931        for (int i = tid; i < 512; i += nthreads) s_buf[i] = iq3s_grid[i];
1932        stage_iq3s_masks(s_buf, tid, nthreads);
1933        iq_sync_lds();
1934        return s_buf;
1935    } else {
1936        return nullptr;
1937    }
1938}
1939
1940template<int TY, bool STAGE_GRID = kStageIqGrid<TY>>
1941struct IqGridWords {
1942    static constexpr int value = !STAGE_GRID ? 4 : (TY == 22 || TY == 29) ? 2048 : (TY == 17 || TY == 21 || kTqType<TY>) ? 1024 : (TY == 16 || TY == 18) ? 512 : 4;
1943};
1944
1945// mmvq_kernel with the columns taken NC at a time.  After warp_sum every lane holds the same sum, so lane c stores
1946// column c.
1947// #778: `__shared__ alignas(16)` does not compile for gfx1030 (HIP); the attribute after the declarator does, but nvcc
1948// with MSVC as host does not take it.  Same layout either way.
1949#if defined(__HIPCC__)
1950#define STRATA_SHARED_ALIGN16_U32(name, ...) __shared__ uint32_t name[__VA_ARGS__] __attribute__((aligned(16)))
1951#else
1952#define STRATA_SHARED_ALIGN16_U32(name, ...) __shared__ alignas(16) uint32_t name[__VA_ARGS__]
1953#endif
1954template<int TY, int NC, bool STAGE_GRID = kStageIqGrid<TY>, bool EXACT_N = false>
1955__global__ void __launch_bounds__(128) mmvq_multi_kernel(const uint8_t* __restrict__ w, size_t row_bytes,
1956                                                         const block_q8_1* __restrict__ x, float* __restrict__ y,
1957                                                         int n_in, int n_out, int ncols) {
1958    STRATA_SHARED_ALIGN16_U32(s_grid_buf, IqGridWords<TY, STAGE_GRID>::value);
1959    const uint32_t* s_grid = stage_iq_grid<TY, STAGE_GRID>(s_grid_buf, threadIdx.y * 32 + threadIdx.x, 128);
1960    const int row = blockIdx.x * 4 + threadIdx.y;
1961    if (row >= n_out) return;
1962    const int lane = threadIdx.x;
1963    const int nb = n_in / Fmt<TY>::qk, xb = n_in / 32;
1964    const uint8_t* wr = w + (size_t) row * row_bytes;
1965    if constexpr (EXACT_N) {
1966        int off[NC];
1967#pragma unroll
1968        for (int c = 0; c < NC; ++c) off[c] = c * xb;
1969        float s[NC];
1970        row_dot_multi<TY, NC, true, STAGE_GRID>(wr, x, off, NC, nb, lane, s, s_grid);
1971#pragma unroll
1972        for (int c = 0; c < NC; ++c)
1973            if (lane == c) y[(size_t) c * n_out + row] = s[c];
1974    } else {
1975        for (int c0 = 0; c0 < ncols; c0 += NC) {
1976            const int n = min(NC, ncols - c0);
1977            int off[NC];
1978#pragma unroll
1979            for (int c = 0; c < NC; ++c) off[c] = (c0 + min(c, n - 1)) * xb;
1980            float s[NC];
1981            row_dot_multi<TY, NC, false, STAGE_GRID>(wr, x, off, n, nb, lane, s, s_grid);
1982#pragma unroll
1983            for (int c = 0; c < NC; ++c)
1984                if (c < n && lane == c) y[(size_t) (c0 + c) * n_out + row] = s[c];
1985        }
1986    }
1987}
1988
1989// ---------------------------------------------------------------- grouped native experts
1990constexpr int GU_ROWS = 8;     // rows per block (one warp each)
1991
1992// Group g is computed by block row g % gridDim.y: rows y, y + gridDim.y, ... < *n_groups.  The callers size the
1993// launch for the most groups a call can have (cap: every entry its own expert), but the count is only known on the
1994// device, and a verify window's PCIe call usually has no group at all: with one block row per possible group every
1995// unused one was cap x (2 n_ff / 8 + n_embd / 8) blocks that started only to return.  A smaller gridDim.y strides
1996// instead.  Each group's rows are computed by the same warp code in the same order either way, so the results do
1997// not depend on gridDim.y (gridDim.y = cap_groups is the one-row-per-group launch).
1998template<int TG>
1999__global__ void __launch_bounds__(256) native_gu_kernel(const unsigned long long* __restrict__ grp_ptr,
2000                                                        const int32_t* __restrict__ grp_start,
2001                                                        const int32_t* __restrict__ n_groups,
2002                                                        const int32_t* __restrict__ ent_tok,
2003                                                        const block_q8_1* __restrict__ xq, NativeExpertLayout L,
2004                                                        float* __restrict__ gate, float* __restrict__ up) {
2005    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
2006    const int row = blockIdx.x * GU_ROWS + warp;             // 0 .. 2*n_ff
2007    if (row >= 2 * L.n_ff) return;
2008    const bool is_up = row >= L.n_ff;
2009    const int r = is_up ? row - (int) L.n_ff : row;
2010    const size_t off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
2011    const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
2012    const int ng = *n_groups;
2013    for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2014        const uint8_t* blob = (const uint8_t*) grp_ptr[g];
2015        const uint8_t* wr = blob + off;
2016        // NVFP4: the expert's global scales from the blob's tail; s_down goes on the down output (native_down_kernel):
2017        // folded into up it left the hidden near 1e-5, whose q8_1 block scale is an FP16 subnormal
2018        float scale = 1.0f;
2019        if (L.tail_off) {
2020            const float* tail = (const float*) (blob + L.tail_off);
2021            scale = is_up ? tail[1] : tail[0];
2022        }
2023        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2024        for (int e = e0; e < e1; ++e) {
2025            const float s = row_dot<TG>(wr, xq + (size_t) ent_tok[e] * xb, nb, lane);
2026            if (lane == 0) (is_up ? up : gate)[(size_t) e * L.n_ff + r] = s * scale;
2027        }
2028    }
2029}
2030
2031// native_gu_kernel with the group's entries taken GRP_NC at a time, each weight part decoded once per pass.
2032// A group has at most one entry per token of the window (kVerifyMaxT = 8; setup writes --spec 4, and a split window
2033// has halves of <= 4), so 4 takes such windows in one pass; 8 would take ~64-80 registers against ~48 (ptxas -v).
2034constexpr int GRP_NC = 4;
2035
2036template<int TG, bool STAGE_GRID = kStageIqGrid<TG>, bool SUB16 = true>
2037__global__ void __launch_bounds__(256) native_gu_multi_kernel(const unsigned long long* __restrict__ grp_ptr,
2038                                                              const int32_t* __restrict__ grp_start,
2039                                                              const int32_t* __restrict__ n_groups,
2040                                                              const int32_t* __restrict__ ent_tok,
2041                                                              const block_q8_1* __restrict__ xq, NativeExpertLayout L,
2042                                                              float* __restrict__ gate, float* __restrict__ up) {
2043    const int ng = *n_groups;
2044    if (blockIdx.y >= ng) return;
2045    STRATA_SHARED_ALIGN16_U32(s_grid_buf, IqGridWords<TG, STAGE_GRID>::value);
2046    const uint32_t* s_grid = stage_iq_grid<TG, STAGE_GRID>(s_grid_buf, threadIdx.x, 256);
2047    const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
2048    if constexpr (SUB16 && (TG == 144 || TG == 145)) {
2049        if (nb * Fmt<TG>::ipb == 160) {   // the trellis rows (tq_sub8_on): 160 dots at n_embd 2560, 8 lanes a row
2050            const int subwarp = threadIdx.x >> 3, t = threadIdx.x & 7;
2051            const int row = blockIdx.x * 32 + subwarp;            // 0 .. 2*n_ff
2052            if (row >= 2 * L.n_ff) return;
2053            const bool is_up = row >= L.n_ff;
2054            const int r = is_up ? row - (int) L.n_ff : row;
2055            const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
2056            float* dst = is_up ? up : gate;
2057            for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2058                const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2059                const float sc = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[is_up ? 1 : 0] : 1.0f;
2060                const int e0 = grp_start[g], e1 = grp_start[g + 1];
2061                for (int e = e0; e < e1; e += GRP_NC) {
2062                    const int n = min(GRP_NC, e1 - e);
2063                    if (n == 1) {
2064                        const int off1[1] = { ent_tok[e] * 80 };
2065                        float s1[1];
2066                        row_dot_160_sub8<TG, 1, true, STAGE_GRID>(wr, xq, off1, 1, t, s1, s_grid);
2067                        if (t == 0) dst[(size_t) e * L.n_ff + r] = s1[0] * sc;
2068                    } else if (n == 2) {
2069                        const int off2[2] = { ent_tok[e] * 80, ent_tok[e + 1] * 80 };
2070                        float s2[2];
2071                        row_dot_160_sub8<TG, 2, true, STAGE_GRID>(wr, xq, off2, 2, t, s2, s_grid);
2072                        if (t < 2) dst[(size_t) (e + t) * L.n_ff + r] = s2[t] * sc;
2073                    } else if (n == 3) {
2074                        const int off3[3] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80 };
2075                        float s3[3];
2076                        row_dot_160_sub8<TG, 3, true, STAGE_GRID>(wr, xq, off3, 3, t, s3, s_grid);
2077                        if (t < 3) dst[(size_t) (e + t) * L.n_ff + r] = s3[t] * sc;
2078                    } else {
2079                        const int off4[4] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80, ent_tok[e + 3] * 80 };
2080                        float s4[4];
2081                        row_dot_160_sub8<TG, 4, true, STAGE_GRID>(wr, xq, off4, 4, t, s4, s_grid);
2082                        if (t < 4) dst[(size_t) (e + t) * L.n_ff + r] = s4[t] * sc;
2083                    }
2084                }
2085            }
2086            return;
2087        }
2088    } else if constexpr (SUB16) {
2089        if (xb == 80 && nb * Fmt<TG>::ipb == 80) {   // row_dot_80_sub16 covers exactly 80 dots (not the 128-value TQ blocks)
2090            const int subwarp = threadIdx.x >> 4, t = threadIdx.x & 15;
2091            const int row = blockIdx.x * 16 + subwarp;            // 0 .. 2*n_ff
2092            if (row >= 2 * L.n_ff) return;
2093            const bool is_up = row >= L.n_ff;
2094            const int r = is_up ? row - (int) L.n_ff : row;
2095            const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
2096            float* dst = is_up ? up : gate;
2097            for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2098                const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2099                // NVFP4: the expert's s_gate / s_up on the FP32 output, as native_gu_kernel (1 otherwise: exact)
2100                const float sc = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[is_up ? 1 : 0] : 1.0f;
2101                const int e0 = grp_start[g], e1 = grp_start[g + 1];
2102                for (int e = e0; e < e1; e += GRP_NC) {
2103                    const int n = min(GRP_NC, e1 - e);
2104                    if (n == 1) {
2105                        const int off1[1] = { ent_tok[e] * 80 };
2106                        float s1[1];
2107                        row_dot_80_sub16<TG, 1, true, STAGE_GRID>(wr, xq, off1, 1, t, s1, s_grid);
2108                        if (t == 0) dst[(size_t) e * L.n_ff + r] = s1[0] * sc;
2109                    } else if (n == 2) {
2110                        const int off2[2] = { ent_tok[e] * 80, ent_tok[e + 1] * 80 };
2111                        float s2[2];
2112                        row_dot_80_sub16<TG, 2, true, STAGE_GRID>(wr, xq, off2, 2, t, s2, s_grid);
2113                        if (t < 2) dst[(size_t) (e + t) * L.n_ff + r] = s2[t] * sc;
2114                    } else if (n == 3) {
2115                        const int off3[3] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80 };
2116                        float s3[3];
2117                        row_dot_80_sub16<TG, 3, true, STAGE_GRID>(wr, xq, off3, 3, t, s3, s_grid);
2118                        if (t < 3) dst[(size_t) (e + t) * L.n_ff + r] = s3[t] * sc;
2119                    } else {
2120                        const int off4[4] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80, ent_tok[e + 3] * 80 };
2121                        float s4[4];
2122                        row_dot_80_sub16<TG, 4, true, STAGE_GRID>(wr, xq, off4, 4, t, s4, s_grid);
2123                        if (t < 4) dst[(size_t) (e + t) * L.n_ff + r] = s4[t] * sc;
2124                    }
2125                }
2126            }
2127            return;
2128        }
2129    }
2130    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
2131    // cc 6.0 trellis experts (staged codebook): a block takes the row chunks blockIdx.x, + gridDim.x, ... so the 4 KB
2132    // codebook staging above is paid once for several chunks (the launch shrinks the grid to match); every other
2133    // launch has one chunk per block and this is the single pass it always was
2134    constexpr bool kRowLoop = kTqType<TG> && STAGE_GRID;
2135    if constexpr (kRowLoop) {
2136        // cc 6.0 trellis gate/up: the group's entries (GRP_NC at a time) are copied once to shared memory by the block, and the
2137        // block's row chunks all apply them from there: the apply reads each entry's q8_1 block with five 4-byte loads per
2138        // lane, which from global memory is what an extra entry costs on this card.  The same words, the same operations
2139        // in the same order (row_dot_multi), so the same sums.
2140        if (xb <= 80) {
2141            __shared__ uint32_t s_x[GRP_NC * 80 * 9];
2142            const block_q8_1* xs = reinterpret_cast<const block_q8_1*>(s_x);
2143            for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2144                const uint8_t* gp = (const uint8_t*) grp_ptr[g];
2145                const int e0 = grp_start[g], e1 = grp_start[g + 1];
2146                for (int e = e0; e < e1; e += GRP_NC) {
2147                    const int n = min(GRP_NC, e1 - e);
2148                    __syncthreads();
2149                    for (int i = 0; i < n; ++i) {
2150                        const uint32_t* src = reinterpret_cast<const uint32_t*>(xq + (size_t) ent_tok[e + i] * xb);
2151                        for (int j = threadIdx.x; j < xb * 9; j += 256) s_x[i * xb * 9 + j] = src[j];
2152                    }
2153                    __syncthreads();
2154                    for (int rc = blockIdx.x; rc * GU_ROWS < 2 * L.n_ff; rc += gridDim.x) {
2155                        const int row = rc * GU_ROWS + warp;
2156                        if (row >= 2 * L.n_ff) continue;
2157                        const bool is_up = row >= L.n_ff;
2158                        const int r = is_up ? row - (int) L.n_ff : row;
2159                        const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
2160                        float* dst = is_up ? up : gate;
2161                        const uint8_t* wr = gp + w_off;
2162                        const float sc = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[is_up ? 1 : 0] : 1.0f;
2163                        if (n == 1) {
2164                            const int off1[1] = { 0 };
2165                            float s1[1];
2166                            row_dot_multi<TG, 1, true, STAGE_GRID>(wr, xs, off1, 1, nb, lane, s1, s_grid);
2167                            if (lane == 0) dst[(size_t) e * L.n_ff + r] = s1[0] * sc;
2168                        } else if (n == 2) {
2169                            const int off2[2] = { 0, xb };
2170                            float s2[2];
2171                            row_dot_multi<TG, 2, true, STAGE_GRID>(wr, xs, off2, 2, nb, lane, s2, s_grid);
2172                            if (lane < 2) dst[(size_t) (e + lane) * L.n_ff + r] = s2[lane] * sc;
2173                        } else if (n == 3) {
2174                            const int off3[3] = { 0, xb, 2 * xb };
2175                            float s3[3];
2176                            row_dot_multi<TG, 3, true, STAGE_GRID>(wr, xs, off3, 3, nb, lane, s3, s_grid);
2177                            if (lane < 3) dst[(size_t) (e + lane) * L.n_ff + r] = s3[lane] * sc;
2178                        } else {
2179                            const int off4[4] = { 0, xb, 2 * xb, 3 * xb };
2180                            float s4[4];
2181                            row_dot_multi<TG, 4, true, STAGE_GRID>(wr, xs, off4, 4, nb, lane, s4, s_grid);
2182                            if (lane < 4) dst[(size_t) (e + lane) * L.n_ff + r] = s4[lane] * sc;
2183                        }
2184                    }
2185                }
2186            }
2187            return;
2188        }
2189    }
2190    for (int rc = blockIdx.x; ; rc += gridDim.x) {
2191    const int row = rc * GU_ROWS + warp;             // 0 .. 2*n_ff
2192    if (row >= 2 * L.n_ff) break;
2193    const bool is_up = row >= L.n_ff;
2194    const int r = is_up ? row - (int) L.n_ff : row;
2195    const size_t w_off = (is_up ? L.up_off : 0) + (size_t) r * L.gu_row;
2196    float* dst = is_up ? up : gate;
2197    for (int g = blockIdx.y; g < ng; g += gridDim.y) {   // the group stride, as native_gu_kernel
2198        const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2199                // NVFP4: the expert's s_gate / s_up on the FP32 output, as native_gu_kernel (1 otherwise: exact)
2200                const float sc = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[is_up ? 1 : 0] : 1.0f;
2201        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2202        for (int e = e0; e < e1; e += GRP_NC) {
2203            const int n = min(GRP_NC, e1 - e);
2204            if (n == 1) {
2205                const int off1[1] = { ent_tok[e] * xb };
2206                float s1[1];
2207                row_dot_multi<TG, 1, true, STAGE_GRID>(wr, xq, off1, 1, nb, lane, s1, s_grid);
2208                if (lane == 0) dst[(size_t) e * L.n_ff + r] = s1[0] * sc;
2209            } else if (n == 2) {
2210                const int off2[2] = { ent_tok[e] * xb, ent_tok[e + 1] * xb };
2211                float s2[2];
2212                row_dot_multi<TG, 2, true, STAGE_GRID>(wr, xq, off2, 2, nb, lane, s2, s_grid);
2213                if (lane < 2) dst[(size_t) (e + lane) * L.n_ff + r] = s2[lane] * sc;
2214            } else if (n == 3) {
2215                const int off3[3] = { ent_tok[e] * xb, ent_tok[e + 1] * xb, ent_tok[e + 2] * xb };
2216                float s3[3];
2217                row_dot_multi<TG, 3, true, STAGE_GRID>(wr, xq, off3, 3, nb, lane, s3, s_grid);
2218                if (lane < 3) dst[(size_t) (e + lane) * L.n_ff + r] = s3[lane] * sc;
2219            } else {
2220                const int off4[4] = { ent_tok[e] * xb, ent_tok[e + 1] * xb, ent_tok[e + 2] * xb, ent_tok[e + 3] * xb };
2221                float s4[4];
2222                row_dot_multi<TG, 4, true, STAGE_GRID>(wr, xq, off4, 4, nb, lane, s4, s_grid);
2223                if (lane < 4) dst[(size_t) (e + lane) * L.n_ff + r] = s4[lane] * sc;
2224            }
2225        }
2226    }
2227    if constexpr (!kRowLoop) break;
2228    }
2229}
2230
2231// APR (prism.hadamard): y = H_block (signs * x) per block of each row, block = blockDim.x (a power of two <= 1024),
2232// one thread block per (row block, row).  The butterflies are the CPU's (hadamard.cpp) in the same order, so the
2233// rotated values are the same floats.
2234template<typename T> __device__ __forceinline__ float ld_f(const T* p) { return (float) *p; }
2235template<> __device__ __forceinline__ float ld_f<__half>(const __half* p) { return __half2float(*p); }
2236template<typename T> __device__ __forceinline__ void st_f(T* p, float v) { *p = v; }
2237template<> __device__ __forceinline__ void st_f<__half>(__half* p, float v) { *p = __float2half(v); }
2238template<typename T>
2239__global__ void hadamard_rows_kernel(const T* __restrict__ x, T* __restrict__ y, int64_t width,
2240                                     const float* __restrict__ signs, float scale) {
2241    extern __shared__ float hbuf[];
2242    const int n = blockDim.x, i = threadIdx.x;
2243    const int64_t col = (int64_t) blockIdx.x * n + i, at = (int64_t) blockIdx.y * width + col;
2244    float v = ld_f<T>(x + at);
2245    if (signs) v *= signs[col];
2246    hbuf[i] = v;
2247    for (int len = 1; len < n; len <<= 1) {
2248        __syncthreads();
2249        if ((i & len) == 0) {
2250            const float a = hbuf[i], c = hbuf[i + len];
2251            hbuf[i] = a + c;
2252            hbuf[i + len] = a - c;
2253        }
2254    }
2255    __syncthreads();
2256    st_f<T>(y + at, hbuf[i] * scale);
2257}
2258
2259__global__ void swiglu_entries_kernel(const float* __restrict__ gate, const float* __restrict__ up, float* __restrict__ h,
2260                                      long long n) {
2261    const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;
2262    if (i >= n) return;
2263    const float g = gate[i];
2264    h[i] = (g / (1.0f + __expf(-g))) * up[i];
2265}
2266
2267template<int TD>
2268__global__ void __launch_bounds__(256) native_down_kernel(const unsigned long long* __restrict__ grp_ptr,
2269                                                          const int32_t* __restrict__ grp_start,
2270                                                          const int32_t* __restrict__ n_groups,
2271                                                          const int32_t* __restrict__ ent_dst,
2272                                                          const block_q8_1* __restrict__ hq, NativeExpertLayout L,
2273                                                          float* __restrict__ out) {
2274    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
2275    const int r = blockIdx.x * 8 + warp;
2276    if (r >= L.n_embd) return;
2277    const size_t off = L.down_off + (size_t) r * L.d_row;
2278    const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
2279    const int ng = *n_groups;
2280    for (int g = blockIdx.y; g < ng; g += gridDim.y) {   // as native_gu_kernel
2281        const uint8_t* blob = (const uint8_t*) grp_ptr[g];
2282        const uint8_t* wr = blob + off;
2283        const float sd = L.tail_off ? ((const float*) (blob + L.tail_off))[2] : 1.0f;   // NVFP4: s_down
2284        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2285        for (int e = e0; e < e1; ++e) {
2286            const float s = row_dot<TD>(wr, hq + (size_t) e * hb, nb, lane);
2287            if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s * sd;
2288        }
2289    }
2290}
2291
2292// the 8-lane down rows: IQ4_NL's K = 40, NVFP4's K = 20
2293template<int TD, int NC, bool EXACT_N = false, bool STAGE_GRID = false>
2294__device__ __forceinline__ void row_dot_sub8(const uint8_t* row, const block_q8_1* x, const int (&off)[NC], int n, int t,
2295                                             float (&s)[NC], const uint32_t* __restrict__ s_grid = nullptr) {
2296    if constexpr (TD == 40) row_dot_20_sub8<TD, NC, EXACT_N>(row, x, off, n, t, s);
2297    else row_dot_40_sub8<TD, NC, EXACT_N, STAGE_GRID>(row, x, off, n, t, s, s_grid);
2298}
2299
2300// native_down_kernel with the entries taken GRP_NC at a time
2301template<int TD, bool SUB_DOWN = true, bool STAGE_TQ = false>
2302__global__ void __launch_bounds__(256) native_down_multi_kernel(const unsigned long long* __restrict__ grp_ptr,
2303                                                                const int32_t* __restrict__ grp_start,
2304                                                                const int32_t* __restrict__ n_groups,
2305                                                                const int32_t* __restrict__ ent_dst,
2306                                                                const block_q8_1* __restrict__ hq, NativeExpertLayout L,
2307                                                                float* __restrict__ out) {
2308    const int ng = *n_groups;
2309    if (blockIdx.y >= ng) return;
2310    STRATA_SHARED_ALIGN16_U32(s_grid_buf, IqGridWords<TD, STAGE_TQ>::value);   // the trellis codebook on a cc 6.0 card, else 4 unused words
2311    const uint32_t* s_grid = stage_iq_grid<TD, STAGE_TQ>(s_grid_buf, threadIdx.x, 256);
2312    __shared__ uint32_t s_hq_buf[GRP_NC * 20 * 9];
2313    const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
2314    if constexpr (SUB_DOWN && kTqType<TD> && STAGE_TQ) {
2315        // cc 6.0 trellis down rows (K = 40 dots at n_ff 640, the IQ4_NL row shape): 8 lanes a row, 32 rows a chunk, and a
2316        // block takes the chunks blockIdx.x, + gridDim.x, ... of one staged codebook and one staged set of activations
2317        // (the launch shrinks the grid to match).  The sums are row_dot_40_sub8's, as the IQ4_NL rows.
2318        if (hb == 20) {
2319            const int t = threadIdx.x & 7;
2320            const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
2321            for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2322                const uint8_t* gp = (const uint8_t*) grp_ptr[g];
2323                const float sd = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[2] : 1.0f;
2324                const int e0 = grp_start[g], e1 = grp_start[g + 1];
2325                for (int e = e0; e < e1; e += GRP_NC) {
2326                    const int n = min(GRP_NC, e1 - e);
2327                    const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);
2328                    const int words = n * (20 * 9);
2329                    __syncthreads();
2330                    for (int i = threadIdx.x; i < words; i += 256) s_hq_buf[i] = src[i];
2331                    __syncthreads();
2332                    for (int rc = blockIdx.x; rc * 32 < L.n_embd; rc += gridDim.x) {
2333                        const int r = rc * 32 + (threadIdx.x >> 3);
2334                        if (r >= L.n_embd) continue;
2335                        const uint8_t* wr = gp + L.down_off + (size_t) r * L.d_row;
2336                        if (n == 1) {
2337                            const int off1[1] = { 0 };
2338                            float s1[1];
2339                            row_dot_sub8<TD, 1, true, STAGE_TQ>(wr, s_hq, off1, 1, t, s1, s_grid);
2340                            if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0] * sd;
2341                        } else if (n == 2) {
2342                            const int off2[2] = { 0, 20 };
2343                            float s2[2];
2344                            row_dot_sub8<TD, 2, true, STAGE_TQ>(wr, s_hq, off2, 2, t, s2, s_grid);
2345                            if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t] * sd;
2346                        } else if (n == 3) {
2347                            const int off3[3] = { 0, 20, 40 };
2348                            float s3[3];
2349                            row_dot_sub8<TD, 3, true, STAGE_TQ>(wr, s_hq, off3, 3, t, s3, s_grid);
2350                            if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t] * sd;
2351                        } else {
2352                            const int off4[4] = { 0, 20, 40, 60 };
2353                            float s4[4];
2354                            row_dot_sub8<TD, 4, true, STAGE_TQ>(wr, s_hq, off4, 4, t, s4, s_grid);
2355                            if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t] * sd;
2356                        }
2357                    }
2358                }
2359            }
2360            return;
2361        }
2362    } else
2363    if constexpr (SUB_DOWN && (TD == 20 || TD == 40)) {   // IQ4_NL (K 40) and NVFP4 (K 20): 8-lane rows
2364        if (hb == 20) {
2365            const int r = blockIdx.x * 32 + (threadIdx.x >> 3);
2366            const int t = threadIdx.x & 7;
2367            const bool valid_r = (r < L.n_embd);
2368            const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;
2369            const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
2370            for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2371                const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2372                const float sd = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[2] : 1.0f;   // NVFP4: s_down
2373                const int e0 = grp_start[g], e1 = grp_start[g + 1];
2374                for (int e = e0; e < e1; e += GRP_NC) {
2375                    const int n = min(GRP_NC, e1 - e);
2376                    const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);
2377                    const int words = n * (20 * 9);
2378                    if (g > (int) blockIdx.y || e > e0) iq_sync_lds();
2379                    for (int i = threadIdx.x; i < words; i += 256) s_hq_buf[i] = src[i];
2380                    iq_sync_lds();
2381                    if (valid_r) {
2382                        if (n == 1) {
2383                            const int off1[1] = { 0 };
2384                            float s1[1];
2385                            row_dot_sub8<TD, 1, true, STAGE_TQ>(wr, s_hq, off1, 1, t, s1, s_grid);
2386                            if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0] * sd;
2387                        } else if (n == 2) {
2388                            const int off2[2] = { 0, 20 };
2389                            float s2[2];
2390                            row_dot_sub8<TD, 2, true, STAGE_TQ>(wr, s_hq, off2, 2, t, s2, s_grid);
2391                            if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t] * sd;
2392                        } else if (n == 3) {
2393                            const int off3[3] = { 0, 20, 40 };
2394                            float s3[3];
2395                            row_dot_sub8<TD, 3, true, STAGE_TQ>(wr, s_hq, off3, 3, t, s3, s_grid);
2396                            if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t] * sd;
2397                        } else {
2398                            const int off4[4] = { 0, 20, 40, 60 };
2399                            float s4[4];
2400                            row_dot_sub8<TD, 4, true, STAGE_TQ>(wr, s_hq, off4, 4, t, s4, s_grid);
2401                            if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t] * sd;
2402                        }
2403                    }
2404                }
2405            }
2406            return;
2407        }
2408    } else if constexpr (SUB_DOWN && TD == 42) {
2409        if (hb == 20) {
2410            const int r = blockIdx.x * 16 + (threadIdx.x >> 4);
2411            const int t = threadIdx.x & 15;
2412            const bool valid_r = (r < L.n_embd);
2413            const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;
2414            const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
2415            for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2416                const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2417                const float sd = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[2] : 1.0f;   // NVFP4: s_down
2418                const int e0 = grp_start[g], e1 = grp_start[g + 1];
2419                for (int e = e0; e < e1; e += GRP_NC) {
2420                    const int n = min(GRP_NC, e1 - e);
2421                    const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);
2422                    const int words = n * (20 * 9);
2423                    if (g > (int) blockIdx.y || e > e0) iq_sync_lds();
2424                    for (int i = threadIdx.x; i < words; i += 256) s_hq_buf[i] = src[i];
2425                    iq_sync_lds();
2426                    if (valid_r) {
2427                        if (n == 1) {
2428                            const int off1[1] = { 0 };
2429                            float s1[1];
2430                            row_dot_20_sub16<TD, 1, true>(wr, s_hq, off1, 1, t, s1);
2431                            if (t == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0] * sd;
2432                        } else if (n == 2) {
2433                            const int off2[2] = { 0, 20 };
2434                            float s2[2];
2435                            row_dot_20_sub16<TD, 2, true>(wr, s_hq, off2, 2, t, s2);
2436                            if (t < 2) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s2[t] * sd;
2437                        } else if (n == 3) {
2438                            const int off3[3] = { 0, 20, 40 };
2439                            float s3[3];
2440                            row_dot_20_sub16<TD, 3, true>(wr, s_hq, off3, 3, t, s3);
2441                            if (t < 3) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s3[t] * sd;
2442                        } else {
2443                            const int off4[4] = { 0, 20, 40, 60 };
2444                            float s4[4];
2445                            row_dot_20_sub16<TD, 4, true>(wr, s_hq, off4, 4, t, s4);
2446                            if (t < 4) out[(size_t) ent_dst[e + t] * L.n_embd + r] = s4[t] * sd;
2447                        }
2448                    }
2449                }
2450            }
2451            return;
2452        }
2453    }
2454    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
2455    const int r = blockIdx.x * 8 + warp;
2456    const bool valid_r = (r < L.n_embd);
2457    const size_t w_off = L.down_off + (size_t) (valid_r ? r : 0) * L.d_row;
2458    for (int g = blockIdx.y; g < ng; g += gridDim.y) {   // the group stride, as native_gu_kernel
2459        const uint8_t* wr = (const uint8_t*) grp_ptr[g] + w_off;
2460                const float sd = L.tail_off ? ((const float*) (grp_ptr[g] + L.tail_off))[2] : 1.0f;   // NVFP4: s_down
2461        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2462        if (hb == 20) {
2463            const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
2464            for (int e = e0; e < e1; e += GRP_NC) {
2465                const int n = min(GRP_NC, e1 - e);
2466                const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);
2467                const int words = n * (20 * 9);
2468                if (g > (int) blockIdx.y || e > e0) iq_sync_lds();
2469                for (int i = threadIdx.x; i < words; i += 256) s_hq_buf[i] = src[i];
2470                iq_sync_lds();
2471                if (valid_r) {
2472                    if (n == 1) {
2473                        const int off1[1] = { 0 };
2474                        float s1[1];
2475                        row_dot_multi<TD, 1, true, STAGE_TQ>(wr, s_hq, off1, 1, nb, lane, s1, s_grid);
2476                        if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s1[0] * sd;
2477                    } else if (n == 2) {
2478                        const int off2[2] = { 0, 20 };
2479                        float s2[2];
2480                        row_dot_multi<TD, 2, true, STAGE_TQ>(wr, s_hq, off2, 2, nb, lane, s2, s_grid);
2481                        if (lane < 2) out[(size_t) ent_dst[e + lane] * L.n_embd + r] = s2[lane] * sd;
2482                    } else {
2483                        int off[GRP_NC];
2484#pragma unroll
2485                        for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * 20;
2486                        float s[GRP_NC];
2487                        row_dot_multi<TD, GRP_NC, false, STAGE_TQ>(wr, s_hq, off, n, nb, lane, s, s_grid);
2488#pragma unroll
2489                        for (int c = 0; c < GRP_NC; ++c)
2490                            if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c] * sd;
2491                    }
2492                }
2493            }
2494        } else if (valid_r) {
2495            for (int e = e0; e < e1; e += GRP_NC) {
2496                const int n = min(GRP_NC, e1 - e);
2497                int off[GRP_NC];
2498#pragma unroll
2499                for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb;
2500                float s[GRP_NC];
2501                row_dot_multi<TD, GRP_NC, false, STAGE_TQ>(wr, hq, off, n, nb, lane, s, s_grid);
2502#pragma unroll
2503                for (int c = 0; c < GRP_NC; ++c)
2504                    if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c] * sd;
2505            }
2506        }
2507    }
2508}
2509
2510// ---------------------------------------------------------------- EXPDEC (STRATA_EXPDEC=1): the group's activations
2511// in shared memory, R rows per lane
2512//
2513// native_gu_multi_kernel / native_down_multi_kernel decode each weight part once and apply it to every entry of the
2514// group, but the gate/up apply re-reads the entry's q8_1 block from global memory with 9 scattered 4-byte loads
2515// (36-byte blocks: a warp's load touches 32 sectors), so an entry costs about 60% of a whole expert (nsys, 2080 Ti,
2516// L02 at 131k: ~2.6 us per expert and ~1.6 us per entry and layer) although it reads nothing from DRAM.  Here a
2517// block stages its group's entries (ED_NC at a time, as the default) in shared memory laid out so that a call's
2518// words are two 16-byte loads (gate/up, Q2_0 down: the block's two halves in separate planes, conflict-free) or two
2519// 8-byte loads (IQ4_NL down), the fp16 block scale already a float; every lane computes R rows at once, so the
2520// activation words are loaded once per R rows; the IQ3_XXS / IQ3_S codebooks are staged too (IQ2_* already were),
2521// and a block takes `rb` rows (auto: the most that keep ~STRATA_EXPDEC_MINBLK blocks in flight) instead of 16.
2522// Each (row, entry) sum is the default kernel's sum tree (row_dot_80_sub16 / row_dot_40_sub8 / row_dot_20_sub16: the
2523// same lane does the same calls in the same order with the same operations, `apply_u` = `apply` on the block's
2524// words), so the output is bitwise the same (expdec_bench checks it; docs/EXPERTDEC.md).
2525#ifndef STRATA_EXPDEC_MINB
2526#define STRATA_EXPDEC_MINB 4   // gate/up __launch_bounds__ min blocks per SM by default (STRATA_EXPDEC_MINB at runtime): 4 = up to 64
2527                               // registers, as the default kernels (bench: equal on the 2080 Ti, 0.87-0.95 on the 3060); 2 = up to 128
2528#endif
2529constexpr int ED_NC = GRP_NC;   // entries staged at once
2530constexpr int ED_XB = 80;       // q8_1 blocks of a gate/up row (n_embd 2560)
2531constexpr int ED_HB = 20;       // q8_1 blocks of a down row (n_ff 640)
2532
2533// the codebook of a gate/up format in shared memory: words, and the copy (every thread of the block; sync after)
2534template<int TG> struct EdGrid;
2535template<> struct EdGrid<16> { static constexpr int words = 512;
2536    __device__ static void copy(uint32_t* s, int tid) { const uint2* src = (const uint2*) iq2xxs_grid; uint2* dst = (uint2*) s; for (int i = tid; i < 256; i += 256) dst[i] = src[i]; } };
2537template<> struct EdGrid<17> { static constexpr int words = 1024;
2538    __device__ static void copy(uint32_t* s, int tid) { const uint2* src = (const uint2*) iq2xs_grid; uint2* dst = (uint2*) s; for (int i = tid; i < 512; i += 256) dst[i] = src[i]; } };
2539template<> struct EdGrid<22> { static constexpr int words = 2048;
2540    __device__ static void copy(uint32_t* s, int tid) { const uint2* src = (const uint2*) iq2s_grid; uint2* dst = (uint2*) s; for (int i = tid; i < 1024; i += 256) dst[i] = src[i]; } };
2541// (IQ3_XXS / IQ3_S: the codebook and, behind it, the sign-mask tables Split<TG>::load<true> reads - stage_iq_grid's layout)
2542template<> struct EdGrid<18> { static constexpr int words = 512;
2543    __device__ static void copy(uint32_t* s, int tid) {
2544        for (int i = tid; i < 256; i += 256) s[i] = iq3xxs_grid[i];
2545        stage_iq3xxs_masks(s, tid, 256);
2546    } };
2547template<> struct EdGrid<21> { static constexpr int words = 1024;
2548    __device__ static void copy(uint32_t* s, int tid) {
2549        for (int i = tid; i < 512; i += 256) s[i] = iq3s_grid[i];
2550        stage_iq3s_masks(s, tid, 256);
2551    } };
2552
2553// One entry's q8_1 row (XB blocks of 36 bytes, 4-byte aligned) into shared memory as entry c: the 8 words of block k
2554// in planes (HALVES: s_u[(2 c + h) XB + k] = words 4h..4h+3, two 16-byte loads per call, conflict-free over 16
2555// consecutive k; else s_u[(c XB + k) 2 + h], the block's 32 bytes together, for the IQ4_NL pairs) and the fp16 scale
2556// as s_ds[c XB + k] = __low2float(ds), the value `apply` computes.  All 256 threads.
2557template<int XB, bool HALVES>
2558__device__ __forceinline__ void ed_stage_entry(int4* __restrict__ s_u, float* __restrict__ s_ds, int c,
2559                                               const block_q8_1* __restrict__ src, int tid) {
2560    static_assert(XB <= 128, "XB must fit in 128 thread-pairs");
2561    const int* w32 = (const int*) src;
2562    const int k = tid >> 1, h = tid & 1;
2563    if (k < XB) {
2564        const int* p = w32 + k * 9 + 1 + 4 * h;
2565        const int4 v = make_int4(p[0], p[1], p[2], p[3]);
2566        if constexpr (HALVES) s_u[(c * 2 + h) * XB + k] = v;
2567        else s_u[(c * XB + k) * 2 + h] = v;
2568    }
2569    if (tid < XB) {
2570        const int v = w32[tid * 9];
2571        const half2 h2 = *reinterpret_cast<const half2*>(&v);
2572        s_ds[c * XB + tid] = __low2float(h2);
2573    }
2574}
2575template<int XB>
2576__device__ __forceinline__ void ed_load_u(const int4* __restrict__ s_u, int c, int k, int (&u)[8]) {
2577    const int4 a = s_u[(c * 2 + 0) * XB + k], b = s_u[(c * 2 + 1) * XB + k];
2578    u[0] = a.x; u[1] = a.y; u[2] = a.z; u[3] = a.w;
2579    u[4] = b.x; u[5] = b.y; u[6] = b.z; u[7] = b.w;
2580}
2581
2582// R gate/up rows against the NC staged entries, lane t of a 16-lane sub-warp: row_dot_80_sub16's tree (calls t,
2583// t+32, t+64 into s; t+16, t+48 into s16; s = __fadd_rn(s, s16); xor 8-4-2-1), every call's weight part decoded once
2584// per row and the entry's block loaded once per NC x R products.
2585template<int TG, int R, int NC>
2586__device__ __forceinline__ void ed_gu_rows(const uint8_t* const* wr, const int4* __restrict__ s_u,
2587                                           const float* __restrict__ s_ds, const uint32_t* __restrict__ s_grid, int t,
2588                                           float (&s)[R][NC]) {
2589    using F = Fmt<TG>;
2590    using S = Split<TG>;
2591    float s16[R][NC];
2592#pragma unroll
2593    for (int r = 0; r < R; ++r)
2594#pragma unroll
2595        for (int c = 0; c < NC; ++c) { s[r][c] = 0.0f; s16[r][c] = 0.0f; }
2596#pragma unroll
2597    for (int j = 0; j < 3; ++j) {
2598        const int k = t + 32 * j;
2599        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
2600        typename S::W w[R];
2601#pragma unroll
2602        for (int r = 0; r < R; ++r) w[r] = S::template load<true>(wr[r], kbx, iqs, s_grid);
2603#pragma unroll
2604        for (int c = 0; c < NC; ++c) {
2605            int u[8];
2606            ed_load_u<ED_XB>(s_u, c, k, u);
2607            const float d8 = s_ds[c * ED_XB + k];
2608#pragma unroll
2609            for (int r = 0; r < R; ++r) s[r][c] += S::apply_u(w[r], u, d8);
2610        }
2611    }
2612#pragma unroll
2613    for (int j = 0; j < 2; ++j) {
2614        const int k = t + 16 + 32 * j;
2615        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
2616        typename S::W w[R];
2617#pragma unroll
2618        for (int r = 0; r < R; ++r) w[r] = S::template load<true>(wr[r], kbx, iqs, s_grid);
2619#pragma unroll
2620        for (int c = 0; c < NC; ++c) {
2621            int u[8];
2622            ed_load_u<ED_XB>(s_u, c, k, u);
2623            const float d8 = s_ds[c * ED_XB + k];
2624#pragma unroll
2625            for (int r = 0; r < R; ++r) s16[r][c] += S::apply_u(w[r], u, d8);
2626        }
2627    }
2628#pragma unroll
2629    for (int r = 0; r < R; ++r)
2630#pragma unroll
2631        for (int c = 0; c < NC; ++c) {
2632            s[r][c] = __fadd_rn(s[r][c], s16[r][c]);
2633#pragma unroll
2634            for (int o = 8; o > 0; o >>= 1) s[r][c] += __shfl_xor_sync(0xffffffffu, s[r][c], o);
2635        }
2636}
2637
2638// gate/up: 16 sub-warps of 16 lanes, R rows each = 16 R rows per pass, `rb` rows per block (a multiple of 16 R; 2 n_ff
2639// is one too, so a pass is whole or absent for the entire block).  Group stride as native_gu_multi_kernel.
2640template<int TG, int R, int MINB>
2641#if defined(__HIPCC__)
2642__global__ void __launch_bounds__(256, MINB * 2) expdec_gu_kernel(
2643#else
2644__global__ void __launch_bounds__(256, MINB) expdec_gu_kernel(
2645#endif
2646                                                                            const unsigned long long* __restrict__ grp_ptr,
2647                                                                            const int32_t* __restrict__ grp_start,
2648                                                                            const int32_t* __restrict__ n_groups,
2649                                                                            const int32_t* __restrict__ ent_tok,
2650                                                                            const block_q8_1* __restrict__ xq, NativeExpertLayout L,
2651                                                                            float* __restrict__ gate, float* __restrict__ up, int rb) {
2652    const int ng = *n_groups;
2653    if (blockIdx.y >= ng) return;
2654    __shared__ alignas(16) int4 s_u[ED_NC * 2 * ED_XB];
2655    __shared__ float s_ds[ED_NC * ED_XB];
2656    STRATA_SHARED_ALIGN16_U32(s_grid_buf, EdGrid<TG>::words);
2657    const int tid = threadIdx.x;
2658    EdGrid<TG>::copy(s_grid_buf, tid);   // visible after the staging's iq_sync_lds
2659    const int sw = tid >> 4, t = tid & 15;
2660    const int nrow = 2 * (int) L.n_ff, n_ff = (int) L.n_ff;
2661    const int row_base = blockIdx.x * rb;
2662    for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2663        const uint8_t* blob = (const uint8_t*) grp_ptr[g];
2664        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2665        for (int e = e0; e < e1; e += ED_NC) {
2666            const int n = min(ED_NC, e1 - e);
2667            if (g > (int) blockIdx.y || e > e0) iq_sync_lds();
2668            for (int c = 0; c < n; ++c) ed_stage_entry<ED_XB, true>(s_u, s_ds, c, xq + (size_t) ent_tok[e + c] * ED_XB, tid);
2669            iq_sync_lds();
2670            for (int p = 0; p * 16 * R < rb; ++p) {
2671                const int row0 = row_base + p * 16 * R + sw * R;
2672                if (row0 >= nrow) break;   // uniform over the block
2673                const bool is_up = row0 >= n_ff;
2674                const int r0 = is_up ? row0 - n_ff : row0;
2675                const uint8_t* wr[R];
2676#pragma unroll
2677                for (int r = 0; r < R; ++r) wr[r] = blob + (is_up ? L.up_off : 0) + (size_t) (r0 + r) * L.gu_row;
2678                float* dst = is_up ? up : gate;
2679                auto run = [&](auto nc) {
2680                    constexpr int NC = decltype(nc)::value;
2681                    float s[R][NC];
2682                    ed_gu_rows<TG, R, NC>(wr, s_u, s_ds, s_grid_buf, t, s);
2683#pragma unroll
2684                    for (int c = 0; c < NC; ++c)
2685                        if (t == c)
2686#pragma unroll
2687                            for (int r = 0; r < R; ++r) dst[(size_t) (e + c) * n_ff + r0 + r] = s[r][c];
2688                };
2689                switch (n) {
2690                    case 1: run(std::integral_constant<int, 1>{}); break;
2691                    case 2: run(std::integral_constant<int, 2>{}); break;
2692                    case 3: run(std::integral_constant<int, 3>{}); break;
2693                    default: run(std::integral_constant<int, 4>{}); break;
2694                }
2695            }
2696        }
2697    }
2698}
2699
2700// R IQ4_NL down rows, lane t of an 8-lane sub-warp: row_dot_40_sub8's tree.  s_p: the block's 8 words together
2701// (ed_stage_entry<ED_HB, false>), read as the int2 pairs (iqs, iqs + 1) and (iqs + 4, iqs + 5).
2702template<int R, int NC>
2703__device__ __forceinline__ void ed_d20_rows(const uint8_t* const* wr, const int2* __restrict__ s_p,
2704                                            const float* __restrict__ s_ds, int t, float (&s)[R][NC]) {
2705    using F = Fmt<20>;
2706    using S = Split<20>;
2707    auto term = [&](int k, int r, int c, const typename S::W& w) -> float {
2708        const int kbx = k / F::ipb, par = k & 1;
2709        const int2 p0 = s_p[(c * ED_HB + kbx) * 4 + par], p1 = s_p[(c * ED_HB + kbx) * 4 + 2 + par];
2710        return S::apply_u(w, p0, p1, s_ds[c * ED_HB + kbx]);
2711    };
2712    auto loadw = [&](int k, typename S::W (&w)[R]) {
2713        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
2714#pragma unroll
2715        for (int r = 0; r < R; ++r) w[r] = S::load(wr[r], kbx, iqs);
2716    };
2717#pragma unroll
2718    for (int r = 0; r < R; ++r)
2719#pragma unroll
2720        for (int c = 0; c < NC; ++c) s[r][c] = 0.0f;
2721#pragma unroll
2722    for (int j = 0; j < 2; ++j) {   // k = t, t + 32
2723        const int k = t + 32 * j;
2724        typename S::W w[R];
2725        loadw(k, w);
2726#pragma unroll
2727        for (int c = 0; c < NC; ++c)
2728#pragma unroll
2729            for (int r = 0; r < R; ++r) s[r][c] += term(k, r, c, w[r]);
2730    }
2731    {
2732        const int k = t + 16;
2733        typename S::W w[R];
2734        loadw(k, w);
2735#pragma unroll
2736        for (int c = 0; c < NC; ++c)
2737#pragma unroll
2738            for (int r = 0; r < R; ++r) {
2739                float s16 = 0.0f;
2740                s16 += term(k, r, c, w[r]);
2741                s[r][c] = __fadd_rn(s[r][c], s16);
2742            }
2743    }
2744    float s8[R][NC];
2745#pragma unroll
2746    for (int r = 0; r < R; ++r)
2747#pragma unroll
2748        for (int c = 0; c < NC; ++c) s8[r][c] = 0.0f;
2749    {
2750        const int k = t + 8;
2751        typename S::W w[R];
2752        loadw(k, w);
2753#pragma unroll
2754        for (int c = 0; c < NC; ++c)
2755#pragma unroll
2756            for (int r = 0; r < R; ++r) s8[r][c] += term(k, r, c, w[r]);
2757    }
2758    {
2759        const int k = t + 24;
2760        typename S::W w[R];
2761        loadw(k, w);
2762#pragma unroll
2763        for (int c = 0; c < NC; ++c)
2764#pragma unroll
2765            for (int r = 0; r < R; ++r) {
2766                float s24 = 0.0f;
2767                s24 += term(k, r, c, w[r]);
2768                s[r][c] = __fadd_rn(s[r][c], __fadd_rn(s8[r][c], s24));
2769            }
2770    }
2771#pragma unroll
2772    for (int r = 0; r < R; ++r)
2773#pragma unroll
2774        for (int c = 0; c < NC; ++c)
2775#pragma unroll
2776            for (int o = 4; o > 0; o >>= 1) s[r][c] += __shfl_xor_sync(0xffffffffu, s[r][c], o);
2777}
2778
2779// R Q2_0 down rows, lane t of a 16-lane sub-warp: row_dot_20_sub16's tree (call t; call t + 16 for t < 4 into s16).
2780template<int R, int NC>
2781__device__ __forceinline__ void ed_d42_rows(const uint8_t* const* wr, const int4* __restrict__ s_u,
2782                                            const float* __restrict__ s_ds, int t, float (&s)[R][NC]) {
2783    using F = Fmt<42>;
2784    using S = Split<42>;
2785    {
2786        const int k = t, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
2787        typename S::W w[R];
2788#pragma unroll
2789        for (int r = 0; r < R; ++r) w[r] = S::load(wr[r], kbx, iqs);
2790#pragma unroll
2791        for (int c = 0; c < NC; ++c) {
2792            int u[8];
2793            ed_load_u<ED_HB>(s_u, c, k, u);
2794            const float d8 = s_ds[c * ED_HB + k];
2795#pragma unroll
2796            for (int r = 0; r < R; ++r) { s[r][c] = 0.0f; s[r][c] += S::apply_u(w[r], u, d8); }
2797        }
2798    }
2799    float s16[R][NC];
2800#pragma unroll
2801    for (int r = 0; r < R; ++r)
2802#pragma unroll
2803        for (int c = 0; c < NC; ++c) s16[r][c] = 0.0f;
2804    if (t < 4) {
2805        const int k = t + 16, kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
2806        typename S::W w[R];
2807#pragma unroll
2808        for (int r = 0; r < R; ++r) w[r] = S::load(wr[r], kbx, iqs);
2809#pragma unroll
2810        for (int c = 0; c < NC; ++c) {
2811            int u[8];
2812            ed_load_u<ED_HB>(s_u, c, k, u);
2813            const float d8 = s_ds[c * ED_HB + k];
2814#pragma unroll
2815            for (int r = 0; r < R; ++r) s16[r][c] += S::apply_u(w[r], u, d8);
2816        }
2817    }
2818#pragma unroll
2819    for (int r = 0; r < R; ++r)
2820#pragma unroll
2821        for (int c = 0; c < NC; ++c) {
2822            s[r][c] = __fadd_rn(s[r][c], s16[r][c]);
2823#pragma unroll
2824            for (int o = 8; o > 0; o >>= 1) s[r][c] += __shfl_xor_sync(0xffffffffu, s[r][c], o);
2825        }
2826}
2827
2828// down (IQ4_NL: 32 sub-warps of 8 lanes; Q2_0: 16 of 16), R rows per lane, `rb` rows per block (a multiple of the
2829// rows per pass; n_embd too).  The entries' h rows are contiguous in hq (entry e at e * ED_HB).
2830template<int TD, int R>
2831__global__ void __launch_bounds__(256, STRATA_EXPDEC_MINB) expdec_down_kernel(const unsigned long long* __restrict__ grp_ptr,
2832                                                                              const int32_t* __restrict__ grp_start,
2833                                                                              const int32_t* __restrict__ n_groups,
2834                                                                              const int32_t* __restrict__ ent_dst,
2835                                                                              const block_q8_1* __restrict__ hq, NativeExpertLayout L,
2836                                                                              float* __restrict__ out, int rb) {
2837    const int ng = *n_groups;
2838    if (blockIdx.y >= ng) return;
2839    constexpr int LANES = TD == 20 ? 8 : 16;
2840    constexpr int RPP = (256 / LANES) * R;   // rows per pass
2841    __shared__ alignas(16) int4 s_u[ED_NC * 2 * ED_HB];
2842    __shared__ float s_ds[ED_NC * ED_HB];
2843    const int tid = threadIdx.x;
2844    const int sw = tid / LANES, t = tid % LANES;
2845    const int nrow = (int) L.n_embd;
2846    const int row_base = blockIdx.x * rb;
2847    for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2848        const uint8_t* blob = (const uint8_t*) grp_ptr[g] + L.down_off;
2849        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2850        for (int e = e0; e < e1; e += ED_NC) {
2851            const int n = min(ED_NC, e1 - e);
2852            if (g > (int) blockIdx.y || e > e0) iq_sync_lds();
2853            for (int c = 0; c < n; ++c) ed_stage_entry<ED_HB, TD == 42>(s_u, s_ds, c, hq + (size_t) (e + c) * ED_HB, tid);
2854            iq_sync_lds();
2855            for (int p = 0; p * RPP < rb; ++p) {
2856                const int row0 = row_base + p * RPP + sw * R;
2857                if (row0 >= nrow) break;   // uniform over the block
2858                const uint8_t* wr[R];
2859#pragma unroll
2860                for (int r = 0; r < R; ++r) wr[r] = blob + (size_t) (row0 + r) * L.d_row;
2861                auto run = [&](auto nc) {
2862                    constexpr int NC = decltype(nc)::value;
2863                    float s[R][NC];
2864                    if constexpr (TD == 20) ed_d20_rows<R, NC>(wr, (const int2*) s_u, s_ds, t, s);
2865                    else ed_d42_rows<R, NC>(wr, s_u, s_ds, t, s);
2866#pragma unroll
2867                    for (int c = 0; c < NC; ++c)
2868                        if (t == c) {
2869                            const size_t o = (size_t) ent_dst[e + c] * L.n_embd + row0;
2870#pragma unroll
2871                            for (int r = 0; r < R; ++r) out[o + r] = s[r][c];
2872                        }
2873                };
2874                switch (n) {
2875                    case 1: run(std::integral_constant<int, 1>{}); break;
2876                    case 2: run(std::integral_constant<int, 2>{}); break;
2877                    case 3: run(std::integral_constant<int, 3>{}); break;
2878                    default: run(std::integral_constant<int, 4>{}); break;
2879                }
2880            }
2881        }
2882    }
2883}
2884
2885// ---------------------------------------------------------------- q8_1 (quantize.cu)
2886// value i of a q8_1 row set (the warp holds block i / 32, lane = i % 32)
2887__device__ __forceinline__ void q8_1_store(const float xi, block_q8_1* __restrict__ y, const long long i) {
2888    float amax = fabsf(xi), sum = xi;
2889#pragma unroll
2890    for (int o = 16; o > 0; o >>= 1) {
2891        amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
2892        sum += __shfl_xor_sync(0xffffffffu, sum, o);
2893    }
2894    const float d = q8_1_finite(amax / 127.0f);   // #606: q8_1_finite.hpp - the same bits for every finite block
2895    const int8_t q = q8_1_quant(xi, d, amax);
2896    const long long ib = i / 32, iqs = i % 32;
2897    y[ib].qs[iqs] = q;
2898    if (iqs == 0) y[ib].ds = q8_1_ds(d, sum);
2899}
2900
2901__global__ void quantize_q8_1_kernel(const float* __restrict__ x, block_q8_1* __restrict__ y, long long n) {
2902    const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;
2903    if (i >= n) return;
2904    q8_1_store(x[i], y, i);
2905}
2906
2907// swiglu_entries_kernel and quantize_q8_1_kernel in one pass, over the call's own entries only:
2908// [grp_start[0], grp_start[*n_groups]) (a call's entries are contiguous; the verify window's PCIe call starts after
2909// its VRAM call) instead of all cap_entries twice - nothing reads the others: the down kernel reads its groups'.
2910// n_ff is a multiple of 32, so a warp is one q8_1 block and the bounds are warp-uniform.  The values are the two
2911// kernels': the SwiGLU product is rounded on its own - it must not contract into the first add of q8_1_store's block
2912// sum, as it could not when it went through memory (CUDA: __fmul_rn; HIP's __fmul_rn is a plain product, so there
2913// the product is written here under contract(off)) - then q8_1_store unchanged: the same blocks, bit for bit.
2914__global__ void __launch_bounds__(256) swiglu_q8_1_entries_kernel(const float* __restrict__ gate,
2915                                                                  const float* __restrict__ up,
2916                                                                  const int32_t* __restrict__ grp_start,
2917                                                                  const int32_t* __restrict__ n_groups, int n_ff,
2918                                                                  block_q8_1* __restrict__ hq) {
2919#if defined(__HIPCC__)
2920#pragma clang fp contract(off)
2921#endif
2922    const long long lo = (long long) grp_start[0] * n_ff, hi = (long long) grp_start[*n_groups] * n_ff;
2923    for (long long i = lo + (long long) blockIdx.x * blockDim.x + threadIdx.x; i < hi;
2924         i += (long long) gridDim.x * blockDim.x) {
2925        const float g = gate[i];
2926#if defined(__HIPCC__)
2927        const float h = (g / (1.0f + __expf(-g))) * up[i];
2928#else
2929        const float h = __fmul_rn(g / (1.0f + __expf(-g)), up[i]);
2930#endif
2931        q8_1_store(h, hq, i);
2932    }
2933}
2934
2935// 147-verify (STRATA_GU_SWIGLU=1): native_gu_multi_kernel's 16-lane gate and up rows, SwiGLU and the q8_1 blocks in ONE
2936// launch.  A block owns 32 consecutive hidden columns r of a group: its 32 sub-warps each compute gate row r and up row
2937// r (the same row_dot_80_sub16 calls, entries GRP_NC at a time, the same NVFP4 tail scale), so the product
2938// h = silu(gate) * up is formed in the block and warp k quantizes entry k's 32 values with q8_1_store - the q8_1 block
2939// of those columns.  Every value is the separate kernels': the dots are the same calls, gate and up are the same floats
2940// (written to memory before), the product is rounded on its own as in swiglu_q8_1_entries_kernel, and q8_1_store is the
2941// same.  It saves the gate/up round trip through memory and one launch per layer.
2942template<int TG, bool STAGE_GRID>
2943__global__ void __launch_bounds__(512) native_gu_swiglu_kernel(const unsigned long long* __restrict__ grp_ptr,
2944                                                               const int32_t* __restrict__ grp_start,
2945                                                               const int32_t* __restrict__ n_groups,
2946                                                               const int32_t* __restrict__ ent_tok,
2947                                                               const block_q8_1* __restrict__ xq, NativeExpertLayout L,
2948                                                               block_q8_1* __restrict__ hq) {
2949#if defined(__HIPCC__)
2950#pragma clang fp contract(off)
2951#endif
2952    const int ng = *n_groups;
2953    if ((int) blockIdx.y >= ng) return;
2954    STRATA_SHARED_ALIGN16_U32(s_grid_buf, IqGridWords<TG, STAGE_GRID>::value);
2955    const uint32_t* s_grid = stage_iq_grid<TG, STAGE_GRID>(s_grid_buf, threadIdx.x, 512);
2956    __shared__ float sh[GRP_NC][32];
2957    const int sw = threadIdx.x >> 4, t = threadIdx.x & 15, warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
2958    const int r = blockIdx.x * 32 + sw;                       // the hidden column (gate row r, up row r)
2959    const size_t g_off = (size_t) r * L.gu_row, u_off = L.up_off + (size_t) r * L.gu_row;
2960    for (int g = blockIdx.y; g < ng; g += gridDim.y) {
2961        const uint8_t* blob = (const uint8_t*) grp_ptr[g];
2962        const float sg = L.tail_off ? ((const float*) (blob + L.tail_off))[0] : 1.0f;   // NVFP4: s_gate / s_up
2963        const float su = L.tail_off ? ((const float*) (blob + L.tail_off))[1] : 1.0f;
2964        const int e0 = grp_start[g], e1 = grp_start[g + 1];
2965        for (int e = e0; e < e1; e += GRP_NC) {
2966            const int n = min(GRP_NC, e1 - e);
2967            float gv[GRP_NC], uv[GRP_NC];
2968            if (n == 1) {
2969                const int off1[1] = { ent_tok[e] * 80 };
2970                float a1[1], b1[1];
2971                row_dot2_80_sub16<TG, 1, true, STAGE_GRID>(blob + g_off, blob + u_off, xq, off1, 1, t, a1, b1, s_grid);
2972                gv[0] = a1[0]; uv[0] = b1[0];
2973            } else if (n == 2) {
2974                const int off2[2] = { ent_tok[e] * 80, ent_tok[e + 1] * 80 };
2975                float a2[2], b2[2];
2976                row_dot2_80_sub16<TG, 2, true, STAGE_GRID>(blob + g_off, blob + u_off, xq, off2, 2, t, a2, b2, s_grid);
2977#pragma unroll
2978                for (int c = 0; c < 2; ++c) { gv[c] = a2[c]; uv[c] = b2[c]; }
2979            } else if (n == 3) {
2980                const int off3[3] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80 };
2981                float a3[3], b3[3];
2982                row_dot2_80_sub16<TG, 3, true, STAGE_GRID>(blob + g_off, blob + u_off, xq, off3, 3, t, a3, b3, s_grid);
2983#pragma unroll
2984                for (int c = 0; c < 3; ++c) { gv[c] = a3[c]; uv[c] = b3[c]; }
2985            } else {
2986                const int off4[4] = { ent_tok[e] * 80, ent_tok[e + 1] * 80, ent_tok[e + 2] * 80, ent_tok[e + 3] * 80 };
2987                float a4[4], b4[4];
2988                row_dot2_80_sub16<TG, 4, true, STAGE_GRID>(blob + g_off, blob + u_off, xq, off4, 4, t, a4, b4, s_grid);
2989#pragma unroll
2990                for (int c = 0; c < 4; ++c) { gv[c] = a4[c]; uv[c] = b4[c]; }
2991            }
2992            // sub-lane c holds entry c's sums (as the separate kernel's store): h of column r, entry c
2993#pragma unroll
2994            for (int c = 0; c < GRP_NC; ++c) {
2995                if (c < n && t == c) {
2996                    const float gg = gv[c] * sg, uu = uv[c] * su;
2997#if defined(__HIPCC__)
2998                    sh[c][sw] = (gg / (1.0f + __expf(-gg))) * uu;
2999#else
3000                    sh[c][sw] = __fmul_rn(gg / (1.0f + __expf(-gg)), uu);
3001#endif
3002                }
3003            }
3004            __syncthreads();
3005            if (warp < n) q8_1_store(sh[warp][lane], hq, (long long) (e + warp) * L.n_ff + (long long) blockIdx.x * 32 + lane);
3006            __syncthreads();
3007        }
3008    }
3009}
3010
3011// ---------------------------------------------------------------- dequant (dequantize.cuh)
3012template<typename dst_t> __device__ __forceinline__ dst_t cvt(float v);
3013template<> __device__ __forceinline__ float cvt<float>(float v) { return v; }
3014template<> __device__ __forceinline__ __half cvt<__half>(float v) { return __float2half(v); }
3015
3016template<typename dst_t>
3017__device__ void dq_iq2_xxs(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3018    const block_iq2_xxs* x = (const block_iq2_xxs*) vx;
3019    const int64_t il = tid / 8, ib = tid % 8;
3020    dst_t* y = yy + 32 * ib + 8 * il;
3021    const uint16_t* q2 = x[ibs].qs + 4 * ib;
3022    const uint8_t* aux8 = (const uint8_t*) q2;
3023    const uint8_t* grid = (const uint8_t*) (iq2xxs_grid + aux8[il]);
3024    const uint32_t aux32 = q2[2] | (q2[3] << 16);
3025    const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.25f;
3026    const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127];
3027    for (int j = 0; j < 8; ++j) y[j] = cvt<dst_t>(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f));
3028}
3029template<typename dst_t>
3030__device__ void dq_iq2_xs(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3031    const block_iq2_xs* x = (const block_iq2_xs*) vx;
3032    const int64_t il = tid / 8, ib = tid % 8;
3033    dst_t* y = yy + 32 * ib + 8 * il;
3034    const uint16_t* q2 = x[ibs].qs + 4 * ib;
3035    const uint8_t* grid = (const uint8_t*) (iq2xs_grid + (q2[il] & 511));
3036    const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f;
3037    const uint8_t signs = ksigns_iq2xs[q2[il] >> 9];
3038    for (int j = 0; j < 8; ++j) y[j] = cvt<dst_t>(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f));
3039}
3040template<typename dst_t>
3041__device__ void dq_iq2_s(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3042    const block_iq2_s* x = (const block_iq2_s*) vx;
3043    const int64_t il = tid / 8, ib = tid % 8;
3044    dst_t* y = yy + 32 * ib + 8 * il;
3045    const uint8_t* grid = (const uint8_t*) (iq2s_grid + (x[ibs].qs[4 * ib + il] | ((x[ibs].qh[ib] << (8 - 2 * il)) & 0x300)));
3046    const float d = (float) x[ibs].d * (0.5f + ((x[ibs].scales[ib] >> 4 * (il / 2)) & 0xf)) * 0.25f;
3047    const uint8_t signs = x[ibs].qs[QK_K / 8 + 4 * ib + il];
3048    for (int j = 0; j < 8; ++j) y[j] = cvt<dst_t>(d * grid[j] * (signs & kmask_iq2xs[j] ? -1.f : 1.f));
3049}
3050template<typename dst_t>
3051__device__ void dq_iq3_xxs(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3052    const block_iq3_xxs* x = (const block_iq3_xxs*) vx;
3053    const int64_t il = tid / 8, ib = tid % 8;
3054    dst_t* y = yy + 32 * ib + 8 * il;
3055    const uint8_t* q3 = x[ibs].qs + 8 * ib;
3056    const uint16_t* gas = (const uint16_t*) (x[ibs].qs + QK_K / 4) + 2 * ib;
3057    const uint8_t* grid1 = (const uint8_t*) (iq3xxs_grid + q3[2 * il + 0]);
3058    const uint8_t* grid2 = (const uint8_t*) (iq3xxs_grid + q3[2 * il + 1]);
3059    const uint32_t aux32 = gas[0] | (gas[1] << 16);
3060    const float d = (float) x[ibs].d * (0.5f + (aux32 >> 28)) * 0.5f;
3061    const uint8_t signs = ksigns_iq2xs[(aux32 >> 7 * il) & 127];
3062    for (int j = 0; j < 4; ++j) {
3063        y[j + 0] = cvt<dst_t>(d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f));
3064        y[j + 4] = cvt<dst_t>(d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f));
3065    }
3066}
3067template<typename dst_t>
3068__device__ void dq_iq3_s(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3069    const block_iq3_s* x = (const block_iq3_s*) vx;
3070    const int64_t il = tid / 8, ib = tid % 8;
3071    dst_t* y = yy + 32 * ib + 8 * il;
3072    const uint8_t* qs = x[ibs].qs + 8 * ib;
3073    const uint8_t* grid1 = (const uint8_t*) (iq3s_grid + (qs[2 * il + 0] | ((x[ibs].qh[ib] << (8 - 2 * il)) & 256)));
3074    const uint8_t* grid2 = (const uint8_t*) (iq3s_grid + (qs[2 * il + 1] | ((x[ibs].qh[ib] << (7 - 2 * il)) & 256)));
3075    const float d = (float) x[ibs].d * (1 + 2 * ((x[ibs].scales[ib / 2] >> 4 * (ib % 2)) & 0xf));
3076    const uint8_t signs = x[ibs].signs[4 * ib + il];
3077    for (int j = 0; j < 4; ++j) {
3078        y[j + 0] = cvt<dst_t>(d * grid1[j] * (signs & kmask_iq2xs[j + 0] ? -1.f : 1.f));
3079        y[j + 4] = cvt<dst_t>(d * grid2[j] * (signs & kmask_iq2xs[j + 4] ? -1.f : 1.f));
3080    }
3081}
3082template<typename dst_t>
3083__device__ void dq_iq1_m(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3084    const block_iq1_m* x = (const block_iq1_m*) vx;
3085    const int64_t il = tid / 8, ib = tid % 8;
3086    dst_t* y = yy + 32 * ib + 8 * il;
3087    const uint16_t* sc = (const uint16_t*) x[ibs].scales;
3088    iq1m_scale_t scale;
3089    scale.u16 = (sc[0] >> 12) | ((sc[1] >> 8) & 0x00f0) | ((sc[2] >> 4) & 0x0f00) | (sc[3] & 0xf000);
3090    const int64_t ib16 = 2 * ib + il / 2;
3091    const float d = (float) scale.f16 * (2 * ((sc[ib16 / 4] >> 3 * (ib16 % 4)) & 0x7) + 1);
3092    const float delta = x[ibs].qh[2 * ib + il / 2] & (0x08 << 4 * (il % 2)) ? -1 - IQ1M_DELTA : -1 + IQ1M_DELTA;
3093    uint32_t grid32[2];
3094    const int8_t* q = (const int8_t*) grid32;
3095    grid32[0] = iq1s_grid_gpu[x[ibs].qs[4 * ib + il] | (((x[ibs].qh[2 * ib + il / 2] >> 4 * (il % 2)) & 7) << 8)];
3096    grid32[1] = (grid32[0] >> 4) & 0x0f0f0f0f;
3097    grid32[0] &= 0x0f0f0f0f;
3098    for (int j = 0; j < 8; ++j) y[j] = cvt<dst_t>(d * (q[j] + delta));
3099}
3100template<typename dst_t>
3101__device__ void dq_iq4_nl(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3102    const block_iq4_nl* x = (const block_iq4_nl*) vx + ibs * (QK_K / QK4_NL);
3103    const int64_t il = tid / 8, ib = tid % 8;
3104    dst_t* y = yy + 32 * ib + 4 * il;
3105    const uint8_t* q4 = x[ib].qs + 4 * il;
3106    const float d = (float) x[ib].d;
3107    for (int j = 0; j < 4; ++j) {
3108        y[j + 0] = cvt<dst_t>(d * kvalues_iq4nl[q4[j] & 0xf]);
3109        y[j + 16] = cvt<dst_t>(d * kvalues_iq4nl[q4[j] >> 4]);
3110    }
3111}
3112// Q3_K (the Q2_0 file's token_embd): llama.cpp's dequantize_block_q3_K, its 64 threads folded onto 32
3113template<typename dst_t>
3114__device__ void dq_q3_k(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3115    const block_q3_K* x = (const block_q3_K*) vx + ibs;
3116    for (int tt = tid; tt < 64; tt += 32) {
3117        const int r = tt / 4, t2 = r / 2, is0 = r % 2;
3118        const int l0 = 16 * is0 + 4 * (tt % 4);
3119        const int n = t2 / 4, j = t2 - 4 * n;
3120        const uint8_t m = (uint8_t) (1 << (4 * n + j));
3121        const int is = 8 * n + 2 * j + is0;
3122        const int shift = 2 * j;
3123        const int8_t us = is < 4  ? (int8_t) ((x->scales[is - 0] & 0xF) | (((x->scales[is + 8] >> 0) & 3) << 4)) :
3124                          is < 8  ? (int8_t) ((x->scales[is - 0] & 0xF) | (((x->scales[is + 4] >> 2) & 3) << 4)) :
3125                          is < 12 ? (int8_t) ((x->scales[is - 8] >> 4) | (((x->scales[is + 0] >> 4) & 3) << 4)) :
3126                                    (int8_t) ((x->scales[is - 8] >> 4) | (((x->scales[is - 4] >> 6) & 3) << 4));
3127        const float dl = (float) x->d * (us - 32);
3128        dst_t* y = yy + 128 * n + 32 * j;
3129        const uint8_t* q = x->qs + 32 * n;
3130        const uint8_t* hm = x->hmask;
3131        for (int l = l0; l < l0 + 4; ++l) y[l] = cvt<dst_t>(dl * ((int8_t) ((q[l] >> shift) & 3) - ((hm[l] & m) ? 0 : 4)));
3132    }
3133}
3134template<typename dst_t>
3135__device__ void dq_iq4_xs(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3136    const block_iq4_xs* x = (const block_iq4_xs*) vx + ibs;
3137    const int il = tid / 8, ib = tid % 8;
3138    dst_t* y = yy + 32 * ib + 4 * il;
3139    const uint8_t* q4 = x->qs + 16 * ib + 4 * il;
3140    const float d = (float) x->d * ((((x->scales_l[ib / 2] >> 4 * (ib % 2)) & 0xf) | (((x->scales_h >> 2 * ib) & 3) << 4)) - 32);
3141    for (int j = 0; j < 4; ++j) {
3142        y[j + 0] = cvt<dst_t>(d * kvalues_iq4nl[q4[j] & 0xf]);
3143        y[j + 16] = cvt<dst_t>(d * kvalues_iq4nl[q4[j] >> 4]);
3144    }
3145}
3146template<typename dst_t>
3147__device__ void dq_q2_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3148    // one "superblock" = 256 values = 4 blocks of 64; thread tid writes 8 values
3149    const block_q2_0* x = (const block_q2_0*) vx + ibs * 4;
3150    const int b = tid / 8, part = tid % 8;          // block 0..3, 8 values each
3151    const float d = (float) x[b].d;
3152    for (int j = 0; j < 8; ++j) {
3153        const int i = part * 8 + j;
3154        const int code = (x[b].qs[i / 4] >> ((i % 4) * 2)) & 3;
3155#if defined(__HIPCC__)
3156        // HIP compilers fold the half path's negative scale times +0 to +0 (HIP 5.7 on gfx1012, gfx1151 on ROCm
3157        // 7.13 - PR #895, gfx1200/gfx1201 on ROCm 7.10 - #1474); the gating arch list only ever chased the newest
3158        // report (#1540).  Preserve the scale's sign, as the FP32/CPU paths do: value-identical where the fold never happens.
3159        if constexpr (std::is_same_v<dst_t, __half>) {
3160            if (code == 1) {
3161                yy[b * 64 + i] = __ushort_as_half(__half_as_ushort(x[b].d) & 0x8000u);
3162                continue;
3163            }
3164        }
3165#endif
3166        yy[b * 64 + i] = cvt<dst_t>(d * (float) (code - 1));
3167    }
3168}
3169
3170// llama.cpp's dequantize_q4_K / dequantize_q5_K (dequantize.cuh; q5_K's 64 threads folded onto 32) and the 32-value
3171// blocks of Q5_1 / Q8_0, 8 of them per 256-value "superblock" (thread tid writes 8 values of block tid % 8).
3172__device__ __forceinline__ void get_scale_min_k4(int j, const uint8_t* q, uint8_t& d, uint8_t& m) {
3173    if (j < 4) {
3174        d = q[j] & 63; m = q[j + 4] & 63;
3175    } else {
3176        d = (q[j + 4] & 0xF) | ((q[j - 4] >> 6) << 4);
3177        m = (q[j + 4] >> 4) | ((q[j - 0] >> 6) << 4);
3178    }
3179}
3180template<typename dst_t>
3181__device__ void dq_q4_k(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3182    const block_q4_K* x = (const block_q4_K*) vx;
3183    const int64_t il = tid / 8, ir = tid % 8, is = 2 * il;
3184    const int n = 4;
3185    dst_t* y = yy + 64 * il + n * ir;
3186    const float dall = __low2half(x[ibs].dm);
3187    const float dmin = __high2half(x[ibs].dm);
3188    const uint8_t* q = x[ibs].qs + 32 * il + n * ir;
3189    uint8_t sc, m;
3190    get_scale_min_k4((int) is + 0, x[ibs].scales, sc, m);
3191    const float d1 = dall * sc, m1 = dmin * m;
3192    get_scale_min_k4((int) is + 1, x[ibs].scales, sc, m);
3193    const float d2 = dall * sc, m2 = dmin * m;
3194    for (int l = 0; l < n; ++l) {
3195        y[l + 0] = cvt<dst_t>(d1 * (q[l] & 0xF) - m1);
3196        y[l + 32] = cvt<dst_t>(d2 * (q[l] >> 4) - m2);
3197    }
3198}
3199template<typename dst_t>
3200__device__ void dq_q5_k(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3201    const block_q5_K* x = (const block_q5_K*) vx;
3202    for (int tt = tid; tt < 64; tt += 32) {
3203        const int il = tt / 16, ir = tt % 16, is = 2 * il;
3204        dst_t* y = yy + 64 * il + 2 * ir;
3205        const float dall = __low2half(x[ibs].dm);
3206        const float dmin = __high2half(x[ibs].dm);
3207        const uint8_t* ql = x[ibs].qs + 32 * il + 2 * ir;
3208        const uint8_t* qh = x[ibs].qh + 2 * ir;
3209        uint8_t sc, m;
3210        get_scale_min_k4(is + 0, x[ibs].scales, sc, m);
3211        const float d1 = dall * sc, m1 = dmin * m;
3212        get_scale_min_k4(is + 1, x[ibs].scales, sc, m);
3213        const float d2 = dall * sc, m2 = dmin * m;
3214        uint8_t hm = (uint8_t) (1 << (2 * il));
3215        y[0] = cvt<dst_t>(d1 * ((ql[0] & 0xF) + (qh[0] & hm ? 16 : 0)) - m1);
3216        y[1] = cvt<dst_t>(d1 * ((ql[1] & 0xF) + (qh[1] & hm ? 16 : 0)) - m1);
3217        hm <<= 1;
3218        y[32] = cvt<dst_t>(d2 * ((ql[0] >> 4) + (qh[0] & hm ? 16 : 0)) - m2);
3219        y[33] = cvt<dst_t>(d2 * ((ql[1] >> 4) + (qh[1] & hm ? 16 : 0)) - m2);
3220    }
3221}
3222template<typename dst_t>
3223__device__ void dq_q5_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3224    // symmetric: one delta (no min), the high bit folded in then centered by the format's fixed -16 offset
3225    const block_q5_0* x = (const block_q5_0*) vx + ibs * (QK_K / QK5_0);
3226    const int ib = tid % 8, il = tid / 8;
3227    const float d = __half2float(x[ib].d);
3228    uint32_t qh;
3229    memcpy(&qh, x[ib].qh, sizeof(qh));
3230    dst_t* y = yy + 32 * ib;
3231    for (int j = 0; j < 4; ++j) {
3232        const int iqs = 4 * il + j;
3233        const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
3234        const int xh_1 = ((qh >> (iqs + 12))) & 0x10;
3235        y[iqs] = cvt<dst_t>(((float) ((x[ib].qs[iqs] & 0xf) | xh_0) - 16.0f) * d);
3236        y[iqs + 16] = cvt<dst_t>(((float) ((x[ib].qs[iqs] >> 4) | xh_1) - 16.0f) * d);
3237    }
3238}
3239template<typename dst_t>
3240__device__ void dq_q4_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3241    const block_q4_0* x = (const block_q4_0*) vx + ibs * (QK_K / QK4_0);
3242    const int ib = tid % 8, il = tid / 8;
3243    const float d = __half2float(x[ib].d);
3244    dst_t* y = yy + 32 * ib;
3245    for (int j = 0; j < 4; ++j) {
3246        const int iqs = 4 * il + j;                   // llama.cpp's dequantize_q4_0 for value pairs iqs, iqs + 16
3247        y[iqs] = cvt<dst_t>(((float) (x[ib].qs[iqs] & 0xf) - 8.0f) * d);
3248        y[iqs + 16] = cvt<dst_t>(((float) (x[ib].qs[iqs] >> 4) - 8.0f) * d);
3249    }
3250}
3251template<typename dst_t>
3252__device__ void dq_q4_1(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3253    const block_q4_1* x = (const block_q4_1*) vx + ibs * (QK_K / QK4_1);
3254    const int ib = tid % 8, il = tid / 8;
3255    const float2 dm = __half22float2(x[ib].dm);
3256    dst_t* y = yy + 32 * ib;
3257    for (int j = 0; j < 4; ++j) {
3258        const int iqs = 4 * il + j;                   // llama.cpp's dequantize_q4_1 for value pairs iqs, iqs + 16
3259        y[iqs] = cvt<dst_t>((float) (x[ib].qs[iqs] & 0xf) * dm.x + dm.y);
3260        y[iqs + 16] = cvt<dst_t>((float) (x[ib].qs[iqs] >> 4) * dm.x + dm.y);
3261    }
3262}
3263template<typename dst_t>
3264__device__ void dq_q5_1(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3265    const block_q5_1* x = (const block_q5_1*) vx + ibs * (QK_K / QK5_1);
3266    const int ib = tid % 8, il = tid / 8;
3267    const float2 dm = __half22float2(x[ib].dm);
3268    uint32_t qh;
3269    memcpy(&qh, x[ib].qh, sizeof(qh));
3270    dst_t* y = yy + 32 * ib;
3271    for (int j = 0; j < 4; ++j) {
3272        const int iqs = 4 * il + j;                   // llama.cpp's dequantize_q5_1 for value pairs iqs, iqs + 16
3273        const int xh_0 = ((qh >> (iqs + 0)) << 4) & 0x10;
3274        const int xh_1 = ((qh >> (iqs + 12))) & 0x10;
3275        y[iqs] = cvt<dst_t>((float) ((x[ib].qs[iqs] & 0xf) | xh_0) * dm.x + dm.y);
3276        y[iqs + 16] = cvt<dst_t>((float) ((x[ib].qs[iqs] >> 4) | xh_1) * dm.x + dm.y);
3277    }
3278}
3279template<typename dst_t>
3280__device__ void dq_q6_k(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3281    // llama.cpp's dequantize_q6_K (dequantize.cuh, written for 64 threads) folded onto the kernel's 32: each of the
3282    // 64 thread roles runs at tid and tid + 32.
3283    const block_q6_K* x = (const block_q6_K*) vx;
3284    for (int tt = tid; tt < 64; tt += 32) {
3285        const int64_t ip = tt / 32;                 // 0 or 1
3286        const int64_t il = tt - 32 * ip;            // 0...31
3287        const int64_t is = 8 * ip + il / 16;
3288        dst_t* y = yy + 128 * ip + il;
3289        const float d = __half2float(x[ibs].d);
3290        const uint8_t* ql = x[ibs].ql + 64 * ip + il;
3291        const uint8_t qh = x[ibs].qh[32 * ip + il];
3292        const int8_t* sc = x[ibs].scales + is;
3293        y[0]  = cvt<dst_t>(d * sc[0] * ((int8_t) ((ql[0]  & 0xF) | (((qh >> 0) & 3) << 4)) - 32));
3294        y[32] = cvt<dst_t>(d * sc[2] * ((int8_t) ((ql[32] & 0xF) | (((qh >> 2) & 3) << 4)) - 32));
3295        y[64] = cvt<dst_t>(d * sc[4] * ((int8_t) ((ql[0]  >> 4) | (((qh >> 4) & 3) << 4)) - 32));
3296        y[96] = cvt<dst_t>(d * sc[6] * ((int8_t) ((ql[32] >> 4) | (((qh >> 6) & 3) << 4)) - 32));
3297    }
3298}
3299template<typename dst_t>
3300__device__ void dq_q8_0(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3301    const block_q8_0* x = (const block_q8_0*) vx + ibs * (QK_K / QK8_0);
3302    const int ib = tid % 8, il = tid / 8;
3303    const float d = __half2float(x[ib].d);
3304    dst_t* y = yy + 32 * ib + 8 * il;
3305    for (int j = 0; j < 8; ++j) y[j] = cvt<dst_t>((float) x[ib].qs[8 * il + j] * d);
3306}
3307
3308// BF16 (the token embedding as the checkpoint ships it, tools/embd_bf16_pack.py): 8 values per thread.
3309template<typename dst_t>
3310__device__ void dq_bf16(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3311    const uint16_t* x = (const uint16_t*) vx + ibs * 256 + tid * 8;
3312    for (int j = 0; j < 8; ++j) yy[tid * 8 + j] = cvt<dst_t>(__uint_as_float((uint32_t) x[j] << 16));
3313}
3314
3315// NVFP4: one "superblock" = 256 values = 4 blocks of 64; thread tid writes 8 values of block tid / 8.
3316// Sub-block s (16 values) keeps its codes in qs[8 s .. 8 s + 7]: byte j = value j (low nibble) and j + 8 (high).
3317template<typename dst_t>
3318__device__ void dq_nvfp4(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3319    const block_nvfp4* x = (const block_nvfp4*) vx + ibs * 4;
3320    const int b = tid / 8, part = tid % 8;
3321    for (int j = 0; j < 8; ++j) {
3322        const int i = part * 8 + j, s = i / 16, k = i % 16;
3323        const uint8_t byte = x[b].qs[s * 8 + (k & 7)];
3324        const int code = k < 8 ? (byte & 0x0F) : (byte >> 4);
3325        yy[b * 64 + i] = cvt<dst_t>((float) kvalues_fp4[code] * ue4m3_to_f32_half(x[b].d[s]));
3326    }
3327}
3328
3329// APR trellis types: one 256-value call = two 128-blocks; thread tid decodes block tid/16, lane (tid/2)%8, steps
3330// 2(tid%2)..2(tid%2)+1 (8 values)
3331template<int TY, typename dst_t>
3332__device__ void dq_tq(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3333    const int blk = tid >> 4, l = (tid >> 1) & 7, half = tid & 1;
3334    const auto* b = (const typename TqInfo<TY>::block_t*) vx + 2 * ibs + blk;
3335    const float d = tq_h2f(b->d);
3336    uint32_t s[4];
3337    tq_states4<TY>(b->qs, l, s);
3338    dst_t* y = yy + blk * 128 + 16 * l + 8 * half;
3339#pragma unroll
3340    for (int i = 0; i < 2; ++i) {
3341        float2 a, c;
3342        tq_step(s[2 * half + i], a, c);
3343        y[4 * i + 0] = cvt<dst_t>(d * a.x);
3344        y[4 * i + 1] = cvt<dst_t>(d * a.y);
3345        y[4 * i + 2] = cvt<dst_t>(d * c.x);
3346        y[4 * i + 3] = cvt<dst_t>(d * c.y);
3347    }
3348}
3349
3350// TQP (Gyro-L): pair trellis; the step's 2 weights are the first pair of TQ2_T state s.
3351__device__ __forceinline__ float2 tqp_pair(uint32_t s) {
3352    const uint32_t* lut = (const uint32_t*) tq_lut_f16;
3353    const uint32_t x = (s & TQ_STATE_MASK) * 0x9e3779b1u;
3354    const uint32_t pa = lut[x >> 21];
3355    return make_float2(tq_h2f(pa & 0xFFFFu), tq_h2f(pa >> 16));
3356}
3357// one 256-value call = two 128-blocks; thread tid decodes block tid/16, lane (tid>>1)&7, steps
3358// 8*l + 4*half .. +3 (8 values, 2 per step)
3359template<int TY, typename dst_t>
3360__device__ void dq_tqp(const void* vx, int64_t ibs, dst_t* yy, int tid) {
3361    const int blk = tid >> 4, l = (tid >> 1) & 7, half = tid & 1;
3362    const auto* b = (const typename TqInfo<TY>::block_t*) vx + 2 * ibs + blk;
3363    const float d = tq_h2f(b->d);
3364    uint32_t s[8];
3365    tqp_states8_cheap<TY>(b->qs, l, s);
3366    dst_t* y = yy + blk * 128 + 16 * l + 8 * half;
3367#pragma unroll
3368    for (int i = 0; i < 4; ++i) {
3369        const float2 a = tqp_pair(s[4 * half + i]);
3370        y[2 * i + 0] = cvt<dst_t>(d * a.x);
3371        y[2 * i + 1] = cvt<dst_t>(d * a.y);
3372    }
3373}
3374
3375// Every type below must also be in is_iq() (BF16: embed_type_supported): the host entry points refuse the others,
3376// so the default is unreachable.
3377template<typename dst_t>
3378__device__ __forceinline__ void dq_dispatch(int ty, const void* vx, int64_t ibs, dst_t* y, int tid) {
3379    switch (ty) {
3380        case 16: dq_iq2_xxs(vx, ibs, y, tid); break;
3381        case 17: dq_iq2_xs(vx, ibs, y, tid); break;
3382        case 18: dq_iq3_xxs(vx, ibs, y, tid); break;
3383        case 20: dq_iq4_nl(vx, ibs, y, tid); break;
3384        case 21: dq_iq3_s(vx, ibs, y, tid); break;
3385        case 22: dq_iq2_s(vx, ibs, y, tid); break;
3386        case 29: dq_iq1_m(vx, ibs, y, tid); break;
3387        case 23: dq_iq4_xs(vx, ibs, y, tid); break;
3388        case 11: dq_q3_k(vx, ibs, y, tid); break;
3389        case 42: dq_q2_0(vx, ibs, y, tid); break;
3390        case 12: dq_q4_k(vx, ibs, y, tid); break;
3391        case 13: dq_q5_k(vx, ibs, y, tid); break;
3392        case 14: dq_q6_k(vx, ibs, y, tid); break;   // the Q6K_EXPERTS kernels, and the token embedding (Gyro-S)
3393        case 7: dq_q5_1(vx, ibs, y, tid); break;
3394        case 6: dq_q5_0(vx, ibs, y, tid); break;
3395        case 2: dq_q4_0(vx, ibs, y, tid); break;
3396        case 3: dq_q4_1(vx, ibs, y, tid); break;
3397        case 40: dq_nvfp4(vx, ibs, y, tid); break;
3398        case 8: dq_q8_0(vx, ibs, y, tid); break;
3399        case 30: dq_bf16(vx, ibs, y, tid); break;
3400        case 144: dq_tq<144>(vx, ibs, y, tid); break;
3401        case 145: dq_tq<145>(vx, ibs, y, tid); break;
3402        case 146: dq_tq<146>(vx, ibs, y, tid); break;
3403        case 147: dq_tqp<147>(vx, ibs, y, tid); break;
3404        case 148: dq_tqp<148>(vx, ibs, y, tid); break;
3405        case 149: dq_tqp<149>(vx, ibs, y, tid); break;
3406        default: break;
3407    }
3408}
3409
3410// flat: superblock i -> y + 256 i
3411template<typename dst_t>
3412__global__ void dequant_flat_kernel(int ty, const void* __restrict__ vx, dst_t* __restrict__ y,
3413                                    const float* __restrict__ scale) {
3414    const int64_t i = blockIdx.x;
3415    dq_dispatch<dst_t>(ty, vx, i, y + i * QK_K, threadIdx.x);
3416    if (scale != nullptr) {       // NVFP4 down: s_down (the weights stay in FP16's normal range)
3417        __syncwarp();
3418        const float sc = *scale;
3419        for (int k = 0; k < 8; ++k) {
3420            const int j = threadIdx.x * 8 + k;
3421            y[i * QK_K + j] = cvt<dst_t>((float) y[i * QK_K + j] * sc);
3422        }
3423    }
3424}
3425// gate/up: superblock i of a role matrix (n_embd/256 per row) -> interleaved row 2r + parity
3426__global__ void dequant_gu_kernel(int ty, const void* __restrict__ gate, const void* __restrict__ up, int64_t per_row,
3427                                  __half* __restrict__ y, const float* __restrict__ tail) {
3428    const int64_t i = blockIdx.x;
3429    const int parity = blockIdx.y;
3430    const int64_t r = i / per_row, c = i % per_row;
3431    __half* dst = y + ((2 * r + parity) * per_row + c) * QK_K;
3432    dq_dispatch<__half>(ty, parity ? up : gate, i, dst, threadIdx.x);
3433    if (tail != nullptr) {        // NVFP4: gate * s_gate, up * s_up (s_down on the down output: FP16 would underflow)
3434        __syncwarp();
3435        const float sc = parity ? tail[1] : tail[0];
3436        for (int k = 0; k < 8; ++k) {
3437            const int j = threadIdx.x * 8 + k;
3438            dst[j] = __float2half(__half2float(dst[j]) * sc);
3439        }
3440    }
3441}
3442
3443// the types dq_dispatch dequantizes
3444bool is_iq(int t) {
3445    return t == 16 || t == 17 || t == 18 || t == 20 || t == 21 || t == 22 || t == 23 || t == 29 || t == 42 || t == 11 ||
3446#ifdef STRATA_Q6K_EXPERTS
3447           t == 12 || t == 13 || t == 14 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40 || t == 144 || t == 145 || t == 146 || t == 147 || t == 148 || t == 149;
3448#else
3449           t == 12 || t == 13 || t == 7 || t == 6 || t == 2 || t == 3 || t == 8 || t == 40 || t == 144 || t == 145 || t == 146 || t == 147 || t == 148 || t == 149;
3450#endif
3451}
3452// values per block of the types the grouped expert kernels take (0 = none)
3453int gu_qk(int t) {
3454    switch (t) {
3455#define STRATA_QK(T) case T: return Fmt<T>::qk;
3456        STRATA_GU_FMTS(STRATA_QK)
3457#undef STRATA_QK
3458        default: return 0;
3459    }
3460}
3461int d_qk(int t) {
3462    switch (t) {
3463#define STRATA_QK(T) case T: return Fmt<T>::qk;
3464        STRATA_D_FMTS(STRATA_QK)
3465#undef STRATA_QK
3466        default: return 0;
3467    }
3468}
3469bool gu_split(int t) {
3470    switch (t) {
3471#define STRATA_SP(T) case T: return kSplit<T> && !split_off<T>();
3472        STRATA_GU_FMTS(STRATA_SP)
3473#undef STRATA_SP
3474        default: return false;
3475    }
3476}
3477
3478bool env_on(const char* name) {
3479    const char* v = std::getenv(name);
3480    return v != nullptr && v[0] != '\0' && v[0] != '0';
3481}
3482// STRATA_OLD_IQ_MMVQ=1 keeps the per-column kernels (bitwise equal to the new ones; kept for A/B timing)
3483bool g_old_kernels = env_on("STRATA_OLD_IQ_MMVQ");
3484bool g_no_sub16_gu = env_on("STRATA_NO_SUB16_GU");
3485// STRATA_IQ_STAGE_GRID=0 disables staging 64-bit i-quant codebook tables into shared memory
3486bool g_stage_grid = [] {
3487    const char* v = std::getenv("STRATA_IQ_STAGE_GRID");
3488    return v == nullptr || v[0] == '\0' || v[0] != '0';
3489}();
3490// The single-matrix mmvq (128-thread blocks, one per 4 rows) pays the 2-8 KB staging per block: on the RTX 5070 its
3491// IQ2_XS / IQ2_S / IQ1_M calls were 10-20% slower staged at 3-8 columns (iq_multi_parity --bench), while the grouped
3492// expert kernels gain.  So mmvq stages only with STRATA_IQ_STAGE_GRID_MMVQ=1 (bitwise the same either way).
3493bool g_stage_grid_mmvq = g_stage_grid && [] {
3494    const char* v = std::getenv("STRATA_IQ_STAGE_GRID_MMVQ");
3495    return v != nullptr && v[0] == '1';
3496}();
3497// IQ3_XXS's and IQ3_S's codebooks and sign-mask tables staged in shared memory by the grouped expert kernels (the
3498// single-matrix mmvq does not): bitwise the same either way.  OPT-IN: STRATA_IQ_STAGE_TABLES=1.  The PR (#1424) made it
3499// the default on compute capability 6.0 (GP100: no __dp4a, these kernels decode-bound at 70-140 GB/s); on a Tesla P100
3500// (IQ3_XXS and IQ3_S packs, 5-6 interleaved pairs each) the decode was 0.97-1.03x of the unstaged kernels, noise, so
3501// it is not on by default.  On an RTX 3090 Ti, forced on, the IQ3_S layers took 3-13% longer.
3502bool stage_tables_on() {
3503    if (!g_stage_grid) return false;
3504    static const bool on = [] {
3505        const char* v = std::getenv("STRATA_IQ_STAGE_TABLES");
3506        return v && v[0] && v[0] != '0';
3507    }();
3508    return on;
3509}
3510
3511// The trellis types (Gyro: TQ2_T / TQK6 / TQK7) read a 4 KB int8 codebook with 8 random lookups per 16 weights.  The
3512// grouped expert kernels stage it in shared memory on compute capability 6.0 (Tesla P100: no dp4a, ~28 ALU ops per
3513// weight in the decode, the global lookups are replayed per distinct line) and leave it in global memory elsewhere
3514// (the newer cards' L1 absorbs it).  STRATA_TQ_STAGE=1 / 0 forces it either way; bitwise the same result both ways.
3515bool tq_stage_on() {
3516    static const int env = [] { const char* v = std::getenv("STRATA_TQ_STAGE"); return v != nullptr && v[0] != '\0' ? (v[0] != '0' ? 1 : 0) : -1; }();
3517    if (env >= 0) return env == 1 && g_stage_grid;
3518#if defined(__HIPCC__)
3519    return false;
3520#else
3521    if (!g_stage_grid) return false;
3522    static int per_dev[64];   // 0 unknown, 1 no, 2 yes
3523    int dev = 0;
3524    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
3525    if (!per_dev[dev]) {
3526        int maj = 0, mnr = 0;
3527        const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
3528                        cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
3529        if (!ok) cudaGetLastError();
3530        per_dev[dev] = ok && maj * 10 + mnr < 61 ? 2 : 1;
3531    }
3532    return per_dev[dev] == 2;
3533#endif
3534}
3535// Everywhere but cc 6.0 (tq_stage_on) the trellis kernels stage the codebook too, and the 160-dot gate/up rows are 8-lane rows (4 per
3536// warp, 32 per block, row_dot_160_sub8) while the down rows are the staged 8-lane rows above: on an RTX 3060 (Gyro-M, 24 groups of one
3537// token) gate/up 221 -> 140 us and down 182 -> 86 us.  Bitwise the same sums as before.  STRATA_TQ_STAGE=0 or STRATA_TQ_SUB8=0 turn it off
3538// (CUDA only: the AMD builds keep the old kernels), STRATA_IQ_STAGE_GRID=0 as for every staged table.
3539bool tq_sub8_on() {
3540#if defined(__HIPCC__)
3541    return false;
3542#else
3543    static const bool on = [] {
3544        const char* v = std::getenv("STRATA_TQ_STAGE");
3545        if (v != nullptr && v[0] == '0') return false;
3546        v = std::getenv("STRATA_TQ_SUB8");
3547        return !(v != nullptr && v[0] == '0');
3548    }();
3549    return on && g_stage_grid && !g_no_sub16_gu && !tq_stage_on();
3550#endif
3551}
3552// row chunks per block of the staged trellis gate/up and down kernels (STRATA_TQ_ROWCH, default 4)
3553int tq_row_chunks() {
3554    static const int n = [] {
3555        const char* v = std::getenv("STRATA_TQ_ROWCH");
3556        const int k = v != nullptr ? std::atoi(v) : 4;
3557        return k < 1 ? 1 : k > 32 ? 32 : k;
3558    }();
3559    return n;
3560}
3561
3562template<int TY, bool STAGE_GRID = kStageIqGrid<TY>>
3563void launch_mmvq_multi_nc(dim3 grid, dim3 block, cudaStream_t s, const uint8_t* W, size_t rb, const block_q8_1* X,
3564                          float* y, int n_in, int n_out, int ncols) {
3565    switch (ncols) {
3566        case 1: mmvq_multi_kernel<TY, 1, STAGE_GRID, true><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, 1); break;
3567        case 2: mmvq_multi_kernel<TY, 2, STAGE_GRID, true><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, 2); break;
3568        case 3: mmvq_multi_kernel<TY, 3, STAGE_GRID, true><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, 3); break;
3569        case 4: mmvq_multi_kernel<TY, 4, STAGE_GRID, true><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, 4); break;
3570        case 5: mmvq_multi_kernel<TY, 5, STAGE_GRID, true><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, 5); break;
3571        case 6: mmvq_multi_kernel<TY, 6, STAGE_GRID, true><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, 6); break;
3572        default:
3573            if (ncols <= 1) mmvq_multi_kernel<TY, 1, STAGE_GRID, false><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);
3574            else mmvq_multi_kernel<TY, 8, STAGE_GRID, false><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);
3575            break;
3576    }
3577}
3578
3579template<int TY>
3580void launch_mmvq(const uint8_t* W, size_t rb, const block_q8_1* X, float* y, int n_in, int n_out, int ncols,
3581                 cudaStream_t s) {
3582    const dim3 grid((unsigned) ((n_out + 3) / 4)), block(32, 4);
3583    if constexpr (!kSplit<TY>) mmvq_kernel<TY><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);
3584    else if (g_old_kernels || split_off<TY>()) mmvq_kernel<TY><<<grid, block, 0, s>>>(W, rb, X, y, n_in, n_out, ncols);
3585    else if constexpr (kStageIqGrid<TY>) {
3586        if (!g_stage_grid_mmvq) {
3587            launch_mmvq_multi_nc<TY, false>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);
3588            return;
3589        }
3590        launch_mmvq_multi_nc<TY, true>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);
3591    } else {
3592        launch_mmvq_multi_nc<TY, false>(grid, block, s, W, rb, X, y, n_in, n_out, ncols);
3593    }
3594}
3595
3596
3597// ---------------------------------------------------------------- S26 STRATA_EXPERT_V2=1 (opt-in): IQ3_S gate/up + IQ4_NL down
3598// Bitwise equal to native_gu_multi_kernel / native_down_multi_kernel (S26 harness, real UD-IQ4_XS expert blobs, T 1-3,
3599// memcmp of every output): each row's lane sums and warp_sum are the same; a warp interleaves RPW rows (more loads in
3600// flight) and reads the chunk's activation rows from LDS and, for IQ3_S, the grid table from LDS (the same values).
3601#if defined(__HIPCC__)
3602#define STRATA_NT_LOAD(p) __builtin_nontemporal_load(p)
3603#else   // (opt-in S26 kernels, AMD-tuned: a CUDA build compiles them with plain loads)
3604#define STRATA_NT_LOAD(p) (*(p))
3605#endif
3606template<bool NT> __device__ __forceinline__ int ld16i(const uint16_t* p) {
3607    if constexpr (NT) return (int) STRATA_NT_LOAD(p); else return (int) *p;
3608}
3609template<bool NT> __device__ __forceinline__ int ldb2(const void* x, int i32) {
3610    const uint16_t* x16 = (const uint16_t*) x;
3611    int x32 = ld16i<NT>(x16 + 2 * i32 + 0) << 0;
3612    x32 |= ld16i<NT>(x16 + 2 * i32 + 1) << 16;
3613    return x32;
3614}
3615template<bool NT> __device__ __forceinline__ int ld8i(const uint8_t* p) {
3616    if constexpr (NT) return (int) STRATA_NT_LOAD(p); else return (int) *p;
3617}
3618template<bool NT> __device__ __forceinline__ float ldhalf(const half* p) {
3619    return __half2float(__ushort_as_half((unsigned short) ld16i<NT>(reinterpret_cast<const uint16_t*>(p))));
3620}
3621template<int TY, bool NT> struct S26Split;
3622template<bool NT> struct S26Split<21, NT> {   // IQ3_S: Split<21>::load with the loads made explicit
3623    using W = Split<21>::W;
3624    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
3625        const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
3626        const int2 qs_packed = make_int2(ldb2<NT>(bq3->qs, iqs + 0), ldb2<NT>(bq3->qs, iqs + 1));
3627        const uint8_t* qs = (const uint8_t*) &qs_packed;
3628        const int qh = ld8i<NT>(bq3->qh + iqs / 2);
3629        const int signs_packed_32 = ldb2<NT>(bq3->signs, iqs / 2);
3630        const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
3631        W r;
3632#pragma unroll
3633        for (int l0 = 0; l0 < 8; l0 += 2) {
3634            const int2 grid_pos = make_int2(iq3s_grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
3635                                            iq3s_grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
3636            const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
3637            const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
3638            r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
3639            r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
3640        }
3641        r.ls = 1 + 2 * ((ld8i<NT>(bq3->scales + iqs / 4) >> ((iqs << 1) & 0x04)) & 0x0F);
3642        r.dw = ldhalf<NT>(&bq3->d);
3643        return r;
3644    }
3645    __device__ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<21>::apply(r, b, iqs); }
3646};
3647template<bool NT> struct S26Split<20, NT> {   // IQ4_NL
3648    using W = Split<20>::W;
3649    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs) {
3650        const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;
3651        W r;
3652#pragma unroll
3653        for (int l = 0; l < 2; ++l) r.v[l] = get_int_from_table_16(ldb2<NT>(bq4->qs, iqs + l), kvalues_iq4nl);
3654        r.dw = ldhalf<NT>(&bq4->d);
3655        return r;
3656    }
3657    __device__ static float apply(const W& r, const block_q8_1* __restrict__ b, int iqs) { return Split<20>::apply(r, b, iqs); }
3658};
3659
3660// S26 v13+: v6 (4 interleaved rows per warp) with the IQ3_S grid table (LT) and / or the chunk's activation rows (LX)
3661// read from LDS: the same table values and the same q8_1 bytes, so the same arithmetic and bits.
3662struct S26IQ3S {   // Split<21>::load with the grid from `grid` (LT) or iq3s_grid itself
3663    using W = Split<21>::W;
3664    template<bool LT = true>
3665    __device__ static W load(const void* __restrict__ vbq, int kbx, int iqs, const uint32_t* grid) {
3666        const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
3667        const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
3668        const uint8_t* qs = (const uint8_t*) &qs_packed;
3669        const int qh = bq3->qh[iqs / 2];
3670        const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
3671        const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
3672        W r;
3673#pragma unroll
3674        for (int l0 = 0; l0 < 8; l0 += 2) {
3675            const int i0 = qs[l0 + 0] | ((qh << (8 - l0)) & 0x100), i1 = qs[l0 + 1] | ((qh << (7 - l0)) & 0x100);
3676            const int2 grid_pos = LT ? make_int2(grid[i0], grid[i1]) : make_int2(iq3s_grid[i0], iq3s_grid[i1]);
3677            const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
3678            const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
3679            r.g[l0 + 0] = __vsub4(grid_pos.x ^ signs0, signs0);
3680            r.g[l0 + 1] = __vsub4(grid_pos.y ^ signs1, signs1);
3681        }
3682        r.ls = 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
3683        r.dw = __half2float(bq3->d);
3684        return r;
3685    }
3686};
3687
3688constexpr int S26_XMAX = 2560 / 32;   // q8_1 blocks of one activation row (n_embd 2560)
3689
3690// S26 BAL: step I of a warp's RPW x NI items (item p = 32 I + lane): rows QA / QB (lanes >= THR take QB)
3691template<int I, int NI, int RPW> struct S26Bal {
3692    static constexpr int P0 = 32 * I, QA = P0 / NI, QB0 = (P0 + 31) / NI, QB = QB0 < RPW ? QB0 : RPW - 1;
3693    static constexpr int THR = (QA + 1) * NI - P0;
3694    static_assert(NI >= 32, "a step spans at most two rows");
3695};
3696
3697template<bool LT, bool LX, int RPW, bool SL = false, bool TS = false>
3698__global__ void __launch_bounds__(256) s26_gu_l_kernel(const unsigned long long* __restrict__ grp_ptr,
3699                                                       const int32_t* __restrict__ grp_start,
3700                                                       const int32_t* __restrict__ n_groups,
3701                                                       const int32_t* __restrict__ ent_tok,
3702                                                       const block_q8_1* __restrict__ xq, NativeExpertLayout L,
3703                                                       float* __restrict__ gate, float* __restrict__ up) {
3704    __shared__ uint32_t s_grid[LT ? 512 : 1];
3705    __shared__ block_q8_1 s_x[LX ? GRP_NC * S26_XMAX : 1];
3706    const int g = blockIdx.y;
3707    if (g >= *n_groups) return;
3708    if constexpr (LT)
3709        for (int i = threadIdx.x; i < 512; i += 256) s_grid[i] = iq3s_grid[i];
3710    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
3711    const int row0 = blockIdx.x * GU_ROWS * RPW + warp;
3712    const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff;
3713    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
3714    const uint8_t* wr[RPW];
3715    int rr[RPW];
3716    bool upq[RPW];
3717#pragma unroll
3718    for (int q = 0; q < RPW; ++q) {
3719        const int row = row0 + q * GU_ROWS;
3720        upq[q] = row >= L.n_ff;
3721        rr[q] = upq[q] ? row - (int) L.n_ff : row;
3722        wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row;
3723    }
3724    const uint32_t* grid = LT ? s_grid : reinterpret_cast<const uint32_t*>(iq3s_grid);
3725    const int nb = (int) (L.n_embd / 256), xb = (int) (L.n_embd / 32);
3726    const int e0 = grp_start[g], e1 = grp_start[g + 1];
3727    for (int e = e0; e < e1; e += GRP_NC) {
3728        const int n = min(GRP_NC, e1 - e);
3729        const block_q8_1* xbase = xq;
3730        int off[GRP_NC];
3731        if constexpr (LX) {
3732            __syncthreads();   // the previous chunk is done with s_x
3733            for (int i = threadIdx.x; i < n * xb; i += 256) {
3734                const int c = i / xb, j = i - c * xb;
3735                memcpy(&s_x[c * S26_XMAX + j], &xq[(size_t) ent_tok[e + c] * xb + j], sizeof(s_x[0]));
3736            }
3737#pragma unroll
3738            for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_XMAX;
3739            xbase = s_x;
3740        } else {
3741#pragma unroll
3742            for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb;
3743        }
3744        if constexpr (LT || LX) __syncthreads();   // s_grid / s_x ready
3745        if (!live) continue;
3746        float s[RPW][GRP_NC];
3747#pragma unroll
3748        for (int q = 0; q < RPW; ++q)
3749#pragma unroll
3750            for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;
3751        for (int k = lane; k < nb * 8; k += 32) {
3752            const int kbx = k / 8, iqs = 2 * (k % 8);
3753            Split<21>::W w[RPW];
3754#pragma unroll
3755            for (int q = 0; q < RPW; ++q) { if constexpr (SL && !LT) w[q] = S26Split<21, false>::load(wr[q], kbx, iqs); else w[q] = S26IQ3S::load<LT>(wr[q], kbx, iqs, grid); }
3756#pragma unroll
3757            for (int q = 0; q < RPW; ++q)
3758#pragma unroll
3759                for (int c = 0; c < GRP_NC; ++c)
3760                    if (c < n) s[q][c] += Split<21>::apply(w[q], xbase + off[c] + kbx * 8, iqs);
3761        }
3762        if constexpr (TS) {   // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums)
3763            constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);
3764            float v[P];
3765#pragma unroll
3766            for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;
3767            const float sum = s26ts::tsum<P>(v, lane);
3768            const int j = s26ts::tsum_token<P>(lane);
3769            if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC) {
3770                const int c = j % GRP_NC;
3771#pragma unroll
3772                for (int q = 0; q < RPW; ++q)
3773                    if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum;
3774            }
3775            continue;
3776        }
3777#pragma unroll
3778        for (int q = 0; q < RPW; ++q)
3779#pragma unroll
3780            for (int c = 0; c < GRP_NC; ++c)
3781                if (c < n) s[q][c] = warp_sum(s[q][c]);
3782#pragma unroll
3783        for (int q = 0; q < RPW; ++q)
3784#pragma unroll
3785            for (int c = 0; c < GRP_NC; ++c)
3786                if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c];
3787    }
3788}
3789
3790constexpr int S26_HMAX = 640 / 32;    // q8_1 blocks of one SwiGLU row (n_ff 640)
3791
3792template<bool LX, int RPW, bool SL = false, bool TS = false, int BAL = 0>
3793__global__ void __launch_bounds__(256) s26_down_l_kernel(const unsigned long long* __restrict__ grp_ptr,
3794                                                         const int32_t* __restrict__ grp_start,
3795                                                         const int32_t* __restrict__ n_groups,
3796                                                         const int32_t* __restrict__ ent_dst,
3797                                                         const block_q8_1* __restrict__ hq, NativeExpertLayout L,
3798                                                         float* __restrict__ out) {
3799    __shared__ block_q8_1 s_h[LX ? GRP_NC * S26_HMAX : 1];
3800    const int g = blockIdx.y;
3801    if (g >= *n_groups) return;
3802    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
3803    const int r0 = blockIdx.x * 8 * RPW + warp;
3804    const bool live = r0 + 8 * (RPW - 1) < L.n_embd;
3805    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
3806    const uint8_t* wr[RPW];
3807#pragma unroll
3808    for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row;
3809    const int nb = (int) (L.n_ff / 32), hb = (int) (L.n_ff / 32);
3810    const int e0 = grp_start[g], e1 = grp_start[g + 1];
3811    for (int e = e0; e < e1; e += GRP_NC) {
3812        const int n = min(GRP_NC, e1 - e);
3813        const block_q8_1* hbase = hq;
3814        int off[GRP_NC];
3815        if constexpr (LX) {
3816            __syncthreads();
3817            for (int i = threadIdx.x; i < n * hb; i += 256) {
3818                const int c = i / hb, j = i - c * hb;
3819                memcpy(&s_h[c * S26_HMAX + j], &hq[(size_t) (e + c) * hb + j], sizeof(s_h[0]));
3820            }
3821            __syncthreads();
3822#pragma unroll
3823            for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_HMAX;
3824            hbase = s_h;
3825        } else {
3826#pragma unroll
3827            for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb;
3828        }
3829        if (!live) continue;
3830        float s[RPW][GRP_NC];
3831#pragma unroll
3832        for (int q = 0; q < RPW; ++q)
3833#pragma unroll
3834            for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;
3835        if constexpr (BAL > 0) {   // S26: 5 items per lane instead of 8 / 4, in BAL groups (loads first)
3836            constexpr int NI = 2 * S26_HMAX, IT = RPW * NI / 32;
3837            static_assert(RPW * NI % 32 == 0, "whole steps");
3838            auto group = [&]<int G0, int... J>(std::integer_sequence<int, J...>) {
3839                Split<20>::W w[sizeof...(J)];
3840                int kk[sizeof...(J)];
3841                bool hh[sizeof...(J)];
3842                ([&] {
3843                    using B = S26Bal<G0 + J, NI, RPW>;
3844                    hh[J] = B::QB != B::QA && lane >= B::THR;
3845                    kk[J] = B::P0 + lane - (hh[J] ? B::QB : B::QA) * NI;
3846                    const uint8_t* rp = hh[J] ? wr[B::QB] : wr[B::QA];
3847                    if constexpr (SL) w[J] = S26Split<20, false>::load(rp, kk[J] / 2, 2 * (kk[J] % 2));
3848                    else w[J] = Split<20>::load(rp, kk[J] / 2, 2 * (kk[J] % 2));
3849                }(), ...);
3850                ([&] {
3851                    using B = S26Bal<G0 + J, NI, RPW>;
3852#pragma unroll
3853                    for (int c = 0; c < GRP_NC; ++c)
3854                        if (c < n) {
3855                            const float v = Split<20>::apply(w[J], hbase + off[c] + kk[J] / 2, 2 * (kk[J] % 2));
3856                            if (hh[J]) s[B::QB][c] += v; else s[B::QA][c] += v;
3857                        }
3858                }(), ...);
3859            };
3860            constexpr int G = (IT + BAL - 1) / BAL;
3861            [&]<int... Q>(std::integer_sequence<int, Q...>) {
3862                (group.template operator()<Q * G>(std::make_integer_sequence<int, (IT - Q * G < G ? IT - Q * G : G)>{}), ...);
3863            }(std::make_integer_sequence<int, BAL>{});
3864        } else
3865        for (int k = lane; k < nb * 2; k += 32) {
3866            const int kbx = k / 2, iqs = 2 * (k % 2);
3867            Split<20>::W w[RPW];
3868#pragma unroll
3869            for (int q = 0; q < RPW; ++q) { if constexpr (SL) w[q] = S26Split<20, false>::load(wr[q], kbx, iqs); else w[q] = Split<20>::load(wr[q], kbx, iqs); }
3870#pragma unroll
3871            for (int q = 0; q < RPW; ++q)
3872#pragma unroll
3873                for (int c = 0; c < GRP_NC; ++c)
3874                    if (c < n) s[q][c] += Split<20>::apply(w[q], hbase + off[c] + kbx, iqs);
3875        }
3876        if constexpr (TS) {   // S26: all RPW x GRP_NC sums in one transposed butterfly (bitwise the same sums)
3877            constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);
3878            float v[P];
3879#pragma unroll
3880            for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;
3881            const float sum = s26ts::tsum<P>(v, lane);
3882            const int j = s26ts::tsum_token<P>(lane);
3883            const int q = j / GRP_NC, c = j % GRP_NC;
3884            if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC && c < n)
3885                out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum;
3886            continue;
3887        }
3888#pragma unroll
3889        for (int q = 0; q < RPW; ++q)
3890#pragma unroll
3891            for (int c = 0; c < GRP_NC; ++c)
3892                if (c < n) s[q][c] = warp_sum(s[q][c]);
3893#pragma unroll
3894        for (int q = 0; q < RPW; ++q)
3895#pragma unroll
3896            for (int c = 0; c < GRP_NC; ++c)
3897                if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c];
3898    }
3899}
3900
3901
3902// S26: swiglu_entries_kernel + quantize_q8_1_kernel in one launch (the same h expression, then the same block quantizer,
3903// contraction off so the product cannot fuse into the first sum); h is still written (it is the scratch the old pair used)
3904__global__ void s26_swiglu_q8_1_kernel(const float* __restrict__ gate, const float* __restrict__ up, float* __restrict__ h,
3905                                       block_q8_1* __restrict__ y, long long n) {
3906#pragma clang fp contract(off)
3907    const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;
3908    if (i >= n) return;   // n is a multiple of 32: whole warps only
3909    const float g = gate[i];
3910    const float xi = (g / (1.0f + __expf(-g))) * up[i];
3911    h[i] = xi;
3912    float amax = fabsf(xi), sum = xi;
3913#pragma unroll
3914    for (int o = 16; o > 0; o >>= 1) {
3915        amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
3916        sum += __shfl_xor_sync(0xffffffffu, sum, o);
3917    }
3918    const float d = q8_1_finite(amax / 127.0f);   // #606: as native_quantize_q8_1_kernel - finite blocks bit for bit
3919    const int8_t q = q8_1_quant(xi, d, amax);
3920    const long long ib = i / 32, iqs = i % 32;
3921    y[ib].qs[iqs] = q;
3922    if (iqs == 0) y[ib].ds = q8_1_ds(d, sum);   // #606: clamped scale/sum (the S26 path bypassed the finite helper)
3923}
3924template<bool LT, bool LX, int RG, int RD, bool SL = false, bool FQ = false, bool TS = false, int BD = 0>
3925void s26_launch_l(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr,
3926                  const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok,
3927                  const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) {
3928    const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * RG)), (unsigned) cap_groups);
3929    s26_gu_l_kernel<LT, LX, RG, SL, TS><<<ggu, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
3930    if (FQ) {
3931        s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh);
3932    } else {
3933        swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh);
3934        quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh);
3935    }
3936    const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups);
3937    s26_down_l_kernel<LX, RD, SL, TS, BD><<<gd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
3938}
3939// ---------------------------------------------------------------- stream B: UD-Q4_K_XL grouped decode experts
3940// STRATA_EXPERT_V2K=1: s26_gu_l_kernel / s26_down_l_kernel's structure (4 interleaved rows per warp, the chunk's q8_1
3941// activation rows in LDS, SwiGLU + q8_1 fused, optionally STRATA_TSUM's transposed butterfly) for Q4_K / Q5_K gate/up
3942// and Q5_1 / Q8_0 down, which otherwise run native_gu_kernel / native_down_kernel (one entry at a time, the weight
3943// words re-read per column).  Each Fmt<TY>::dot is split into S27<TY>::load (everything that depends on the weight) and
3944// apply (the activation words and the same integer / float expression), the same impl functions, so a row's lane-strided
3945// k order, its terms and warp_sum are the old kernels': every output is bitwise the old one's (iq harness, memcmp).
3946
3947template<int TG, bool LX, int RPW, bool TS>
3948__global__ void __launch_bounds__(256) s27_gu_kernel(const unsigned long long* __restrict__ grp_ptr,
3949                                                     const int32_t* __restrict__ grp_start,
3950                                                     const int32_t* __restrict__ n_groups,
3951                                                     const int32_t* __restrict__ ent_tok,
3952                                                     const block_q8_1* __restrict__ xq, NativeExpertLayout L,
3953                                                     float* __restrict__ gate, float* __restrict__ up) {
3954    using F = Fmt<TG>;
3955    using S = S27<TG>;
3956    __shared__ block_q8_1 s_x[LX ? GRP_NC * S26_XMAX : 1];
3957    const int g = blockIdx.y;
3958    if (g >= *n_groups) return;
3959    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
3960    const int row0 = blockIdx.x * GU_ROWS * RPW + warp;
3961    const bool live = row0 + GU_ROWS * (RPW - 1) < 2 * L.n_ff;
3962    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
3963    const uint8_t* wr[RPW];
3964    int rr[RPW];
3965    bool upq[RPW];
3966#pragma unroll
3967    for (int q = 0; q < RPW; ++q) {
3968        const int row = row0 + q * GU_ROWS;
3969        upq[q] = row >= L.n_ff;
3970        rr[q] = upq[q] ? row - (int) L.n_ff : row;
3971        wr[q] = blob + (upq[q] ? L.up_off : 0) + (size_t) rr[q] * L.gu_row;
3972    }
3973    const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32);
3974    const int e0 = grp_start[g], e1 = grp_start[g + 1];
3975    for (int e = e0; e < e1; e += GRP_NC) {
3976        const int n = min(GRP_NC, e1 - e);
3977        const block_q8_1* xbase = xq;
3978        int off[GRP_NC];
3979        if constexpr (LX) {
3980            __syncthreads();   // the previous chunk is done with s_x
3981            for (int i = threadIdx.x; i < n * xb; i += 256) {
3982                const int c = i / xb, j = i - c * xb;
3983                memcpy(&s_x[c * S26_XMAX + j], &xq[(size_t) ent_tok[e + c] * xb + j], sizeof(s_x[0]));
3984            }
3985#pragma unroll
3986            for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_XMAX;
3987            xbase = s_x;
3988            __syncthreads();
3989        } else {
3990#pragma unroll
3991            for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb;
3992        }
3993        if (!live) continue;
3994        float s[RPW][GRP_NC];
3995#pragma unroll
3996        for (int q = 0; q < RPW; ++q)
3997#pragma unroll
3998            for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;
3999        for (int k = lane; k < nb * F::ipb; k += 32) {
4000            const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
4001            typename S::W w[RPW];
4002#pragma unroll
4003            for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs);
4004#pragma unroll
4005            for (int q = 0; q < RPW; ++q)
4006#pragma unroll
4007                for (int c = 0; c < GRP_NC; ++c)
4008                    if (c < n) s[q][c] += S::apply(w[q], xbase + off[c] + kbx * (F::qk / 32), iqs);
4009        }
4010        if constexpr (TS) {
4011            constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);
4012            float v[P];
4013#pragma unroll
4014            for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;
4015            const float sum = s26ts::tsum<P>(v, lane);
4016            const int j = s26ts::tsum_token<P>(lane);
4017            if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC) {
4018                const int c = j % GRP_NC;
4019#pragma unroll
4020                for (int q = 0; q < RPW; ++q)
4021                    if (j / GRP_NC == q && c < n) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = sum;
4022            }
4023            continue;
4024        }
4025#pragma unroll
4026        for (int q = 0; q < RPW; ++q)
4027#pragma unroll
4028            for (int c = 0; c < GRP_NC; ++c)
4029                if (c < n) s[q][c] = warp_sum(s[q][c]);
4030#pragma unroll
4031        for (int q = 0; q < RPW; ++q)
4032#pragma unroll
4033            for (int c = 0; c < GRP_NC; ++c)
4034                if (c < n && lane == c) (upq[q] ? up : gate)[(size_t) (e + c) * L.n_ff + rr[q]] = s[q][c];
4035    }
4036}
4037
4038template<int TD, bool LX, int RPW, bool TS>
4039__global__ void __launch_bounds__(256) s27_down_kernel(const unsigned long long* __restrict__ grp_ptr,
4040                                                       const int32_t* __restrict__ grp_start,
4041                                                       const int32_t* __restrict__ n_groups,
4042                                                       const int32_t* __restrict__ ent_dst,
4043                                                       const block_q8_1* __restrict__ hq, NativeExpertLayout L,
4044                                                       float* __restrict__ out) {
4045    using F = Fmt<TD>;
4046    using S = S27<TD>;
4047    __shared__ block_q8_1 s_h[LX ? GRP_NC * S26_HMAX : 1];
4048    const int g = blockIdx.y;
4049    if (g >= *n_groups) return;
4050    const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31;
4051    const int r0 = blockIdx.x * 8 * RPW + warp;
4052    const bool live = r0 + 8 * (RPW - 1) < L.n_embd;
4053    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
4054    const uint8_t* wr[RPW];
4055#pragma unroll
4056    for (int q = 0; q < RPW; ++q) wr[q] = blob + L.down_off + (size_t) (r0 + 8 * q) * L.d_row;
4057    const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32);
4058    const int e0 = grp_start[g], e1 = grp_start[g + 1];
4059    for (int e = e0; e < e1; e += GRP_NC) {
4060        const int n = min(GRP_NC, e1 - e);
4061        const block_q8_1* hbase = hq;
4062        int off[GRP_NC];
4063        if constexpr (LX) {
4064            __syncthreads();
4065            for (int i = threadIdx.x; i < n * hb; i += 256) {
4066                const int c = i / hb, j = i - c * hb;
4067                memcpy(&s_h[c * S26_HMAX + j], &hq[(size_t) (e + c) * hb + j], sizeof(s_h[0]));
4068            }
4069            __syncthreads();
4070#pragma unroll
4071            for (int c = 0; c < GRP_NC; ++c) off[c] = min(c, n - 1) * S26_HMAX;
4072            hbase = s_h;
4073        } else {
4074#pragma unroll
4075            for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb;
4076        }
4077        if (!live) continue;
4078        float s[RPW][GRP_NC];
4079#pragma unroll
4080        for (int q = 0; q < RPW; ++q)
4081#pragma unroll
4082            for (int c = 0; c < GRP_NC; ++c) s[q][c] = 0.0f;
4083        for (int k = lane; k < nb * F::ipb; k += 32) {
4084            const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
4085            typename S::W w[RPW];
4086#pragma unroll
4087            for (int q = 0; q < RPW; ++q) w[q] = S::load(wr[q], kbx, iqs);
4088#pragma unroll
4089            for (int q = 0; q < RPW; ++q)
4090#pragma unroll
4091                for (int c = 0; c < GRP_NC; ++c)
4092                    if (c < n) s[q][c] += S::apply(w[q], hbase + off[c] + kbx * (F::qk / 32), iqs);
4093        }
4094        if constexpr (TS) {
4095            constexpr int P = s26ts::pow2_ceil(RPW * GRP_NC);
4096            float v[P];
4097#pragma unroll
4098            for (int j = 0; j < P; ++j) v[j] = j < RPW * GRP_NC ? s[j / GRP_NC][j % GRP_NC] : 0.0f;
4099            const float sum = s26ts::tsum<P>(v, lane);
4100            const int j = s26ts::tsum_token<P>(lane);
4101            const int q = j / GRP_NC, c = j % GRP_NC;
4102            if (lane == s26ts::tsum_lane<P>(j) && j < RPW * GRP_NC && c < n)
4103                out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = sum;
4104            continue;
4105        }
4106#pragma unroll
4107        for (int q = 0; q < RPW; ++q)
4108#pragma unroll
4109            for (int c = 0; c < GRP_NC; ++c)
4110                if (c < n) s[q][c] = warp_sum(s[q][c]);
4111#pragma unroll
4112        for (int q = 0; q < RPW; ++q)
4113#pragma unroll
4114            for (int c = 0; c < GRP_NC; ++c)
4115                if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r0 + 8 * q] = s[q][c];
4116    }
4117}
4118
4119template<int TG, int TD, bool LX, int RG, int RD, bool TS>
4120void s27_launch(const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr,
4121                const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok,
4122                const block_q8_1* X, float* gate, float* up, float* h, block_q8_1* hq, float* out, long long nh) {
4123    const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * RG)), (unsigned) cap_groups);
4124    s27_gu_kernel<TG, LX, RG, TS><<<ggu, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4125    s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh);
4126    const dim3 gd((unsigned) (L.n_embd / (8 * RD)), (unsigned) cap_groups);
4127    s27_down_kernel<TD, LX, RD, TS><<<gd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4128}
4129template<int TG, int TD>
4130void s27_launch_ts(bool ts, const NativeExpertLayout& L, int64_t cap_groups, cudaStream_t s,
4131                   const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,
4132                   const int32_t* ent_dst, const int32_t* ent_tok, const block_q8_1* X, float* gate, float* up, float* h,
4133                   block_q8_1* hq, float* out, long long nh) {
4134    if (ts) s27_launch<TG, TD, true, 4, 4, true>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh);
4135    else s27_launch<TG, TD, true, 4, 4, false>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh);
4136}
4137
4138// ---- EXPDEC launch: knobs, shapes, rows per block
4139int env_int_or(const char* name, int dflt) {
4140    const char* v = std::getenv(name);
4141    return v != nullptr && v[0] != '\0' ? std::atoi(v) : dflt;
4142}
4143// read at first use (not at load), so a per-architecture default set at start (nv_defaults.hpp) is seen; native_expert_set_expdec overrides
4144int g_expdec = -1;
4145int expdec_mode() { if (g_expdec < 0) g_expdec = env_on("STRATA_EXPDEC") ? 1 : 0; return g_expdec; }
4146int g_expdec_r = env_int_or("STRATA_EXPDEC_R", 1);          // gate/up rows per lane: 1, 2 (bench: R=1 wins on the 2080 Ti)
4147int g_expdec_dr = env_int_or("STRATA_EXPDEC_DR", 4);        // down rows per lane: 1, 2, 4 (Q2_0: R=4 wins on both cards)
4148int g_expdec_minb = env_int_or("STRATA_EXPDEC_MINB", STRATA_EXPDEC_MINB);   // gate/up __launch_bounds__ min blocks: 2 (<= 128 regs) or 4 (<= 64)
4149int g_expdec_d20 = env_int_or("STRATA_EXPDEC_D20", 0);      // 1: EXPDEC also for the IQ4_NL down (bench: no gain, default kernel)
4150// 1: EXPDEC for the down too (Q2_0; IQ4_NL with _D20).  Default 0: in the engine (nsys of a 131k decode on a 2080 Ti) the Q2_0 down
4151// with EXPDEC was ~10% slower than the default kernel although the bench alone had it at 0.78.  Read at first use, so a per-architecture
4152// default set at start (arch_defaults.cpp: gfx12) is seen; native_expert_set_expdec_params overrides.
4153int g_expdec_down = -1;
4154int expdec_down_on() { if (g_expdec_down < 0) g_expdec_down = env_int_or("STRATA_EXPDEC_DOWN", 0) != 0 ? 1 : 0; return g_expdec_down; }
4155int g_expdec_rb = env_int_or("STRATA_EXPDEC_RB", 0);        // gate/up rows per block (0 = auto)
4156int g_expdec_drb = env_int_or("STRATA_EXPDEC_DRB", 0);      // down rows per block (0 = auto)
4157int g_expdec_minblk = env_int_or("STRATA_EXPDEC_MINBLK", 800);   // auto: the most rows per block that keep this many blocks
4158int expdec_r() { return g_expdec_r == 2 ? 2 : 1; }
4159int expdec_dr() { return g_expdec_dr == 1 || g_expdec_dr == 2 ? g_expdec_dr : 4; }
4160
4161bool expdec_gu_ok(const NativeExpertLayout& L) {
4162    const bool fmt = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22;
4163    return fmt && L.n_embd == 32 * ED_XB && L.n_ff % 64 == 0 && L.n_ff > 0;
4164}
4165bool expdec_down_ok(const NativeExpertLayout& L) {
4166    return expdec_down_on() && ((L.d_type == 20 && g_expdec_d20) || L.d_type == 42) && L.n_ff == 32 * ED_HB && L.n_embd % 128 == 0 &&
4167           L.n_embd > 0;
4168}
4169// rows per block: `knob` rounded up to the rows per pass, or (0) doubled from one pass while ceil(nrow / rb) x
4170// cap_groups blocks stay >= g_expdec_minblk (cap_groups: the launch's group rows; every block row g >= n_groups returns)
4171int expdec_rows_per_block(int nrow, int rpp, int64_t cap_groups, int knob) {
4172    if (knob > 0) {
4173        int rb = (knob + rpp - 1) / rpp * rpp;
4174        return rb > nrow ? nrow : rb;
4175    }
4176    int rb = rpp;
4177    const int64_t cap = cap_groups > 0 ? cap_groups : 1;
4178    while (rb * 2 <= nrow && ((int64_t) ((nrow + 2 * rb - 1) / (2 * rb))) * cap >= g_expdec_minblk) rb *= 2;
4179    return rb;
4180}
4181
4182template<int TG, int R, int MINB>
4183void expdec_gu_r(int64_t gy, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start,
4184                 const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L,
4185                 float* gate, float* up) {
4186    const int nrow = 2 * (int) L.n_ff;
4187    const int rb = expdec_rows_per_block(nrow, 16 * R, cap_groups, g_expdec_rb);
4188    const dim3 grid((unsigned) ((nrow + rb - 1) / rb), (unsigned) gy);
4189    expdec_gu_kernel<TG, R, MINB><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up, rb);
4190}
4191template<int TG>
4192void expdec_gu_t(int64_t gy, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start,
4193                 const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L,
4194                 float* gate, float* up) {
4195    const bool b4 = g_expdec_minb >= 4;
4196    if (expdec_r() == 2) {
4197        if (b4) expdec_gu_r<TG, 2, 4>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4198        else expdec_gu_r<TG, 2, 2>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4199    } else {
4200        if (b4) expdec_gu_r<TG, 1, 4>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4201        else expdec_gu_r<TG, 1, 2>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4202    }
4203}
4204// One line on stderr per (role, format, taken or not), the first time STRATA_EXPDEC=1 meets it: the proof in the
4205// engine's log that the EXPDEC kernels are the ones launched (or captured into the window's graph), with the
4206// choices in force.
4207void expdec_note(const NativeExpertLayout& L, bool gu, bool taken, cudaStream_t s, int64_t gy, int64_t cap_groups) {
4208    static bool seen[2][64][2] = {};
4209    const int ty = gu ? L.gu_type : L.d_type;
4210    if (ty < 0 || ty >= 64 || seen[gu ? 0 : 1][ty][taken ? 1 : 0]) return;
4211    seen[gu ? 0 : 1][ty][taken ? 1 : 0] = true;
4212    cudaStreamCaptureStatus cs = cudaStreamCaptureStatusNone;
4213    (void) cudaStreamIsCapturing(s, &cs);
4214    int dev = -1;
4215    (void) cudaGetDevice(&dev);
4216    if (!taken) {
4217        std::fprintf(stderr, "strata expdec: CUDA%d %s type %d (n_embd %lld, n_ff %lld) not covered: the default kernel runs\n", dev,
4218                     gu ? "gate/up" : "down", ty, (long long) L.n_embd, (long long) L.n_ff);
4219        return;
4220    }
4221    if (gu) {
4222        const int R = expdec_r(), rb = expdec_rows_per_block(2 * (int) L.n_ff, 16 * R, cap_groups, g_expdec_rb);
4223        std::fprintf(stderr, "strata expdec: CUDA%d gate/up type %d: expdec_gu_kernel R %d MINB %d, %d rows per block, grid %d x %lld "
4224                             "(cap %lld groups)%s\n", dev, ty, R, g_expdec_minb >= 4 ? 4 : 2, rb, (2 * (int) L.n_ff + rb - 1) / rb,
4225                     (long long) gy, (long long) cap_groups, cs != cudaStreamCaptureStatusNone ? ", captured into a graph" : "");
4226    } else {
4227        const int R = expdec_dr(), lanes = ty == 20 ? 8 : 16;
4228        const int rb = expdec_rows_per_block((int) L.n_embd, (256 / lanes) * R, cap_groups, g_expdec_drb);
4229        std::fprintf(stderr, "strata expdec: CUDA%d down type %d: expdec_down_kernel R %d, %d rows per block, grid %d x %lld "
4230                             "(cap %lld groups)%s\n", dev, ty, R, rb, ((int) L.n_embd + rb - 1) / rb, (long long) gy,
4231                     (long long) cap_groups, cs != cudaStreamCaptureStatusNone ? ", captured into a graph" : "");
4232    }
4233}
4234
4235// false: EXPDEC is off or does not take this layout (the caller launches the default kernels)
4236bool expdec_gu(const NativeExpertLayout& L, int64_t gy, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr,
4237               const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, float* gate,
4238               float* up) {
4239    if (!expdec_mode() || g_old_kernels) return false;
4240    if (!expdec_gu_ok(L)) { expdec_note(L, true, false, s, gy, cap_groups); return false; }
4241    expdec_note(L, true, true, s, gy, cap_groups);
4242    switch (L.gu_type) {
4243        case 16: expdec_gu_t<16>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
4244        case 17: expdec_gu_t<17>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
4245        case 18: expdec_gu_t<18>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
4246        case 21: expdec_gu_t<21>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
4247        default: expdec_gu_t<22>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
4248    }
4249    return true;
4250}
4251template<int TD, int R>
4252void expdec_down_r(int64_t gy, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start,
4253                   const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, const NativeExpertLayout& L, float* out) {
4254    constexpr int LANES = TD == 20 ? 8 : 16;
4255    const int nrow = (int) L.n_embd;
4256    const int rb = expdec_rows_per_block(nrow, (256 / LANES) * R, cap_groups, g_expdec_drb);
4257    const dim3 grid((unsigned) ((nrow + rb - 1) / rb), (unsigned) gy);
4258    expdec_down_kernel<TD, R><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out, rb);
4259}
4260template<int TD>
4261void expdec_down_t(int64_t gy, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start,
4262                   const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, const NativeExpertLayout& L, float* out) {
4263    switch (expdec_dr()) {
4264        case 1: expdec_down_r<TD, 1>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
4265        case 2: expdec_down_r<TD, 2>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
4266        default: expdec_down_r<TD, 4>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
4267    }
4268}
4269bool expdec_down(const NativeExpertLayout& L, int64_t gy, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr,
4270                 const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, float* out) {
4271    if (!expdec_mode() || g_old_kernels) return false;
4272    if (!expdec_down_ok(L)) { expdec_note(L, false, false, s, gy, cap_groups); return false; }
4273    expdec_note(L, false, true, s, gy, cap_groups);
4274    if (L.d_type == 20) expdec_down_t<20>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4275    else expdec_down_t<42>(gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4276    return true;
4277}
4278
4279template<int TG>
4280void launch_gu(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start,
4281               const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X, const NativeExpertLayout& L,
4282               float* gate, float* up) {
4283    // the sub-16 rows (row_dot_80_sub16) assume 80 dots per row: (n_embd / qk) * ipb == 80. The APR trellis types
4284    // (qk 128, ipb 8: 160 dots at n_embd 2560) take the full-warp multi kernel, as before the sub-16 kernels.
4285    const bool g_no_sub16_gu = ::strata::kernels::g_no_sub16_gu || (L.n_embd / Fmt<TG>::qk) * Fmt<TG>::ipb != 80;
4286    if constexpr (!kSplit<TG>) native_gu_kernel<TG><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4287    else if (g_old_kernels || split_off<TG>()) native_gu_kernel<TG><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4288    else if constexpr (kStageIqGrid<TG>) {
4289        if constexpr (TG == 144 || TG == 145) {   // tq_sub8_on: the 8-lane trellis rows, 32 rows a block
4290            if (tq_sub8_on() && (L.n_embd / Fmt<TG>::qk) * Fmt<TG>::ipb == 160) {
4291                dim3 g8 = grid;
4292                g8.x = (unsigned) ((2 * L.n_ff + 31) / 32);
4293                native_gu_multi_kernel<TG, true, true><<<g8, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4294                return;
4295            }
4296        }
4297        if (!g_stage_grid || ((TG == 18 || TG == 21) && !stage_tables_on()) || (kTqType<TG> && !tq_stage_on())) {
4298            if (g_no_sub16_gu) native_gu_multi_kernel<TG, false, false><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4299            else native_gu_multi_kernel<TG, false, true><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4300            return;
4301        }
4302        dim3 sg = grid;
4303        if constexpr (kTqType<TG>) sg.x = (grid.x + tq_row_chunks() - 1) / tq_row_chunks();   // the staged codebook is paid once per chunks
4304        if (g_no_sub16_gu) native_gu_multi_kernel<TG, true, false><<<sg, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4305        else native_gu_multi_kernel<TG, true, true><<<sg, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4306    } else {
4307        if (g_no_sub16_gu) native_gu_multi_kernel<TG, false, false><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4308        else native_gu_multi_kernel<TG, false, true><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
4309    }
4310}
4311
4312// 147-verify: STRATA_GU_SWIGLU=1 runs gate/up, SwiGLU and the q8_1 blocks as native_gu_swiglu_kernel, where launch_gu would
4313// run native_gu_multi_kernel's 16-lane path (n_embd 2560, the split formats); bitwise the same hq.  Unset: on for a compute
4314// capability 12.0 card (sm120_series.hpp; RTX PRO 5000, 6 pairs: decode +0.6% story, +0.9% code, +0.5% 8K, 6/6 each, the
4315// same tokens), off elsewhere; STRATA_GU_SWIGLU=0 turns it off.
4316bool gu_swiglu_on() {
4317    static const int env = [] { const char* v = std::getenv("STRATA_GU_SWIGLU"); return v != nullptr ? (std::atoi(v) != 0 ? 1 : 0) : -1; }();
4318    if (env >= 0) return env != 0;
4319#if defined(__HIPCC__)
4320    return false;
4321#else
4322    static int per_dev[64];   // 0 unknown, 1 no, 2 yes
4323    int dev = 0;
4324    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) { cudaGetLastError(); return false; }
4325    if (!per_dev[dev]) {
4326        int maj = 0, mnr = 0;
4327        const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
4328                        cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
4329        if (!ok) cudaGetLastError();
4330        per_dev[dev] = ok && strata::sm120_default(maj, mnr) ? 2 : 1;
4331    }
4332    return per_dev[dev] == 2;
4333#endif
4334}
4335template<int TG>
4336bool launch_gu_swiglu(const NativeExpertLayout& L, int64_t gy, cudaStream_t s, const unsigned long long* grp_ptr,
4337                      const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X,
4338                      block_q8_1* hq) {
4339    if constexpr (!kSplit<TG>) {
4340        return false;
4341    } else {
4342        if (g_old_kernels || split_off<TG>() || g_no_sub16_gu || L.n_embd != 2560 || L.n_ff % 32 != 0 || L.n_ff <= 0) return false;
4343        // the 16-lane rows assume 80 dots a row (as launch_gu): the 256-value K-quants and the APR trellis types (TQ2_T /
4344        // TQK6 gate/up: qk 128, ipb 8) have 160 at n_embd 2560 and take launch_gu's full-warp multi kernel.  Gyro-S (TQK6
4345        // gate/up) went through here on every 12.0 card from 147-verify on: half of each gate/up row, looping answers.
4346        if ((L.n_embd / Fmt<TG>::qk) * Fmt<TG>::ipb != 80) return false;
4347        const dim3 grid((unsigned) (L.n_ff / 32), (unsigned) gy);
4348        bool stage = false;
4349        if constexpr (kStageIqGrid<TG>) stage = g_stage_grid && !((TG == 18 || TG == 21) && !stage_tables_on()) && !(kTqType<TG> && !tq_stage_on());
4350        if constexpr (kStageIqGrid<TG>) {
4351            if (stage) native_gu_swiglu_kernel<TG, true><<<grid, 512, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq);
4352            else native_gu_swiglu_kernel<TG, false><<<grid, 512, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq);
4353        } else {
4354            native_gu_swiglu_kernel<TG, false><<<grid, 512, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq);
4355        }
4356        return true;
4357    }
4358}
4359
4360template<int TD>
4361void launch_down(dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr, const int32_t* grp_start,
4362                 const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, const NativeExpertLayout& L,
4363                 float* out) {
4364    if constexpr (!kSplit<TD>) native_down_kernel<TD><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4365    else if (g_old_kernels || split_off<TD>()) native_down_kernel<TD><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4366    else if constexpr (kTqType<TD>) {   // the trellis down types: the codebook staged where tq_stage_on() or tq_sub8_on()
4367        if (tq_stage_on() || tq_sub8_on()) {
4368            if (g_no_sub16_gu) native_down_multi_kernel<TD, false, true><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4369            else native_down_multi_kernel<TD, true, true><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4370        }
4371        else native_down_multi_kernel<TD, true, false><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4372    }
4373    else if (g_no_sub16_gu) native_down_multi_kernel<TD, false><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4374    else native_down_multi_kernel<TD, true><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4375}
4376// ---------------------------------------------------------------- STRATA_DOWN_WS: the decode down projection, staged
4377// (opt-in, default off; cc 6.0 only).  native_down_multi_kernel's IQ4_NL (K 40, n_ff 640) and Q2_0 (K 20) rows read each
4378// weight as 2-byte loads, an item at a time, straight from global memory, and a block (32 / 16 rows) waits on that.
4379// Here a block copies its rows (IQ4_NL 32, Q2_0 64: 11,520 bytes) into shared memory with 16-byte loads - one round
4380// trip, all in flight - reads the plan words before the group test and the entries' destination rows before the weights
4381// land, and then runs the production row dots on the copy: the same 8 / 16-lane sub-warp, lane t, items, float
4382// expressions and order (row_dot_40_sub8 / row_dot_20_sub16: s += item t (+ t + 32), s16, s8, s24, the __fadd_rn's,
4383// xor 4..1 / 8..1, * sd).  Two integer-only changes inside an item: the dp4a emulation's byte products are taken from
4384// the table lookup's bytes with vmad byte selectors (no interleaving byte_perm), and IQ4_NL's lookup uses raw prmt
4385// selectors (bit 3, sign replicate, only touches the bytes the low/high merge drops; lhsi's nibbles are 0..7, so no
4386// 0x7777 masks).  An item's int32 sum is the sum of the same int8 x int8 products, so every output is bit for bit
4387// native_down_multi_kernel's (memcmp equal on all 48 layers of the Swift 1.5 IQ3_S pack, all 512 experts, 1-6
4388// entries a group and T = 1..4 plans; native_expert_bench checks it against mode 0 and mode 8 by output hash).
4389#if defined(STRATA_EXPERIMENTAL_SM60) && !defined(__HIPCC__) && !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906) && \
4390    !defined(STRATA_GPU_METAL)
4391#define STRATA_DOWN_WS_BUILT 1   // the CUDA build with STRATA_EXPERIMENTAL_SM60 only
4392#else
4393#define STRATA_DOWN_WS_BUILT 0
4394#endif
4395#if STRATA_DOWN_WS_BUILT
4396#define STRATA_DWS_VMAD(r, a, sa, b, sb) asm("vmad.s32.s32.s32 %0, %1.b" #sa ", %2.b" #sb ", %0;" : "+r"(r) : "r"(a), "r"(b))
4397
4398__device__ __forceinline__ uint32_t dws_prmt(uint32_t a, uint32_t b, uint32_t c) {
4399    uint32_t d;
4400    asm("prmt.b32 %0, %1, %2, %3;" : "=r"(d) : "r"(a), "r"(b), "r"(c));
4401    return d;
4402}
4403
4404// get_int_from_table_16(q4, kvalues_iq4nl) before its 0x6420 / 0x7531 interleave: t0 = T(v0) T(v16) T(v1) T(v17),
4405// t1 = T(v2) T(v18) T(v3) T(v19).  low = prmt(T0..7, q) is right for codes < 8, high = prmt(T8..15, q ^ 0x8..) for
4406// codes >= 8, and the merge with lhsi (nibbles 0..7) takes exactly those bytes - the same bytes as __byte_perm's masked
4407// selectors give.
4408__device__ __forceinline__ void dws_iq4_tab(uint32_t q4, int& t0, int& t1) {
4409    const uint32_t* table32 = (const uint32_t*) kvalues_iq4nl;
4410    const uint32_t lhsi = 0x32103210u | ((q4 & 0x88888888u) >> 1);
4411    const uint32_t qx = q4 ^ 0x88888888u;
4412    t0 = (int) dws_prmt(dws_prmt(table32[0], table32[1], q4), dws_prmt(table32[2], table32[3], qx), lhsi);
4413    t1 = (int) dws_prmt(dws_prmt(table32[0], table32[1], q4 >> 16), dws_prmt(table32[2], table32[3], qx >> 16), lhsi >> 16);
4414}
4415
4416struct DwsIq4W { int t0[2], t1[2]; float dw; };
4417
4418__device__ __forceinline__ DwsIq4W dws_iq4_load(const void* __restrict__ vbq, int kbx, int iqs) {
4419    const block_iq4_nl* bq4 = (const block_iq4_nl*) vbq + kbx;
4420    DwsIq4W r;
4421#pragma unroll
4422    for (int l = 0; l < 2; ++l) dws_iq4_tab((uint32_t) get_int_b2(bq4->qs, iqs + l), r.t0[l], r.t1[l]);
4423    r.dw = __half2float(bq4->d);
4424    return r;
4425}
4426
4427// = Split<20>::apply(Split<20>::load(...)): x_l = (t0.b0 t0.b2 t1.b0 t1.b2) . q8[l], y_l = (t0.b1 t0.b3 t1.b1 t1.b3) . q8[l + 4]
4428__device__ __forceinline__ float dws_iq4_apply(const DwsIq4W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
4429    const int* q8 = (const int*) bq8_1->qs + iqs;
4430    int sumi = 0;
4431#pragma unroll
4432    for (int l = 0; l < 2; ++l) {
4433        const int A = q8[l + 0], B = q8[l + 4];
4434        STRATA_DWS_VMAD(sumi, r.t0[l], 0, A, 0);
4435        STRATA_DWS_VMAD(sumi, r.t0[l], 2, A, 1);
4436        STRATA_DWS_VMAD(sumi, r.t1[l], 0, A, 2);
4437        STRATA_DWS_VMAD(sumi, r.t1[l], 2, A, 3);
4438        STRATA_DWS_VMAD(sumi, r.t0[l], 1, B, 0);
4439        STRATA_DWS_VMAD(sumi, r.t0[l], 3, B, 1);
4440        STRATA_DWS_VMAD(sumi, r.t1[l], 1, B, 2);
4441        STRATA_DWS_VMAD(sumi, r.t1[l], 3, B, 3);
4442    }
4443    const float d = r.dw * __low2float(bq8_1->ds);
4444    return d * sumi;
4445}
4446
4447// row_dot_40_sub8<20, NC, true> (t < 8: its k loop is k = t, t + 32), the five items' words loaded first
4448template<int NC>
4449__device__ __forceinline__ void dws_row40(const uint8_t* row, const block_q8_1* x, int t, float (&s)[NC]) {
4450    const int k0 = t, k1 = t + 32, k2 = t + 16, k3 = t + 8, k4 = t + 24;
4451    const DwsIq4W w0 = dws_iq4_load(row, k0 / 2, 2 * (k0 % 2));
4452    const DwsIq4W w1 = dws_iq4_load(row, k1 / 2, 2 * (k1 % 2));
4453    const DwsIq4W w2 = dws_iq4_load(row, k2 / 2, 2 * (k2 % 2));
4454    const DwsIq4W w3 = dws_iq4_load(row, k3 / 2, 2 * (k3 % 2));
4455    const DwsIq4W w4 = dws_iq4_load(row, k4 / 2, 2 * (k4 % 2));
4456#pragma unroll
4457    for (int c = 0; c < NC; ++c) {
4458        const block_q8_1* xc = x + 20 * c;
4459        s[c] = 0.0f;
4460        s[c] += dws_iq4_apply(w0, xc + k0 / 2, 2 * (k0 % 2));
4461        s[c] += dws_iq4_apply(w1, xc + k1 / 2, 2 * (k1 % 2));
4462        {
4463            float s16 = 0.0f;
4464            s16 += dws_iq4_apply(w2, xc + k2 / 2, 2 * (k2 % 2));
4465            s[c] = __fadd_rn(s[c], s16);
4466        }
4467        float s8 = 0.0f;
4468        s8 += dws_iq4_apply(w3, xc + k3 / 2, 2 * (k3 % 2));
4469        {
4470            float s24 = 0.0f;
4471            s24 += dws_iq4_apply(w4, xc + k4 / 2, 2 * (k4 % 2));
4472            s[c] = __fadd_rn(s[c], __fadd_rn(s8, s24));
4473        }
4474    }
4475#pragma unroll
4476    for (int c = 0; c < NC; ++c) {
4477#pragma unroll
4478        for (int o = 4; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
4479    }
4480}
4481
4482// Split<42>::load before its 0x5140 / 0x7362 interleave (qx = qe.b0 qo.b0 qe.b1 qo.b1, qy = qe.b2 qo.b2 qe.b3 qo.b3)
4483struct DwsQ2W { int qe[4], qo[4]; float d2; };
4484
4485__device__ __forceinline__ DwsQ2W dws_q2_load(const void* __restrict__ vbq, int kbx, int iqs) {
4486    const block_q2_0* bq2_0 = (const block_q2_0*) vbq + kbx;
4487    DwsQ2W r;
4488    r.d2 = bq2_0->d;
4489    const int16_t* qs = (const int16_t*) bq2_0->qs + iqs * 4;
4490#pragma unroll
4491    for (int j = 0; j < 4; ++j) {
4492        const int q = qs[j];
4493        r.qe[j] = __byte_perm(0x020100FF, 0x020100FF, q >> 0);
4494        r.qo[j] = __byte_perm(0x020100FF, 0x020100FF, q >> 2);
4495    }
4496    return r;
4497}
4498
4499// = Split<42>::apply, the 32 products summed in two int32 chains
4500__device__ __forceinline__ float dws_q2_apply(const DwsQ2W& r, const block_q8_1* __restrict__ bq8_1, int iqs) {
4501    const block_q8_1* bq8_1_chunk = bq8_1 + iqs;
4502    int a[2] = { 0, 0 };
4503#pragma unroll
4504    for (int j = 0; j < 4; ++j) {
4505        const int u = get_int_b4(bq8_1_chunk->qs, j * 2 + 0);
4506        const int v = get_int_b4(bq8_1_chunk->qs, j * 2 + 1);
4507        int& x = a[j & 1];
4508        STRATA_DWS_VMAD(x, u, 0, r.qe[j], 0);
4509        STRATA_DWS_VMAD(x, u, 1, r.qo[j], 0);
4510        STRATA_DWS_VMAD(x, u, 2, r.qe[j], 1);
4511        STRATA_DWS_VMAD(x, u, 3, r.qo[j], 1);
4512        STRATA_DWS_VMAD(x, v, 0, r.qe[j], 2);
4513        STRATA_DWS_VMAD(x, v, 1, r.qo[j], 2);
4514        STRATA_DWS_VMAD(x, v, 2, r.qe[j], 3);
4515        STRATA_DWS_VMAD(x, v, 3, r.qo[j], 3);
4516    }
4517    const int sumi = a[0] + a[1];
4518    const float d8 = __low2float(bq8_1_chunk->ds);
4519    return r.d2 * d8 * sumi;
4520}
4521
4522// row_dot_20_sub16<42, NC, true>
4523template<int NC>
4524__device__ __forceinline__ void dws_row20(const uint8_t* row, const block_q8_1* x, int t, float (&s)[NC]) {
4525    const DwsQ2W w = dws_q2_load(row, t / 2, t % 2);
4526#pragma unroll
4527    for (int c = 0; c < NC; ++c) {
4528        s[c] = 0.0f;
4529        s[c] += dws_q2_apply(w, x + 20 * c + (t / 2) * 2, t % 2);
4530    }
4531    float s16[NC];
4532#pragma unroll
4533    for (int c = 0; c < NC; ++c) s16[c] = 0.0f;
4534    if (t < 4) {
4535        const int k = t + 16;
4536        const DwsQ2W w2 = dws_q2_load(row, k / 2, k % 2);
4537#pragma unroll
4538        for (int c = 0; c < NC; ++c) s16[c] += dws_q2_apply(w2, x + 20 * c + (k / 2) * 2, k % 2);
4539    }
4540#pragma unroll
4541    for (int c = 0; c < NC; ++c) {
4542        s[c] = __fadd_rn(s[c], s16[c]);
4543#pragma unroll
4544        for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
4545    }
4546}
4547
4548// NC entries of one row; every lane of the sub-warp holds the same sum (butterfly), lane c stores entry c
4549template<int TD, int NC>
4550__device__ __forceinline__ void dws_rows(const uint8_t* wr, const block_q8_1* s_hq, int t, float sd, float* __restrict__ out,
4551                                         const int (&dst)[NC], int64_t n_embd, int r) {
4552    float s[NC];
4553    if constexpr (TD == 20) dws_row40<NC>(wr, s_hq, t, s);
4554    else dws_row20<NC>(wr, s_hq, t, s);
4555#pragma unroll
4556    for (int c = 0; c < NC; ++c)
4557        if (t == c) out[(size_t) dst[c] * n_embd + r] = s[c] * sd;
4558}
4559
4560// grid (n_embd / RB, gy), 256 threads: RB = 32 IQ4_NL rows (one pass of 8-lane rows) or 64 Q2_0 rows (four passes of
4561// 16-lane rows); entries NCMAX at a time (1: a T = 1 window, every group one entry; 4: as GRP_NC)
4562template<int TD, int NCMAX>
4563__global__ void __launch_bounds__(256, 4) native_down_ws_kernel(const unsigned long long* __restrict__ grp_ptr,
4564                                                                const int32_t* __restrict__ grp_start,
4565                                                                const int32_t* __restrict__ n_groups,
4566                                                                const int32_t* __restrict__ ent_dst,
4567                                                                const block_q8_1* __restrict__ hq, NativeExpertLayout L,
4568                                                                float* __restrict__ out) {
4569    constexpr int LPR = TD == 20 ? 8 : 16, RPP = 256 / LPR, P = TD == 20 ? 1 : 4, RB = RPP * P;
4570    constexpr int DROW = TD == 20 ? 360 : 180, WB = RB * DROW, NV = (WB / 16 + 255) / 256;
4571    static_assert(WB % 16 == 0, "16-byte copies");
4572    STRATA_SHARED_ALIGN16_U32(s_w, WB / 4);
4573    STRATA_SHARED_ALIGN16_U32(s_hq_buf, NCMAX * 20 * 9);
4574    const int tid = threadIdx.x, t = tid % LPR, sub = tid / LPR;
4575    const int r0 = blockIdx.x * RB;
4576    const int nrow = min(RB, (int) L.n_embd - r0);
4577    const block_q8_1* s_hq = reinterpret_cast<const block_q8_1*>(s_hq_buf);
4578    // the plan words of this block row's first group before the test (gridDim.y <= cap_groups: in bounds)
4579    int g = blockIdx.y;
4580    unsigned long long gpu = grp_ptr[g];
4581    int e0 = grp_start[g], e1 = grp_start[g + 1];
4582    const int ng = *n_groups;
4583    for (; g < ng; g += gridDim.y) {   // the group stride, as native_down_multi_kernel
4584        if (g != (int) blockIdx.y) {
4585            __syncthreads();
4586            gpu = grp_ptr[g];
4587            e0 = grp_start[g];
4588            e1 = grp_start[g + 1];
4589        }
4590        const uint8_t* gp = (const uint8_t*) gpu + L.down_off + (size_t) r0 * DROW;
4591        const float sd = L.tail_off ? ((const float*) (gpu + L.tail_off))[2] : 1.0f;
4592        int dst[NCMAX];
4593#pragma unroll
4594        for (int c = 0; c < NCMAX; ++c) dst[c] = ent_dst[min(e0 + c, e1 - 1)];
4595        const int nbytes = nrow * DROW;
4596        if ((((uintptr_t) gp) & 15) == 0 && (nbytes & 15) == 0) {
4597            const uint4* src = reinterpret_cast<const uint4*>(gp);
4598            uint4* dw = reinterpret_cast<uint4*>(s_w);
4599            uint4 v[NV];
4600#pragma unroll
4601            for (int k = 0; k < NV; ++k)
4602                if (tid + 256 * k < (nbytes >> 4)) v[k] = __ldg(src + tid + 256 * k);
4603#pragma unroll
4604            for (int k = 0; k < NV; ++k)
4605                if (tid + 256 * k < (nbytes >> 4)) dw[tid + 256 * k] = v[k];
4606        } else {
4607            const uint16_t* s2 = reinterpret_cast<const uint16_t*>(gp);
4608            uint16_t* d2 = reinterpret_cast<uint16_t*>(s_w);
4609            for (int i = tid; i < (nbytes >> 1); i += 256) d2[i] = s2[i];
4610        }
4611        for (int e = e0; e < e1; e += NCMAX) {
4612            const int n = min(NCMAX, e1 - e);
4613            if (e != e0) {
4614                __syncthreads();
4615#pragma unroll
4616                for (int c = 0; c < NCMAX; ++c) dst[c] = ent_dst[min(e + c, e1 - 1)];
4617            }
4618            const uint32_t* src = reinterpret_cast<const uint32_t*>(hq + (size_t) e * 20);
4619            for (int i = tid; i < n * 180; i += 256) s_hq_buf[i] = src[i];
4620            __syncthreads();
4621#pragma unroll
4622            for (int p = 0; p < P; ++p) {
4623                const int rl = p * RPP + sub;
4624                if (rl >= nrow) continue;
4625                const uint8_t* wr = reinterpret_cast<const uint8_t*>(s_w) + rl * DROW;
4626                const int r = r0 + rl;
4627                if constexpr (NCMAX == 1) {
4628                    const int d1[1] = { dst[0] };
4629                    dws_rows<TD, 1>(wr, s_hq, t, sd, out, d1, L.n_embd, r);
4630                } else {
4631                    static_assert(NCMAX == 4, "NCMAX 1 or 4");
4632                    if (n == 1) {
4633                        const int d1[1] = { dst[0] };
4634                        dws_rows<TD, 1>(wr, s_hq, t, sd, out, d1, L.n_embd, r);
4635                    } else if (n == 2) {
4636                        const int d2[2] = { dst[0], dst[1] };
4637                        dws_rows<TD, 2>(wr, s_hq, t, sd, out, d2, L.n_embd, r);
4638                    } else if (n == 3) {
4639                        const int d3[3] = { dst[0], dst[1], dst[2] };
4640                        dws_rows<TD, 3>(wr, s_hq, t, sd, out, d3, L.n_embd, r);
4641                    } else {
4642                        const int d4[4] = { dst[0], dst[1], dst[2], dst[3] };
4643                        dws_rows<TD, 4>(wr, s_hq, t, sd, out, d4, L.n_embd, r);
4644                    }
4645                }
4646            }
4647        }
4648    }
4649}
4650#undef STRATA_DWS_VMAD
4651
4652// STRATA_DOWN_WS=1 on a compute capability 6.0 device: the IQ4_NL / Q2_0 down rows at n_ff 640 take
4653// native_down_ws_kernel (whatever the expert mode: it is bitwise mode 0's, and mode 8's matches mode 0)
4654bool down_ws_on(const NativeExpertLayout& L) {
4655    static const bool env = env_on("STRATA_DOWN_WS");
4656    if (!env || g_old_kernels || g_no_sub16_gu || L.n_ff != 640 || (L.d_type != 20 && L.d_type != 42)) return false;
4657    static int per_dev[64];   // 0 unknown, 1 no, 2 yes
4658    int dev = 0;
4659    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
4660    if (!per_dev[dev]) {
4661        int major = 0, minor = 0;
4662        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
4663        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
4664        per_dev[dev] = major == 6 && minor == 0 ? 2 : 1;
4665    }
4666    return per_dev[dev] == 2;
4667}
4668
4669void launch_down_ws(const NativeExpertLayout& L, int64_t gy, int64_t cap_groups, cudaStream_t s, const unsigned long long* grp_ptr,
4670                    const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_dst, const block_q8_1* hq, float* out) {
4671    const int rb = L.d_type == 20 ? 32 : 64;
4672    const dim3 grid((unsigned) ((L.n_embd + rb - 1) / rb), (unsigned) gy);
4673    const bool one = cap_groups <= 10;   // a T = 1 window: ten groups of one entry
4674    if (L.d_type == 20) {
4675        if (one) native_down_ws_kernel<20, 1><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4676        else native_down_ws_kernel<20, 4><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4677    } else {
4678        if (one) native_down_ws_kernel<42, 1><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4679        else native_down_ws_kernel<42, 4><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
4680    }
4681}
4682#endif  // STRATA_DOWN_WS_BUILT
4683
4684
4685// ---------------------------------------------------------------- STRATA_EXPERT_NIBBLE: gate/up on 4-bit slots
4686// (opt-in, default off; strata/core/expert_nibble.hpp has the slot layout and the item code).  A converted layer's
4687// VRAM slot holds each 32-weight item of a gate/up row as 16 bytes of 4-bit codes (one 16-byte load), its integer
4688// scale byte and the superblock's fp16 d bit for bit; the kernels below decode an item into the production
4689// Split<TG>::W (or IQ3_S's offset form) with 1-4 instructions per four weights instead of the codebook lookups, then
4690// run the production integer chain and float tail in the production lane / item / addition order (row_dot_80_sub16:
4691// k = t, t+32, t+64 into s, t+16, t+48 into s16, __fadd_rn, xor 8, 4, 2, 1), so every gate / up value is bit for bit
4692// native_gu_multi_kernel<TG, *, true>'s.  Two skeletons in the shape of native_gu_multi_kernel (grid (80, gy), 256
4693// threads, 16 lanes a row, a group's entries GRP_NC at a time, the group stride):
4694//   S  the entries' q8_1 blocks staged in shared memory, each item's code loaded and decoded where it is used, the
4695//      production apply on it (IQ3_S: v = 2u - 15 restored per byte - no sum of x)
4696//   P  the lane's five items' codes, scales and d loaded before the staging (in flight during it), the entries' qs
4697//      words staged as 16-byte rows and ds as a float, the production chain written out on the registers (IQ3_S:
4698//      sumi = 2 dot(u, x) - 15 sum(x) with sum(x) from the staged words: the same int32)
4699// Then the load-time transcoder, the GGUF rebuild (the start-up check and the prompt path's gather) and the slot hash.
4700// Built only with STRATA_EXPERT_NIBBLE_BUILT (a CUDA build with STRATA_EXPERIMENTAL_SM60); elsewhere a gu_nib layout
4701// stops in native_expert_grouped, and the switch is refused at start.
4702#if STRATA_EXPERT_NIBBLE_BUILT
4703namespace nibk = strata::core::nibble;
4704
4705__device__ __forceinline__ uint32_t nib_prmt(uint32_t a, uint32_t b, uint32_t sel) {
4706    uint32_t r;
4707    asm("prmt.b32 %0, %1, %2, %3;" : "=r"(r) : "r"(a), "r"(b), "r"(sel));   // the sign-replicate modes too
4708    return r;
4709}
4710
4711// One item's code -> the production W (what Split<TG>::load gives for the same GGUF item, byte for byte).
4712template<int TG> struct NibLoad;
4713template<> struct NibLoad<22> {   // IQ2_S: the nibble is the PRMT selector into {8,25,43,0} {-8,-25,-43,0}
4714    using W = Split<22>::W;
4715    __device__ static W load(uint4 q, uint32_t sc, __half d) {
4716        constexpr uint32_t T0 = 0x002B1908u, T1 = 0x00D5E7F8u;
4717        W r;
4718        const uint32_t qw[4] = { q.x, q.y, q.z, q.w };
4719#pragma unroll
4720        for (int m = 0; m < 4; ++m) {
4721            r.g[2 * m + 0] = (int) nib_prmt(T0, T1, qw[m]);
4722            r.g[2 * m + 1] = (int) nib_prmt(T0, T1, qw[m] >> 16);
4723        }
4724        r.ls0 = sc & 0x0F;
4725        r.ls1 = sc >> 4;
4726        r.dw = __half2float(d);
4727        return r;
4728    }
4729};
4730template<> struct NibLoad<18> {   // IQ3_XXS: magnitude PRMT into {4..62}, sign-replicated byte masks, (g ^ m) + (m & 1s)
4731    using W = Split<18>::W;
4732    __device__ static W load(uint4 q, uint32_t sc, __half d) {
4733        constexpr uint32_t T0 = 0x1C140C04u, T1 = 0x3E342C24u;   // {4,12,20,28} {36,44,52,62}
4734        W r;
4735        const uint32_t qw[4] = { q.x, q.y, q.z, q.w };
4736#pragma unroll
4737        for (int m = 0; m < 4; ++m) {
4738            const uint32_t w = qw[m], ms = w & 0x77777777u, a = w << 4;
4739            const uint32_t m0 = nib_prmt(a, w, 0xD9C8u), m1 = nib_prmt(a, w, 0xFBEAu);
4740            const uint32_t g0 = nib_prmt(T0, T1, ms), g1 = nib_prmt(T0, T1, ms >> 16);
4741            r.g[2 * m + 0] = (int) ((g0 ^ m0) + (m0 & 0x01010101u));
4742            r.g[2 * m + 1] = (int) ((g1 ^ m1) + (m1 & 0x01010101u));
4743        }
4744        r.ls = (int) sc;
4745        r.dw = __half2float(d);
4746        return r;
4747    }
4748};
4749template<> struct NibLoad<21> {   // IQ3_S: v = 2u - 15 per byte, ((2u | 0x80) - 0x0F) ^ 0x80 (every byte >= 0x80: no borrow)
4750    using W = Split<21>::W;
4751    __device__ static W load(uint4 q, uint32_t sc, __half d) {
4752        W r;
4753        const uint32_t qw[4] = { q.x, q.y, q.z, q.w };
4754#pragma unroll
4755        for (int m = 0; m < 4; ++m) {
4756            const uint32_t lo2 = (qw[m] << 1) & 0x1E1E1E1Eu, hi2 = (qw[m] >> 3) & 0x1E1E1E1Eu;   // 2u per byte
4757            r.g[2 * m + 0] = (int) (((lo2 | 0x80808080u) - 0x0F0F0F0Fu) ^ 0x80808080u);
4758            r.g[2 * m + 1] = (int) (((hi2 | 0x80808080u) - 0x0F0F0F0Fu) ^ 0x80808080u);
4759        }
4760        r.ls = (int) sc;
4761        r.dw = __half2float(d);
4762        return r;
4763    }
4764};
4765
4766// S skeleton row dot over one converted row (codes, scales, d of row `row`), x the staged blocks
4767template<int TG, int NC>
4768__device__ __forceinline__ void nib_row_dot_s(const uint4* __restrict__ crow, const uint8_t* __restrict__ srow,
4769                                              const __half* __restrict__ drow, const block_q8_1* x, const int (&off)[NC],
4770                                              int t, float (&s)[NC]) {
4771    using Q = NibLoad<TG>;
4772    const int iqs = 2 * (t & 7), kb = t >> 3;
4773    const block_q8_1* xb[NC];
4774#pragma unroll
4775    for (int c = 0; c < NC; ++c) { s[c] = 0.0f; xb[c] = x + off[c] + kb * 8; }
4776#pragma unroll
4777    for (int i = 0; i < 3; ++i) {
4778        const typename Q::W w = Q::load(crow[t + 32 * i], srow[t + 32 * i], drow[kb + 4 * i]);
4779#pragma unroll
4780        for (int c = 0; c < NC; ++c) s[c] += Split<TG>::apply(w, xb[c] + 32 * i, iqs);
4781    }
4782    float s16[NC];
4783#pragma unroll
4784    for (int c = 0; c < NC; ++c) s16[c] = 0.0f;
4785#pragma unroll
4786    for (int i = 0; i < 2; ++i) {
4787        const typename Q::W w = Q::load(crow[t + 16 + 32 * i], srow[t + 16 + 32 * i], drow[kb + 2 + 4 * i]);
4788#pragma unroll
4789        for (int c = 0; c < NC; ++c) s16[c] += Split<TG>::apply(w, xb[c] + 16 + 32 * i, iqs);
4790    }
4791#pragma unroll
4792    for (int c = 0; c < NC; ++c) {
4793        s[c] = __fadd_rn(s[c], s16[c]);
4794#pragma unroll
4795        for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
4796    }
4797}
4798
4799// One pass of the S skeleton: the n (1..GRP_NC) entries from e staged, then this thread's row against them.
4800// Block-uniform (e, n): every thread reaches both barriers.
4801template<int TG>
4802__device__ __forceinline__ void nib_pass_s(block_q8_1* s_x, const uint4* crow, const uint8_t* srow, const __half* drow,
4803                                           const int32_t* __restrict__ ent_tok, const block_q8_1* __restrict__ xq,
4804                                           int e, int n, int t, float* dst, int r) {
4805    int tok[GRP_NC];
4806#pragma unroll
4807    for (int c = 0; c < GRP_NC; ++c) tok[c] = ent_tok[e + min(c, n - 1)];
4808    __syncthreads();
4809    for (int i = threadIdx.x; i < n * 80 * 9; i += 256) {   // 80 blocks x 36 B an entry, as 9 words a block
4810        const int c = i / 720, rem = i % 720;
4811        ((int*) s_x)[c * 720 + rem] = ((const int*) (xq + (size_t) tok[c] * 80))[rem];
4812    }
4813    __syncthreads();
4814    if (n == 1) {
4815        const int o[1] = { 0 }; float s[1];
4816        nib_row_dot_s<TG, 1>(crow, srow, drow, s_x, o, t, s);
4817        if (t == 0) dst[(size_t) e * nibk::kNFf + r] = s[0];
4818    } else if (n == 2) {
4819        const int o[2] = { 0, 80 }; float s[2];
4820        nib_row_dot_s<TG, 2>(crow, srow, drow, s_x, o, t, s);
4821        if (t < 2) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t];
4822    } else if (n == 3) {
4823        const int o[3] = { 0, 80, 160 }; float s[3];
4824        nib_row_dot_s<TG, 3>(crow, srow, drow, s_x, o, t, s);
4825        if (t < 3) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t];
4826    } else {
4827        const int o[4] = { 0, 80, 160, 240 }; float s[4];
4828        nib_row_dot_s<TG, 4>(crow, srow, drow, s_x, o, t, s);
4829        if (t < 4) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t];
4830    }
4831}
4832
4833// P skeleton: x as two LDS.128 per item and entry, ds as the float __low2float gives
4834struct NibXQ { int4 a, b; };
4835
4836template<int TG>
4837__device__ __forceinline__ float nib_p_apply(const uint4& q, uint32_t sc, __half dh, const NibXQ& x, float dx, int xsum) {
4838    if constexpr (TG == 22) {   // SplitLs2::apply on the registers
4839        const typename NibLoad<22>::W w = NibLoad<22>::load(q, sc, dh);
4840        int sumi0 = 0, sumi1 = 0;
4841        sumi0 = ggml_cuda_dp4a(w.g[0], x.a.x, sumi0); sumi0 = ggml_cuda_dp4a(w.g[1], x.a.y, sumi0);
4842        sumi0 = ggml_cuda_dp4a(w.g[2], x.a.z, sumi0); sumi0 = ggml_cuda_dp4a(w.g[3], x.a.w, sumi0);
4843        sumi1 = ggml_cuda_dp4a(w.g[4], x.b.x, sumi1); sumi1 = ggml_cuda_dp4a(w.g[5], x.b.y, sumi1);
4844        sumi1 = ggml_cuda_dp4a(w.g[6], x.b.z, sumi1); sumi1 = ggml_cuda_dp4a(w.g[7], x.b.w, sumi1);
4845        const int sumi = (sumi0 * w.ls0 + sumi1 * w.ls1 + (sumi0 + sumi1) / 2) / 4;
4846        const float d = w.dw * dx;
4847        return d * sumi;
4848    } else if constexpr (TG == 18) {   // Split<18>::apply on the registers
4849        const typename NibLoad<18>::W w = NibLoad<18>::load(q, sc, dh);
4850        int sumi = 0;
4851        sumi = ggml_cuda_dp4a(w.g[0], x.a.x, sumi); sumi = ggml_cuda_dp4a(w.g[1], x.a.y, sumi);
4852        sumi = ggml_cuda_dp4a(w.g[2], x.a.z, sumi); sumi = ggml_cuda_dp4a(w.g[3], x.a.w, sumi);
4853        sumi = ggml_cuda_dp4a(w.g[4], x.b.x, sumi); sumi = ggml_cuda_dp4a(w.g[5], x.b.y, sumi);
4854        sumi = ggml_cuda_dp4a(w.g[6], x.b.z, sumi); sumi = ggml_cuda_dp4a(w.g[7], x.b.w, sumi);
4855        sumi = (w.ls * sumi + sumi / 2) / 2;
4856        const float d = w.dw * dx;
4857        return d * sumi;
4858    } else {   // IQ3_S, offset form: dot(v, x) = 2 dot(u, x) - 15 sum(x), exact (|2 dot(u, x)| < 2^17); then Split<21>'s
4859        int u[8];
4860        const uint32_t qw[4] = { q.x, q.y, q.z, q.w };
4861#pragma unroll
4862        for (int m = 0; m < 4; ++m) {
4863            u[2 * m + 0] = (int) (qw[m] & 0x0F0F0F0Fu);
4864            u[2 * m + 1] = (int) ((qw[m] >> 4) & 0x0F0F0F0Fu);
4865        }
4866        int sumu = 0;
4867        sumu = ggml_cuda_dp4a(u[0], x.a.x, sumu); sumu = ggml_cuda_dp4a(u[1], x.a.y, sumu);
4868        sumu = ggml_cuda_dp4a(u[2], x.a.z, sumu); sumu = ggml_cuda_dp4a(u[3], x.a.w, sumu);
4869        sumu = ggml_cuda_dp4a(u[4], x.b.x, sumu); sumu = ggml_cuda_dp4a(u[5], x.b.y, sumu);
4870        sumu = ggml_cuda_dp4a(u[6], x.b.z, sumu); sumu = ggml_cuda_dp4a(u[7], x.b.w, sumu);
4871        int sumi = 2 * sumu - 15 * xsum;
4872        sumi *= (int) sc;
4873        const float d = __half2float(dh) * dx;
4874        return d * sumi;
4875    }
4876}
4877
4878// the lane's items in the production order: k = t, t+32, t+64 (sum s), then t+16, t+48 (sum s16)
4879template<int TG, int NC>
4880__device__ __forceinline__ void nib_row_dot_p(const uint4 (&q)[5], const uint32_t (&sc)[5], const __half (&dh)[5],
4881                                              const NibXQ* __restrict__ sx, const float* __restrict__ sd,
4882                                              const int* __restrict__ sxs, int t, float (&s)[NC]) {
4883    constexpr int K[5] = { 0, 32, 64, 16, 48 };
4884#pragma unroll
4885    for (int c = 0; c < NC; ++c) s[c] = 0.0f;
4886#pragma unroll
4887    for (int i = 0; i < 3; ++i) {
4888        const int k = t + K[i];
4889#pragma unroll
4890        for (int c = 0; c < NC; ++c)
4891            s[c] += nib_p_apply<TG>(q[i], sc[i], dh[i], sx[c * 80 + k], sd[c * 80 + k], TG == 21 ? sxs[c * 80 + k] : 0);
4892    }
4893    float s16[NC];
4894#pragma unroll
4895    for (int c = 0; c < NC; ++c) s16[c] = 0.0f;
4896#pragma unroll
4897    for (int i = 3; i < 5; ++i) {
4898        const int k = t + K[i];
4899#pragma unroll
4900        for (int c = 0; c < NC; ++c)
4901            s16[c] += nib_p_apply<TG>(q[i], sc[i], dh[i], sx[c * 80 + k], sd[c * 80 + k], TG == 21 ? sxs[c * 80 + k] : 0);
4902    }
4903#pragma unroll
4904    for (int c = 0; c < NC; ++c) {
4905        s[c] = __fadd_rn(s[c], s16[c]);
4906#pragma unroll
4907        for (int o = 8; o > 0; o >>= 1) s[c] += __shfl_xor_sync(0xffffffffu, s[c], o);
4908    }
4909}
4910
4911// The P skeleton's work on one group: this lane's five items into registers, then the passes.  Block-uniform.
4912template<int TG>
4913__device__ __forceinline__ void nib_group_p(NibXQ* s_x, float* s_d, int* s_xs, const uint4* crow, const uint8_t* srow,
4914                                            const __half* drow, const int32_t* __restrict__ ent_tok,
4915                                            const block_q8_1* __restrict__ xq, int e0, int e1, int t, float* dst, int r) {
4916    const int kb = t >> 3;
4917    uint4 q[5]; uint32_t sc[5]; __half dh[5];
4918    q[0] = crow[t]; q[1] = crow[t + 32]; q[2] = crow[t + 64]; q[3] = crow[t + 16]; q[4] = crow[t + 48];
4919    sc[0] = srow[t]; sc[1] = srow[t + 32]; sc[2] = srow[t + 64]; sc[3] = srow[t + 16]; sc[4] = srow[t + 48];
4920    dh[0] = drow[kb]; dh[1] = drow[kb + 4]; dh[2] = drow[kb + 8]; dh[3] = drow[kb + 2]; dh[4] = drow[kb + 6];
4921    for (int e = e0; e < e1; e += GRP_NC) {
4922        const int n = min(GRP_NC, e1 - e);
4923        __syncthreads();
4924        for (int i = threadIdx.x; i < n * 80; i += 256) {
4925            const int c = i >= 240 ? 3 : i >= 160 ? 2 : i >= 80 ? 1 : 0, kk = i - 80 * c;
4926            const int tok = ent_tok[e + c];
4927            const int* src = (const int*) (xq + (size_t) tok * 80 + kk);
4928            NibXQ v;
4929            v.a = make_int4(src[1], src[2], src[3], src[4]);
4930            v.b = make_int4(src[5], src[6], src[7], src[8]);
4931            s_x[i] = v;
4932            s_d[i] = __low2float(xq[(size_t) tok * 80 + kk].ds);
4933            if constexpr (TG == 21) {   // sum(x): the production dp4a against 0x01010101 over the 8 qs words
4934                int xs = 0;
4935                xs = ggml_cuda_dp4a(v.a.x, 0x01010101, xs); xs = ggml_cuda_dp4a(v.a.y, 0x01010101, xs);
4936                xs = ggml_cuda_dp4a(v.a.z, 0x01010101, xs); xs = ggml_cuda_dp4a(v.a.w, 0x01010101, xs);
4937                xs = ggml_cuda_dp4a(v.b.x, 0x01010101, xs); xs = ggml_cuda_dp4a(v.b.y, 0x01010101, xs);
4938                xs = ggml_cuda_dp4a(v.b.z, 0x01010101, xs); xs = ggml_cuda_dp4a(v.b.w, 0x01010101, xs);
4939                s_xs[i] = xs;
4940            }
4941        }
4942        __syncthreads();
4943        if (n == 1) {
4944            float s[1]; nib_row_dot_p<TG, 1>(q, sc, dh, s_x, s_d, s_xs, t, s);
4945            if (t == 0) dst[(size_t) e * nibk::kNFf + r] = s[0];
4946        } else if (n == 2) {
4947            float s[2]; nib_row_dot_p<TG, 2>(q, sc, dh, s_x, s_d, s_xs, t, s);
4948            if (t < 2) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t];
4949        } else if (n == 3) {
4950            float s[3]; nib_row_dot_p<TG, 3>(q, sc, dh, s_x, s_d, s_xs, t, s);
4951            if (t < 3) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t];
4952        } else {
4953            float s[4]; nib_row_dot_p<TG, 4>(q, sc, dh, s_x, s_d, s_xs, t, s);
4954            if (t < 4) dst[(size_t) (e + t) * nibk::kNFf + r] = s[t];
4955        }
4956    }
4957}
4958
4959// SKEL kSkelS or kSkelP for every group.  grid (80, gy): 2 x 640 rows = 80 x 16, so every thread has a row and
4960// reaches every barrier.
4961constexpr int kNibSWords = GRP_NC * 80 * (int) (sizeof(block_q8_1) / 4);   // S: the blocks
4962constexpr int kNibXqWords = GRP_NC * 80 * (int) (sizeof(NibXQ) / 4);         // P: the qs rows, then ds, then sum(x)
4963template<int TG, int SKEL>
4964inline constexpr int kNibSmemWords = SKEL == nibk::kSkelS ? kNibSWords : kNibXqWords + GRP_NC * 80 + (TG == 21 ? GRP_NC * 80 : 0);
4965template<int TG, int SKEL>
4966__global__ void __launch_bounds__(256) nib_gu_kernel(const unsigned long long* __restrict__ grp_ptr,
4967                                                     const int32_t* __restrict__ grp_start,
4968                                                     const int32_t* __restrict__ n_groups,
4969                                                     const int32_t* __restrict__ ent_tok,
4970                                                     const block_q8_1* __restrict__ xq, float* __restrict__ gate,
4971                                                     float* __restrict__ up) {
4972    const int ng = *n_groups;
4973    if (blockIdx.y >= (unsigned) ng) return;
4974    STRATA_SHARED_ALIGN16_U32(s_buf, kNibSmemWords<TG, SKEL>);
4975    const int subwarp = threadIdx.x >> 4, t = threadIdx.x & 15;
4976    const int row = blockIdx.x * 16 + subwarp;   // 0 .. 2 n_ff
4977    const bool is_up = row >= nibk::kNFf;
4978    const int r = is_up ? row - (int) nibk::kNFf : row;
4979    float* dst = is_up ? up : gate;
4980    for (int g = blockIdx.y; g < ng; g += gridDim.y) {
4981        const uint8_t* slot = (const uint8_t*) grp_ptr[g];
4982        const uint4* crow = (const uint4*) (slot + nibk::kCodesOff) + (size_t) row * nibk::kItems;
4983        const uint8_t* srow = slot + nibk::kScOff + (size_t) row * nibk::kItems;
4984        const __half* drow = (const __half*) (slot + nibk::kDOff) + (size_t) row * nibk::kSuper;
4985        const int e0 = grp_start[g], e1 = grp_start[g + 1];
4986        if constexpr (SKEL == nibk::kSkelP) {
4987            nib_group_p<TG>((NibXQ*) s_buf, (float*) (s_buf + kNibXqWords), (int*) (s_buf + kNibXqWords + GRP_NC * 80),
4988                            crow, srow, drow, ent_tok, xq, e0, e1, t, dst, r);
4989        } else {
4990            for (int e = e0; e < e1; e += GRP_NC)
4991                nib_pass_s<TG>((block_q8_1*) s_buf, crow, srow, drow, ent_tok, xq, e, min(GRP_NC, e1 - e), t, dst, r);
4992        }
4993    }
4994}
4995
4996#include "nib_gu_proto.cuh"   // STRATA_NIB_GU_PROTO: the staged-once 4-bit gate/up kernel (id 31)
4997
4998int g_nib_variant = -1;   // native_expert_nib_set_variant (the bench / parity); -1 = expert_nibble.hpp's gu_skeleton
4999
5000// STRATA_NIB_GU_PROTO: unset / 0 = off (the S / P skeleton per format); 1 (or 31) = gu-proto 31 (the activations staged
5001// once per two row blocks with 16-byte loads, the production row dot).  Read once.
5002int nib_gu_proto_env() {
5003    static const int v = [] {
5004        const char* e = std::getenv("STRATA_NIB_GU_PROTO");
5005        int id = e != nullptr ? std::atoi(e) : 0;
5006        if (id == 1) id = 31;
5007        if (id != 31) id = 0;
5008        if (id != 0) std::fprintf(stderr, "native_expert_grouped: STRATA_NIB_GU_PROTO: 4-bit gate/up kernel gu-proto %d\n", id);
5009        return id;
5010    }();
5011    return v;
5012}
5013
5014// The gate/up of a converted layer's VRAM groups: native_gu_multi_kernel's grid and outputs.
5015void launch_gu_nib(const NativeExpertLayout& L, dim3 grid, cudaStream_t s, const unsigned long long* grp_ptr,
5016                   const int32_t* grp_start, const int32_t* n_groups, const int32_t* ent_tok, const block_q8_1* X,
5017                   float* gate, float* up) {
5018    if (g_nib_variant >= 10) {   // gu-proto (nib_gu_proto.cuh), forced by the bench / parity
5019        if (((uintptr_t) X & 15) != 0 ||
5020            !nibx_launch(L.gu_type, g_nib_variant, grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up)) {
5021            std::fprintf(stderr, "native_expert_grouped: gu-proto variant %d for type %d is not built (or x is not 16-aligned)\n",
5022                         g_nib_variant, L.gu_type);
5023            std::exit(1);
5024        }
5025        return;
5026    }
5027    // STRATA_NIB_GU_PROTO (opt-in, default off): the gu-proto kernel in place of the S / P skeleton - bitwise the
5028    // same gate / up (iq_nibble_parity (7), native_expert_bench --nibble --vs).  The 16-byte staging needs x 16-aligned
5029    // (verify's nat_xq_ rows are: a 256-aligned buffer, 2,880 B a token); otherwise the production kernel runs.
5030    if (g_nib_variant < 0) {
5031        const int pv = nib_gu_proto_env();
5032        if (pv != 0 && ((uintptr_t) X & 15) == 0 &&
5033            nibx_launch(L.gu_type, pv, grid, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up))
5034            return;
5035    }
5036    const int skel = g_nib_variant >= 0 ? (g_nib_variant == 1 ? nibk::kSkelP : nibk::kSkelS) : nibk::gu_skeleton(L.gu_type);
5037#define STRATA_NIB_GU(TG, S) \
5038    case TG * 2 + S: nib_gu_kernel<TG, S><<<grid, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, gate, up); break;
5039    switch (L.gu_type * 2 + skel) {
5040        STRATA_NIB_GU(22, 0) STRATA_NIB_GU(22, 1)
5041        STRATA_NIB_GU(18, 0) STRATA_NIB_GU(18, 1)
5042        STRATA_NIB_GU(21, 0) STRATA_NIB_GU(21, 1)
5043        default:
5044            std::fprintf(stderr, "native_expert_grouped: 4-bit gate/up type %d at %lld x %lld is not built\n", L.gu_type,
5045                         (long long) L.n_embd, (long long) L.n_ff);
5046            std::exit(1);
5047    }
5048#undef STRATA_NIB_GU
5049}
5050
5051// ---- the load-time transcoder (expert_nibble.hpp's transcode)
5052template<int TG>
5053__device__ __forceinline__ uint32_t nib_code(int v, bool& ok) {
5054    if constexpr (TG == 21) {   // v odd in -15..15 -> u = (v + 15) / 2
5055        if ((v & 1) == 0 || v < -15 || v > 15) { ok = false; return 0; }
5056        return (uint32_t) ((v + 15) >> 1);
5057    } else if constexpr (TG == 18) {   // index of {4, 12, ..., 52, 62} | sign << 3
5058        const int a = v < 0 ? -v : v;
5059        const int i = a == 62 ? 7 : ((a & 7) == 4 && a <= 52) ? (a - 4) >> 3 : -1;
5060        if (i < 0) { ok = false; return 0; }
5061        return (uint32_t) i | (v < 0 ? 8u : 0u);
5062    } else {   // IQ2_S: index of {8, 25, 43} | sign << 2
5063        const int a = v < 0 ? -v : v;
5064        const int i = a == 8 ? 0 : a == 25 ? 1 : a == 43 ? 2 : -1;
5065        if (i < 0) { ok = false; return 0; }
5066        return (uint32_t) i | (v < 0 ? 4u : 0u);
5067    }
5068}
5069
5070// The GGUF blocks (ggml-common.h): their size and the fp16 d at their start
5071template<int TG> struct NibBlk;
5072template<> struct NibBlk<22> { using B = block_iq2_s; };
5073template<> struct NibBlk<18> { using B = block_iq3_xxs; };
5074template<> struct NibBlk<21> { using B = block_iq3_s; };
5075
5076// One thread per (expert, row, item): the production load, the code, scale and d written, read back from memory and
5077// decoded with the kernels' own decoders, compared with the load's W (and, for IQ3_S, the P skeleton's u against v);
5078// `bad` counts the items that differ or hold a weight outside the code set.
5079template<int TG>
5080__global__ void __launch_bounds__(256) nib_transcode_kernel(const uint8_t* __restrict__ src, uint64_t raw_bytes,
5081                                                            uint64_t gu_row, uint64_t up_off,
5082                                                            const unsigned long long* __restrict__ slots, long long n,
5083                                                            unsigned long long* __restrict__ bad) {
5084    const long long i = (long long) blockIdx.x * blockDim.x + threadIdx.x;
5085    if (i >= n * nibk::kRows * nibk::kItems) return;
5086    const int k = (int) (i % nibk::kItems);
5087    const int row = (int) ((i / nibk::kItems) % nibk::kRows);
5088    const long long ex = i / (nibk::kItems * nibk::kRows);
5089    const bool is_up = row >= nibk::kNFf;
5090    const int r = is_up ? row - (int) nibk::kNFf : row;
5091    const uint8_t* wr = src + (size_t) ex * raw_bytes + (is_up ? up_off : 0) + (size_t) r * gu_row;
5092    const int kbx = k / Fmt<TG>::ipb, iqs = Fmt<TG>::step * (k % Fmt<TG>::ipb);
5093    using S = Split<TG>;
5094    const typename S::W w = S::template load<false>(wr, kbx, iqs, nullptr);
5095    bool ok = true;
5096    uint32_t words[4];
5097#pragma unroll
5098    for (int m = 0; m < 4; ++m) {
5099        const uint32_t g0 = (uint32_t) w.g[2 * m], g1 = (uint32_t) w.g[2 * m + 1];
5100        uint32_t word = 0;
5101#pragma unroll
5102        for (int b = 0; b < 4; ++b) {
5103            const uint32_t c0 = nib_code<TG>((int) (int8_t) (g0 >> (8 * b)), ok);
5104            const uint32_t c1 = nib_code<TG>((int) (int8_t) (g1 >> (8 * b)), ok);
5105            if constexpr (TG == 21) word |= (c0 | c1 << 4) << (8 * b);
5106            else word |= c0 << (4 * b) | c1 << (16 + 4 * b);
5107        }
5108        words[m] = word;
5109    }
5110    uint32_t sc;
5111    if constexpr (TG == 22) sc = (uint32_t) (w.ls0 | w.ls1 << 4);
5112    else sc = (uint32_t) w.ls;
5113    ok = ok && sc < 256u;
5114    uint8_t* slot = (uint8_t*) slots[ex];
5115    uint4* cp = (uint4*) (slot + nibk::code_off(row, k));
5116    uint8_t* sp = slot + nibk::scale_off(row, k);
5117    *cp = make_uint4(words[0], words[1], words[2], words[3]);
5118    *sp = (uint8_t) sc;
5119    const __half dsrc = ((const typename NibBlk<TG>::B*) wr + kbx)->d;   // the block's d, bit for bit
5120    __half dread = dsrc;
5121    if (k % Fmt<TG>::ipb == 0) {   // the superblock's first item writes its d
5122        __half* dp = (__half*) (slot + nibk::d_off(row, kbx));
5123        *dp = dsrc;
5124        dread = __ushort_as_half(*(volatile const unsigned short*) dp);
5125        ok = ok && __half_as_ushort(dread) == __half_as_ushort(dsrc);
5126    }
5127    // the code and the scale read back from memory and decoded as the kernels do
5128    const uint4 qb = __ldcv(cp);
5129    const uint32_t sb = *(volatile const uint8_t*) sp;
5130    const typename NibLoad<TG>::W v = NibLoad<TG>::load(qb, sb, dread);
5131#pragma unroll
5132    for (int j = 0; j < 8; ++j) ok = ok && v.g[j] == w.g[j];
5133    if constexpr (TG == 22) ok = ok && v.ls0 == w.ls0 && v.ls1 == w.ls1;
5134    else ok = ok && v.ls == w.ls;
5135    ok = ok && __float_as_uint(v.dw) == __float_as_uint(w.dw);
5136    if constexpr (TG == 21) {   // the P skeleton's u: 2u - 15 per byte is v
5137        const uint32_t qw[4] = { qb.x, qb.y, qb.z, qb.w };
5138#pragma unroll
5139        for (int m = 0; m < 4; ++m) {
5140            const uint32_t u0 = qw[m] & 0x0F0F0F0Fu, u1 = (qw[m] >> 4) & 0x0F0F0F0Fu;
5141            ok = ok && __vsub4(__vadd4(u0, u0), 0x0F0F0F0Fu) == (uint32_t) w.g[2 * m] &&
5142                 __vsub4(__vadd4(u1, u1), 0x0F0F0F0Fu) == (uint32_t) w.g[2 * m + 1];
5143        }
5144    }
5145    if (!ok) atomicAdd(bad, 1ull);
5146}
5147
5148// ---- the GGUF rebuild (expert_nibble.hpp's check_gguf and gather_gguf)
5149// The reverse codebooks: a group's magnitude pattern -> its grid index (0xFFFFFFFF: not in the grid).  32-bit
5150// entries for atomicCAS, which also counts a pattern two grid entries share (none in ggml's grids; then refused).
5151constexpr int kNibRev22 = 6561, kNibRev18 = 4096, kNibRev21 = 4096;   // 3^8 (IQ2_S: 8 weights), 8^4, 8^4 (4 weights)
5152__device__ uint32_t g_nib_rev22[kNibRev22];
5153__device__ uint32_t g_nib_rev18[kNibRev18];
5154__device__ uint32_t g_nib_rev21[kNibRev21];
5155__device__ unsigned long long g_nib_rev_bad;
5156
5157__device__ __forceinline__ int nib_mag22(uint32_t b) { return b == 8 ? 0 : b == 25 ? 1 : b == 43 ? 2 : -1; }
5158__device__ __forceinline__ int nib_mag18(uint32_t b) { return b == 62 ? 7 : ((b & 7) == 4 && b <= 52) ? (int) (b - 4) >> 3 : -1; }
5159__device__ __forceinline__ int nib_mag21(uint32_t b) { return (b & 1) && b <= 15 ? (int) (b - 1) >> 1 : -1; }
5160
5161__global__ void nib_rev_clear_kernel() {
5162    const int i = blockIdx.x * blockDim.x + threadIdx.x;
5163    if (i < kNibRev22) g_nib_rev22[i] = 0xFFFFFFFFu;
5164    if (i < kNibRev18) g_nib_rev18[i] = 0xFFFFFFFFu;
5165    if (i < kNibRev21) g_nib_rev21[i] = 0xFFFFFFFFu;
5166    if (i == 0) g_nib_rev_bad = 0;
5167}
5168__global__ void nib_rev_fill_kernel() {
5169    const int i = blockIdx.x * blockDim.x + threadIdx.x;
5170    uint32_t* tab = nullptr;
5171    int key = 0;
5172    bool ok = true;
5173    uint32_t idx = 0;
5174    if (i < 1024) {   // iq2s_grid: 8 bytes of {8, 25, 43}
5175        const uint64_t g = iq2s_grid[i];
5176        for (int j = 7; j >= 0; --j) { const int m = nib_mag22((uint32_t) (g >> (8 * j)) & 0xFF); ok = ok && m >= 0; key = key * 3 + (m < 0 ? 0 : m); }
5177        tab = g_nib_rev22; idx = (uint32_t) i;
5178    } else if (i < 1024 + 256) {   // iq3xxs_grid: 4 bytes of {4, ..., 62}
5179        const uint32_t g = iq3xxs_grid[i - 1024];
5180        for (int j = 3; j >= 0; --j) { const int m = nib_mag18((g >> (8 * j)) & 0xFF); ok = ok && m >= 0; key = key * 8 + (m < 0 ? 0 : m); }
5181        tab = g_nib_rev18; idx = (uint32_t) (i - 1024);
5182    } else if (i < 1024 + 256 + 512) {   // iq3s_grid: 4 bytes of {1, 3, ..., 15}
5183        const uint32_t g = iq3s_grid[i - 1280];
5184        for (int j = 3; j >= 0; --j) { const int m = nib_mag21((g >> (8 * j)) & 0xFF); ok = ok && m >= 0; key = key * 8 + (m < 0 ? 0 : m); }
5185        tab = g_nib_rev21; idx = (uint32_t) (i - 1280);
5186    } else {
5187        return;
5188    }
5189    if (!ok || atomicCAS(tab + key, 0xFFFFFFFFu, idx) != 0xFFFFFFFFu) atomicAdd(&g_nib_rev_bad, 1ull);
5190}
5191
5192// The bytes of GGUF block `s` of row `row`'s item `ib` (0..7) rebuilt from the slot into `blk` (shared memory, the
5193// block's first byte): the codes give each weight's magnitude index and sign, the reverse codebook the grid index,
5194// the scale byte and d are the block's own.  Disjoint bytes per item (IQ3_S: the even item writes the shared scale
5195// byte); item 0 writes d.
5196template<int TG>
5197__device__ __forceinline__ void nib_gguf_item(uint8_t* blk, int ib, const uint8_t* __restrict__ slot, int row, int k) {
5198    const uint4 q4 = *(const uint4*) (slot + nibk::code_off(row, k));
5199    const uint32_t w[4] = { q4.x, q4.y, q4.z, q4.w };
5200    const uint32_t sc = slot[nibk::scale_off(row, k)];
5201    if (ib == 0) {
5202        const uint8_t* dp = slot + nibk::d_off(row, k / 8);
5203        blk[0] = dp[0];
5204        blk[1] = dp[1];
5205    }
5206    if constexpr (TG == 22) {   // block_iq2_s: d, qs[32] grid low bits, qs[32] signs, qh[8], scales[8]
5207        uint32_t qh = 0;
5208#pragma unroll
5209        for (int l = 0; l < 4; ++l) {
5210            int key = 0;
5211            uint32_t sg = 0;
5212#pragma unroll
5213            for (int j = 7; j >= 0; --j) {
5214                const uint32_t c = j < 4 ? (w[l] >> (4 * j)) & 15u : (w[l] >> (16 + 4 * (j - 4))) & 15u;
5215                key = key * 3 + (int) (c & 3u);
5216                sg |= ((c >> 2) & 1u) << j;
5217            }
5218            const uint32_t idx = key < kNibRev22 ? g_nib_rev22[key] : 0xFFFFFFFFu;
5219            blk[2 + 4 * ib + l] = (uint8_t) idx;
5220            blk[2 + 32 + 4 * ib + l] = (uint8_t) sg;
5221            qh |= ((idx >> 8) & 3u) << (2 * l);
5222        }
5223        blk[66 + ib] = (uint8_t) qh;
5224        blk[74 + ib] = (uint8_t) sc;
5225    } else if constexpr (TG == 18) {   // block_iq3_xxs: d, qs[64] grid indices, 8 x aux32 (4 x 7 sign bits | scale << 28)
5226        uint32_t aux = sc << 28;
5227#pragma unroll
5228        for (int l = 0; l < 4; ++l) {
5229            uint32_t sg = 0;
5230#pragma unroll
5231            for (int h = 0; h < 2; ++h) {
5232                int key = 0;
5233#pragma unroll
5234                for (int j = 3; j >= 0; --j) {
5235                    const uint32_t c = (w[l] >> (16 * h + 4 * j)) & 15u;
5236                    key = key * 8 + (int) (c & 7u);
5237                    sg |= ((c >> 3) & 1u) << (4 * h + j);
5238                }
5239                blk[2 + 8 * ib + 2 * l + h] = (uint8_t) g_nib_rev18[key];
5240            }
5241            aux |= (sg & 0x7Fu) << (7 * l);   // the 8th sign is the parity of the other 7 (ksigns_iq2xs)
5242        }
5243        blk[2 + 64 + 4 * ib + 0] = (uint8_t) aux;
5244        blk[2 + 64 + 4 * ib + 1] = (uint8_t) (aux >> 8);
5245        blk[2 + 64 + 4 * ib + 2] = (uint8_t) (aux >> 16);
5246        blk[2 + 64 + 4 * ib + 3] = (uint8_t) (aux >> 24);
5247    } else {   // block_iq3_s: d, qs[64] grid low bits, qh[8], signs[32], scales[4] (two items' nibbles each)
5248        uint32_t qh = 0;
5249#pragma unroll
5250        for (int l = 0; l < 4; ++l) {
5251            uint32_t sg = 0;
5252#pragma unroll
5253            for (int h = 0; h < 2; ++h) {
5254                int key = 0;
5255#pragma unroll
5256                for (int j = 3; j >= 0; --j) {
5257                    const uint32_t u = (w[l] >> (8 * j + 4 * h)) & 15u;   // v = 2u - 15: negative for u <= 7
5258                    key = key * 8 + (int) (u <= 7u ? 7u - u : u - 8u);
5259                    sg |= (u <= 7u ? 1u : 0u) << (4 * h + j);
5260                }
5261                const uint32_t idx = g_nib_rev21[key];
5262                blk[2 + 8 * ib + 2 * l + h] = (uint8_t) idx;
5263                qh |= ((idx >> 8) & 1u) << (2 * l + h);
5264            }
5265            blk[74 + 4 * ib + l] = (uint8_t) sg;
5266        }
5267        blk[66 + ib] = (uint8_t) qh;
5268        if ((ib & 1) == 0) {
5269            const uint32_t sc1 = slot[nibk::scale_off(row, k + 1)];
5270            blk[106 + ib / 2] = (uint8_t) (((sc - 1u) >> 1) | (((sc1 - 1u) >> 1) << 4));
5271        }
5272    }
5273}
5274
5275constexpr int kNibGgufRows = 8;        // gate/up rows a block rebuilds (in shared memory, then one coalesced pass)
5276constexpr int kNibGgufThreads = 128;
5277constexpr int kNibGgufWords = 8;       // uint4 per thread in the down / tail part
5278struct NibGgufArgs {
5279    const unsigned long long* dev;     // the slots' device addresses (check), or nullptr: `p`
5280    const uint8_t* p[16];              // the slots (gather: an MMQ group, at most mmq::kGatherGroupMax)
5281    int first, n;
5282    uint8_t* gu;                       // gather: the rebuilt [gate | up]; check: the raw blobs' first byte
5283    uint64_t gu_stride;
5284    uint8_t* d;                        // gather: the down rows; check: the raw blobs' down rows
5285    uint64_t d_stride;
5286    uint64_t gu_row, down16, zero16;   // GGUF row bytes; down rows and MMQ tail in uint4
5287    unsigned long long* bad;           // check: 32-bit words / uint4 that differ
5288};
5289// blockIdx.y: expert first + y.  blockIdx.x < kRows / kNibGgufRows: rows [8x, 8x + 8) rebuilt into shared memory,
5290// then written (gather) or compared (check) as 32-bit words; the rest: the down rows as uint4, and (gather, the last
5291// expert) the zeroed tails after gate/up and down.
5292template<int TG, bool CHECK>
5293__global__ void __launch_bounds__(kNibGgufThreads) nib_gguf_kernel(NibGgufArgs a) {
5294    constexpr int BB = (int) sizeof(typename NibBlk<TG>::B);
5295    __shared__ uint32_t s_rows[kNibGgufRows * 1100 / 4];
5296    const int q = a.first + (int) blockIdx.y;
5297    const uint8_t* slot = a.dev != nullptr ? (const uint8_t*) a.dev[q] : a.p[q];
5298    constexpr int kRowBlocks = (int) (nibk::kRows / kNibGgufRows);
5299    unsigned long long nbad = 0;
5300    if ((int) blockIdx.x < kRowBlocks) {
5301        const int r0 = (int) blockIdx.x * kNibGgufRows;
5302        uint8_t* sb = (uint8_t*) s_rows;
5303        for (int u = threadIdx.x; u < kNibGgufRows * (int) nibk::kItems; u += kNibGgufThreads) {
5304            const int rr = u / (int) nibk::kItems, k = u % (int) nibk::kItems;
5305            nib_gguf_item<TG>(sb + (size_t) rr * a.gu_row + (size_t) (k >> 3) * BB, k & 7, slot, r0 + rr, k);
5306        }
5307        __syncthreads();
5308        const int nw = (int) (kNibGgufRows * a.gu_row / 4);
5309        uint32_t* dst = (uint32_t*) (a.gu + (size_t) q * a.gu_stride + (size_t) r0 * a.gu_row);
5310        for (int i = threadIdx.x; i < nw; i += kNibGgufThreads) {
5311            if constexpr (CHECK) nbad += dst[i] != s_rows[i];
5312            else dst[i] = s_rows[i];
5313        }
5314    } else {
5315        const uint4* src = (const uint4*) (slot + nibk::kDownOff);
5316        uint4* dd = (uint4*) (a.d + (size_t) q * a.d_stride);
5317        const int64_t base = ((int64_t) blockIdx.x - kRowBlocks) * (kNibGgufThreads * kNibGgufWords);
5318#pragma unroll
5319        for (int w = 0; w < kNibGgufWords; ++w) {
5320            const int64_t i = base + (int64_t) w * kNibGgufThreads + threadIdx.x;
5321            if (i < (int64_t) a.down16) {
5322                if constexpr (CHECK) {
5323                    const uint4 x = src[i], y = dd[i];
5324                    nbad += x.x != y.x || x.y != y.y || x.z != y.z || x.w != y.w;
5325                } else {
5326                    dd[i] = src[i];
5327                }
5328            } else if (!CHECK && q == a.n - 1 && i < (int64_t) (a.down16 + 2 * a.zero16)) {
5329                const int64_t z = i - (int64_t) a.down16;
5330                if (z < (int64_t) a.zero16) ((uint4*) (a.gu + (size_t) a.n * a.gu_stride))[z] = make_uint4(0, 0, 0, 0);
5331                else ((uint4*) (a.d + (size_t) a.n * a.d_stride))[z - (int64_t) a.zero16] = make_uint4(0, 0, 0, 0);
5332            }
5333        }
5334    }
5335    if constexpr (CHECK) {
5336        if (nbad) atomicAdd(a.bad, nbad);
5337    }
5338}
5339
5340// sum_i (w_i ^ i) * kHashMul mod 2^64 over the first `bytes` bytes of each slot (little-endian words, the last one
5341// zero-extended): expert_nibble.hpp's hash_host.  A sum, so the blocks' order of adding does not change it.
5342__global__ void __launch_bounds__(256) nib_hash_kernel(const unsigned long long* __restrict__ slots, uint64_t bytes,
5343                                                       unsigned long long* __restrict__ out) {
5344    const uint8_t* p = (const uint8_t*) slots[blockIdx.y];
5345    const uint64_t n16 = bytes / 16, nw = (bytes + 3) / 4;
5346    uint64_t h = 0;
5347    for (uint64_t q = (uint64_t) blockIdx.x * blockDim.x + threadIdx.x; q < n16; q += (uint64_t) gridDim.x * blockDim.x) {
5348        const uint4 v = ((const uint4*) p)[q];
5349        const uint32_t i = (uint32_t) (4 * q);
5350        h += (uint64_t) (v.x ^ i) * nibk::kHashMul + (uint64_t) (v.y ^ (i + 1)) * nibk::kHashMul +
5351             (uint64_t) (v.z ^ (i + 2)) * nibk::kHashMul + (uint64_t) (v.w ^ (i + 3)) * nibk::kHashMul;
5352    }
5353    if (blockIdx.x == 0)
5354        for (uint64_t i = 4 * n16 + threadIdx.x; i < nw; i += blockDim.x) {
5355            uint32_t w = 0;
5356            for (uint64_t b = 4 * i; b < 4 * i + 4 && b < bytes; ++b) w |= (uint32_t) p[b] << (8 * (b - 4 * i));
5357            h += (uint64_t) (w ^ (uint32_t) i) * nibk::kHashMul;
5358        }
5359#pragma unroll
5360    for (int o = 16; o > 0; o >>= 1) h += __shfl_xor_sync(0xffffffffu, h, o);
5361    __shared__ uint64_t s_h[8];
5362    if ((threadIdx.x & 31) == 0) s_h[threadIdx.x >> 5] = h;
5363    __syncthreads();
5364    if (threadIdx.x == 0) {
5365        uint64_t t = 0;
5366        for (int w = 0; w < (int) (blockDim.x >> 5); ++w) t += s_h[w];
5367        atomicAdd(out + blockIdx.y, (unsigned long long) t);
5368    }
5369}
5370#endif  // STRATA_EXPERT_NIBBLE_BUILT
5371
5372// STRATA_EXPERT_NIBBLE: whether a layout's gate/up is a converted slot's 4-bit codes (constant false in a build
5373// without the kernels, so its dispatch below is today's code)
5374constexpr bool nib_layout(const NativeExpertLayout& L) {
5375#if STRATA_EXPERT_NIBBLE_BUILT
5376    return L.gu_nib;
5377#else
5378    static_cast<void>(L);
5379    return false;
5380#endif
5381}
5382
5383}  // namespace
5384
5385void iq_set_old_kernels(bool old) { g_old_kernels = old; }
5386bool iq_old_kernels() { return g_old_kernels; }
5387
5388bool iq_supported(int t) noexcept { return is_iq(t); }
5389// BF16 and Q6_K: embedding only (dq_dispatch has them; no expert or prompt-path kernels take them)
5390bool embed_type_supported(int t) noexcept { return is_iq(t) || t == 30 || t == 14; }
5391
5392size_t iq_row_bytes(int t, int64_t n) noexcept {
5393    switch (t) {
5394        case 16: return (size_t) (n / 256) * sizeof(block_iq2_xxs);
5395        case 17: return (size_t) (n / 256) * sizeof(block_iq2_xs);
5396        case 18: return (size_t) (n / 256) * sizeof(block_iq3_xxs);
5397        case 20: return (size_t) (n / 32) * sizeof(block_iq4_nl);
5398        case 21: return (size_t) (n / 256) * sizeof(block_iq3_s);
5399        case 22: return (size_t) (n / 256) * sizeof(block_iq2_s);
5400        case 29: return (size_t) (n / 256) * sizeof(block_iq1_m);
5401        case 23: return (size_t) (n / 256) * sizeof(block_iq4_xs);
5402        case 11: return (size_t) (n / 256) * sizeof(block_q3_K);
5403        case 42: return (size_t) (n / 64) * sizeof(block_q2_0);
5404        case 12: return (size_t) (n / 256) * sizeof(block_q4_K);
5405        case 13: return (size_t) (n / 256) * sizeof(block_q5_K);
5406        case 14: return (size_t) (n / 256) * sizeof(block_q6_K);
5407        case 7: return (size_t) (n / 32) * sizeof(block_q5_1);
5408        case 6: return (size_t) (n / 32) * sizeof(block_q5_0);
5409        case 2: return (size_t) (n / 32) * sizeof(block_q4_0);
5410        case 3: return (size_t) (n / 32) * sizeof(block_q4_1);
5411        case 40: return (size_t) (n / 64) * sizeof(block_nvfp4);
5412        case 8: return (size_t) (n / 32) * sizeof(block_q8_0);
5413        case 30: return (size_t) n * 2;   // BF16: the token embedding only (iq_embed_rows, iq_dequant_f32)
5414        case 144: return (size_t) (n / 128) * sizeof(block_tq2_t);   // APR trellis types
5415        case 145: return (size_t) (n / 128) * sizeof(block_tqk6);
5416        case 146: return (size_t) (n / 128) * sizeof(block_tqk7);
5417        case 147: return (size_t) (n / 128) * sizeof(block_tqp5);
5418        case 148: return (size_t) (n / 128) * sizeof(block_tqp6);
5419        case 149: return (size_t) (n / 128) * sizeof(block_tqp7);
5420        default: return 0;
5421    }
5422}
5423
5424void quantize_q8_1_rows(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) {
5425    const long long n = (long long) n_rows * n_cols;
5426    if (n <= 0) return;
5427    quantize_q8_1_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, (cudaStream_t) stream>>>(x, (block_q8_1*) y, n);
5428    check("quantize_q8_1_rows");
5429}
5430
5431void iq_mmvq(int t, const void* w, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
5432    const size_t rb = iq_row_bytes(t, n_in);
5433    cudaStream_t s = (cudaStream_t) stream;
5434    const auto* W = (const uint8_t*) w;
5435    const auto* X = (const block_q8_1*) x_q8_1;
5436    switch (t) {
5437#define STRATA_MMVQ(T) case T: launch_mmvq<T>(W, rb, X, y, n_in, n_out, ncols, s); break;
5438        STRATA_MMVQ_FMTS(STRATA_MMVQ)
5439#undef STRATA_MMVQ
5440        default: std::fprintf(stderr, "iq_mmvq: type %d is not supported\n", t); std::exit(1);
5441    }
5442    check("iq_mmvq");
5443}
5444
5445void iq_dequant_f16(int t, const void* src, int64_t n, uint16_t* dst, void* stream, const float* scale) {
5446    if (n % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_f16: bad arguments\n"); std::exit(1); }
5447    dequant_flat_kernel<__half><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, (__half*) dst, scale);
5448    check("iq_dequant_f16");
5449}
5450
5451namespace {
5452__global__ void embed_rows_kernel(int ty, const uint8_t* __restrict__ table, size_t row_bytes,
5453                                  const int32_t* __restrict__ tokens, int64_t n_embd, float* __restrict__ y) {
5454    const int t = blockIdx.y;
5455    const int64_t b = blockIdx.x;
5456    const uint8_t* row = table + (size_t) tokens[t] * row_bytes;
5457    dq_dispatch<float>(ty, row, b, y + (size_t) t * n_embd + b * QK_K, threadIdx.x);
5458}
5459}  // namespace
5460
5461void iq_embed_rows(int t, const void* table, size_t row_bytes, const int32_t* tokens, int64_t n_tok, int64_t n_embd,
5462                   float* out, void* stream) {
5463    if (n_tok <= 0) return;
5464    if (n_embd % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_embed_rows: bad arguments\n"); std::exit(1); }
5465    embed_rows_kernel<<<dim3((unsigned) (n_embd / 256), (unsigned) n_tok), 32, 0, (cudaStream_t) stream>>>(
5466        t, (const uint8_t*) table, row_bytes, tokens, n_embd, out);
5467    check("iq_embed_rows");
5468}
5469
5470void iq_dequant_f32(int t, const void* src, int64_t n, float* dst, void* stream) {
5471    if (n % 256 != 0 || !embed_type_supported(t)) { std::fprintf(stderr, "iq_dequant_f32: bad arguments\n"); std::exit(1); }
5472    dequant_flat_kernel<float><<<(unsigned) (n / 256), 32, 0, (cudaStream_t) stream>>>(t, src, dst, nullptr);
5473    check("iq_dequant_f32");
5474}
5475
5476void iq_dequant_gu_f16(int t, const void* gate, const void* up, int64_t n_ff, int64_t n_embd, uint16_t* dst, void* stream,
5477                       const float* tail) {
5478    // checked like the other entry points: an unknown type used to leave `dst` unwritten, a wrong prompt and no error
5479    if (n_embd % 256 != 0 || !is_iq(t)) { std::fprintf(stderr, "iq_dequant_gu_f16: type %d / %lld\n", t, (long long) n_embd); std::exit(1); }
5480    const int64_t per_row = n_embd / 256;
5481    dequant_gu_kernel<<<dim3((unsigned) (n_ff * per_row), 2), 32, 0, (cudaStream_t) stream>>>(t, gate, up, per_row,
5482                                                                                           (__half*) dst, tail);
5483    check("iq_dequant_gu_f16");
5484}
5485
5486// A bad block is a pack or caller error (expert_layout_load already refuses a block that does not divide the expert
5487// widths): it exits with a message, like check() does for a failed launch.
5488namespace {
5489void hadamard_bad_block(const char* what, int block, int64_t width) {
5490    std::fprintf(stderr, "%s: Hadamard block %d is not a power of two in [2, 1024] dividing the row width %lld "
5491                         "(hadamard.txt's block and the expert widths disagree)\n", what, block, (long long) width);
5492    std::exit(1);
5493}
5494constexpr int64_t kHadamardMaxRows = 65535;   // gridDim.y
5495bool hadamard_block_ok(int block, int64_t width) {
5496    return block >= 2 && block <= 1024 && (block & (block - 1)) == 0 && width % block == 0;
5497}
5498}  // namespace
5499
5500void hadamard_rows(const float* x, float* y, int64_t rows, int64_t width, int block, const float* signs, void* stream) {
5501    if (rows <= 0) return;
5502    if (!hadamard_block_ok(block, width)) hadamard_bad_block("hadamard_rows", block, width);
5503    // gridDim.y is limited to 65535: a prompt chunk's T * K rows (16K tokens x 10 experts) go up in slices
5504    for (int64_t r0 = 0; r0 < rows; r0 += kHadamardMaxRows) {
5505        const int64_t n = std::min<int64_t>(kHadamardMaxRows, rows - r0);
5506        hadamard_rows_kernel<float><<<dim3((unsigned) (width / block), (unsigned) n), block, block * sizeof(float),
5507                                      (cudaStream_t) stream>>>(x + r0 * width, y + r0 * width, width, signs,
5508                                                               1.0f / std::sqrt((float) block));
5509    }
5510    check("hadamard_rows");
5511}
5512
5513void hadamard_rows_f16(uint16_t* x, int64_t rows, int64_t width, int block, const float* signs, void* stream) {
5514    if (rows <= 0) return;
5515    if (!hadamard_block_ok(block, width)) hadamard_bad_block("hadamard_rows_f16", block, width);
5516    for (int64_t r0 = 0; r0 < rows; r0 += kHadamardMaxRows) {   // gridDim.y <= 65535, as in hadamard_rows
5517        const int64_t n = std::min<int64_t>(kHadamardMaxRows, rows - r0);
5518        hadamard_rows_kernel<__half><<<dim3((unsigned) (width / block), (unsigned) n), block, block * sizeof(float),
5519                                       (cudaStream_t) stream>>>((const __half*) x + r0 * width, (__half*) x + r0 * width,
5520                                                                width, signs, 1.0f / std::sqrt((float) block));
5521    }
5522    check("hadamard_rows_f16");
5523}
5524
5525const float* hadamard_device_signs(const float* host, int width) {
5526    if (host == nullptr || width <= 0) return nullptr;
5527    static std::mutex mu;
5528    static std::map<std::tuple<int, const float*, int>, float*> table;   // (device, host vector, width)
5529    int dev = 0;
5530    cudaGetDevice(&dev);
5531    std::lock_guard<std::mutex> lock(mu);
5532    float*& d = table[std::make_tuple(dev, host, width)];
5533    if (d == nullptr) {
5534        if (cudaMalloc((void**) &d, (size_t) width * sizeof(float)) != cudaSuccess ||
5535            cudaMemcpy(d, host, (size_t) width * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) {
5536            std::fprintf(stderr, "hadamard_device_signs: %s\n", cudaGetErrorString(cudaGetLastError()));
5537            std::exit(1);
5538        }
5539    }
5540    return d;
5541}
5542
5543// Q3_K shared column scales: x = diag(1/s) x row-wise, the ONE multiply every expert-activation consumer sees
5544// (hadamard_rows above is the structural template: one row per gridDim.y, width split over gridDim.x, the
5545// kHadamardMaxRows slices keep gridDim.y <= 65535).
5546__global__ void lat_colscale_rows_kernel(float* __restrict__ x, int width, const float* __restrict__ inv) {
5547    const int c = (int) blockIdx.x * blockDim.x + threadIdx.x;   // one column per lane, one row per blockIdx.y
5548    if (c < width) x[(int64_t) blockIdx.y * width + c] *= inv[c];
5549}
5550
5551void lat_colscale_rows(float* x, int64_t rows, int width, const float* inv, void* stream) {
5552    if (rows <= 0 || inv == nullptr) return;
5553    const int block = 128;
5554    for (int64_t r0 = 0; r0 < rows; r0 += kHadamardMaxRows) {   // gridDim.y <= 65535, as in hadamard_rows
5555        const int64_t n = std::min<int64_t>(kHadamardMaxRows, rows - r0);
5556        lat_colscale_rows_kernel<<<dim3((unsigned) ((width + block - 1) / block), (unsigned) n), block, 0,
5557                                   (cudaStream_t) stream>>>(x + r0 * width, width, inv);
5558    }
5559    check("lat_colscale_rows");
5560}
5561
5562const float* lat_gu_colscale_dev(int layer, int width) {
5563    int stored = 0;
5564    const float* host = lat_gu_colscale_host(layer, &stored);
5565    if (host == nullptr || width <= 0) return nullptr;
5566    if (stored != width) {   // the manifest's n_embd is the truth; a mismatched caller would read OOB host memory
5567        std::fprintf(stderr, "lat_gu_colscale_dev: layer %d stores %d values, the caller wants width %d\n",
5568                     layer, stored, width);
5569        return nullptr;
5570    }
5571    static std::mutex mu;
5572    static std::map<std::tuple<int, int, const float*>, float*> table;   // (device, layer, host vector)
5573    int dev = 0;
5574    cudaGetDevice(&dev);
5575    std::lock_guard<std::mutex> lock(mu);
5576    float*& d = table[std::make_tuple(dev, layer, host)];
5577    if (d == nullptr) {
5578        if (cudaMalloc((void**) &d, (size_t) width * sizeof(float)) != cudaSuccess ||
5579            cudaMemcpy(d, host, (size_t) width * sizeof(float), cudaMemcpyHostToDevice) != cudaSuccess) {
5580            std::fprintf(stderr, "lat_gu_colscale_dev: %s\n", cudaGetErrorString(cudaGetLastError()));
5581            std::exit(1);
5582        }
5583    }
5584    return d;
5585}
5586
5587bool native_expert_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept {
5588    const int qg = gu_qk(gu_type), qd = d_qk(d_type);
5589    // a type without row bytes would make every row (and the up/down offsets) 0: refused, not run wrong
5590    return qg > 0 && qd > 0 && iq_row_bytes(gu_type, n_embd) > 0 && iq_row_bytes(d_type, n_ff) > 0 && is_iq(gu_type) && is_iq(d_type) && n_embd % qg == 0 && n_ff % qd == 0 &&
5591           n_embd % 256 == 0 && (n_ff * n_embd) % 256 == 0;
5592}
5593
5594NativeExpertLayout native_expert_layout(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
5595    NativeExpertLayout L;
5596    L.gu_type = gu_type;
5597    L.d_type = d_type;
5598    L.n_embd = n_embd;
5599    L.n_ff = n_ff;
5600    L.gu_row = iq_row_bytes(gu_type, n_embd);
5601    L.d_row = iq_row_bytes(d_type, n_ff);
5602    L.up_off = (size_t) n_ff * L.gu_row;
5603    L.down_off = 2 * L.up_off;
5604    L.bytes = L.down_off + (size_t) n_embd * L.d_row;
5605    // NVFP4: {s_gate, s_up, s_down, 0} after down (tools/iq_pack.py) whenever any projection is NVFP4; a mixed
5606    // expert's other projection has 1.0 there, so the kernels below multiply by it unconditionally
5607    if (gu_type == 40 || d_type == 40) {
5608        L.tail_off = L.bytes;
5609        L.bytes += 16;
5610    }
5611    return L;
5612}
5613
5614NativeExpertLayout native_expert_layout_nib(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) {
5615    namespace nb = strata::core::nibble;
5616    NativeExpertLayout L = native_expert_layout(gu_type, d_type, n_embd, n_ff);
5617    L.gu_nib = true;
5618    L.gu_row = (size_t) (nb::kItems * nb::kItemBytes);   // a row's codes (the scales and d follow all the codes)
5619    L.up_off = nb::kUpCodesOff;
5620    L.down_off = nb::kDownOff;
5621    L.bytes = nb::slot_bytes_for((uint64_t) n_embd * L.d_row);
5622    return L;
5623}
5624
5625bool native_expert_nib_supported(int gu_type, int d_type, int64_t n_embd, int64_t n_ff) noexcept {
5626#if STRATA_EXPERT_NIBBLE_BUILT
5627    namespace nb = strata::core::nibble;
5628    return nb::fmt_built(gu_type) && n_embd == nb::kNEmbd && n_ff == nb::kNFf && d_type != 40 &&
5629           native_expert_supported(gu_type, d_type, n_embd, n_ff);
5630#else
5631    (void) gu_type; (void) d_type; (void) n_embd; (void) n_ff;
5632    return false;
5633#endif
5634}
5635
5636void native_expert_nib_set_variant(int v) {
5637#if STRATA_EXPERT_NIBBLE_BUILT
5638    g_nib_variant = v;
5639#else
5640    (void) v;
5641#endif
5642}
5643
5644bool native_expert_nib_variant_attr(int v, int gu_type, int* regs, int* local_bytes, int* blocks_per_sm) {
5645#if STRATA_EXPERT_NIBBLE_BUILT
5646    cudaFuncAttributes a{};
5647    if (!nibx_launch(gu_type, v, dim3(80, 1), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &a)) return false;
5648    *regs = a.numRegs;
5649    *local_bytes = (int) a.localSizeBytes;
5650    *blocks_per_sm = g_nibx_occ;
5651    return true;
5652#else
5653    (void) v; (void) gu_type; (void) regs; (void) local_bytes; (void) blocks_per_sm;
5654    return false;
5655#endif
5656}
5657
5658size_t native_expert_scratch_bytes(int64_t cap, int64_t n_ff) {
5659    const size_t f = (size_t) cap * (size_t) n_ff * sizeof(float);
5660    return 3 * ((f + 255) & ~(size_t) 255) + (((size_t) cap * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255);
5661}
5662
5663
5664// The AMD layouts below (STRATA_EXP_MODE) also build for CUDA: Volta takes mode 8 by default (exp_mode), every
5665// other CUDA card keeps mode 0, the CUDA layout above.
5666#if 1  // dflash2-kern: the layouts build for every HIP arch too (default mode stays 0 off gfx906; STRATA_EXP_MODE picks one)
5667#define STRATA_EXP_LAYOUTS 1
5668#else
5669#define STRATA_EXP_LAYOUTS 0
5670#endif
5671#if defined(STRATA_HIP_GFX906)
5672constexpr int kExpModeDefault = 7;
5673constexpr int kExpFallback = 2;   // modes 5-8 on a format without an LDS kernel: R2
5674constexpr bool kExpLds16 = false; // IQ2_XXS gate/up: R2 as measured on gfx906
5675#else
5676constexpr int kExpModeDefault = 0;
5677constexpr int kExpFallback = 0;   // ... the CUDA layout (V100, IQ2_XXS gate/up: R2 183 us vs 113)
5678constexpr bool kExpLds16 = true;  // IQ2_XXS gate/up in LDS too
5679#endif
5680#if STRATA_EXP_LAYOUTS
5681// ---- AMD layouts for the grouped native experts (STRATA_EXP_MODE; 0 = the CUDA one above).
5682// 1 (W64): a row per 64-lane wavefront - 4x the wavefronts, ~1-2 calls per lane, a 64-lane butterfly.
5683// 2 (R2):  a 32-lane logical warp computes TWO rows in one loop - two independent load chains in flight.
5684// Either way a (row, entry) sum does not depend on the window size.
5685template<int TY>
5686__device__ __forceinline__ float row_dot64(const uint8_t* row, const block_q8_1* x, int nb, int lane) {
5687    using F = Fmt<TY>;
5688    float s = 0.0f;
5689    for (int k = lane; k < nb * F::ipb; k += 64) {
5690        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
5691        s += F::dot(row, x + kbx * (F::qk / 32), kbx, iqs);
5692    }
5693#pragma unroll
5694#if defined(__HIPCC__)
5695    for (int o = 32; o > 0; o >>= 1) s += __shfl_xor(s, o, 64);
5696#else
5697    __trap();   // a 64-lane wavefront: mode 1 is gfx906's only
5698#endif
5699    return s;
5700}
5701template<int TY>
5702__device__ __forceinline__ void row_dot2(const uint8_t* r0, const uint8_t* r1, const block_q8_1* x, int nb, int lane,
5703                                         float& o0, float& o1) {
5704    using F = Fmt<TY>;
5705    float s0 = 0.0f, s1 = 0.0f;
5706    for (int k = lane; k < nb * F::ipb; k += 32) {
5707        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
5708        const block_q8_1* xk = x + kbx * (F::qk / 32);
5709        const float a = F::dot(r0, xk, kbx, iqs);
5710        const float b = F::dot(r1, xk, kbx, iqs);
5711        s0 += a;
5712        s1 += b;
5713    }
5714    o0 = warp_sum(s0);
5715    o1 = warp_sum(s1);
5716}
5717template<int TY, int NR>
5718__device__ __forceinline__ void row_dotn(const uint8_t* const* r, const block_q8_1* x, int nb, int lane, float* o) {
5719    using F = Fmt<TY>;
5720    float acc[NR];
5721#pragma unroll
5722    for (int i = 0; i < NR; ++i) acc[i] = 0.0f;
5723    for (int k = lane; k < nb * F::ipb; k += 32) {
5724        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
5725        const block_q8_1* xk = x + kbx * (F::qk / 32);
5726        float d[NR];
5727#pragma unroll
5728        for (int i = 0; i < NR; ++i) d[i] = F::dot(r[i], xk, kbx, iqs);
5729#pragma unroll
5730        for (int i = 0; i < NR; ++i) acc[i] += d[i];
5731    }
5732#pragma unroll
5733    for (int i = 0; i < NR; ++i) o[i] = warp_sum(acc[i]);
5734}
5735template<int TG, int MODE>
5736__global__ void __launch_bounds__(256) native_gu_amd_kernel(const unsigned long long* __restrict__ grp_ptr,
5737                                                            const int32_t* __restrict__ grp_start,
5738                                                            const int32_t* __restrict__ n_groups,
5739                                                            const int32_t* __restrict__ ent_tok,
5740                                                            const block_q8_1* __restrict__ xq, NativeExpertLayout L,
5741                                                            float* __restrict__ gate, float* __restrict__ up) {
5742    const int g = blockIdx.y;
5743    if (g >= *n_groups) return;
5744    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
5745    const int nb = (int) (L.n_embd / Fmt<TG>::qk), xb = (int) (L.n_embd / 32);
5746    const int e0 = grp_start[g], e1 = grp_start[g + 1];
5747    const int nrow = 2 * (int) L.n_ff;
5748    auto wrow = [&](int row) -> const uint8_t* {
5749        const bool is_up = row >= L.n_ff;
5750        return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;
5751    };
5752    auto put = [&](int row, int e, float v) {
5753        const bool is_up = row >= L.n_ff;
5754        (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;
5755    };
5756    if constexpr (MODE == 1) {
5757        const int lane = threadIdx.x & 63, row = blockIdx.x * 4 + (threadIdx.x >> 6);
5758        if (row >= nrow) return;
5759        const uint8_t* wr = wrow(row);
5760        for (int e = e0; e < e1; ++e) {
5761            const float v = row_dot64<TG>(wr, xq + (size_t) ent_tok[e] * xb, nb, lane);
5762            if (lane == 0) put(row, e, v);
5763        }
5764    } else if constexpr (MODE == 4) {
5765        const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
5766        const int row0 = blockIdx.x * 32 + warp;
5767        if (row0 >= nrow) return;
5768        const uint8_t* w[4];
5769#pragma unroll
5770        for (int i = 0; i < 4; ++i) w[i] = wrow(row0 + 8 * i < nrow ? row0 + 8 * i : row0);
5771        for (int e = e0; e < e1; ++e) {
5772            float o[4];
5773            row_dotn<TG, 4>(w, xq + (size_t) ent_tok[e] * xb, nb, lane, o);
5774            if (lane == 0)
5775#pragma unroll
5776                for (int i = 0; i < 4; ++i) if (row0 + 8 * i < nrow) put(row0 + 8 * i, e, o[i]);
5777        }
5778    } else {
5779        const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
5780        const int row0 = blockIdx.x * 16 + warp, row1 = row0 + 8;
5781        if (row0 >= nrow) return;
5782        const bool two = row1 < nrow;
5783        const uint8_t* w0 = wrow(row0);
5784        const uint8_t* w1 = wrow(two ? row1 : row0);
5785        for (int e = e0; e < e1; ++e) {
5786            float a, b;
5787            row_dot2<TG>(w0, w1, xq + (size_t) ent_tok[e] * xb, nb, lane, a, b);
5788            if (lane == 0) { put(row0, e, a); if (two) put(row1, e, b); }
5789        }
5790    }
5791}
5792template<int TD, int MODE>
5793__global__ void __launch_bounds__(256) native_down_amd_kernel(const unsigned long long* __restrict__ grp_ptr,
5794                                                              const int32_t* __restrict__ grp_start,
5795                                                              const int32_t* __restrict__ n_groups,
5796                                                              const int32_t* __restrict__ ent_dst,
5797                                                              const block_q8_1* __restrict__ hq, NativeExpertLayout L,
5798                                                              float* __restrict__ out) {
5799    const int g = blockIdx.y;
5800    if (g >= *n_groups) return;
5801    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
5802    const int nb = (int) (L.n_ff / Fmt<TD>::qk), hb = (int) (L.n_ff / 32);
5803    const int e0 = grp_start[g], e1 = grp_start[g + 1];
5804    const int nrow = (int) L.n_embd;
5805    if constexpr (MODE == 1) {
5806        const int lane = threadIdx.x & 63, r = blockIdx.x * 4 + (threadIdx.x >> 6);
5807        if (r >= nrow) return;
5808        const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row;
5809        for (int e = e0; e < e1; ++e) {
5810            const float v = row_dot64<TD>(wr, hq + (size_t) e * hb, nb, lane);
5811            if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = v;
5812        }
5813    } else if constexpr (MODE == 4) {
5814        const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
5815        const int r0 = blockIdx.x * 32 + warp;
5816        if (r0 >= nrow) return;
5817        const uint8_t* w[4];
5818#pragma unroll
5819        for (int i = 0; i < 4; ++i) w[i] = blob + L.down_off + (size_t) (r0 + 8 * i < nrow ? r0 + 8 * i : r0) * L.d_row;
5820        for (int e = e0; e < e1; ++e) {
5821            float o[4];
5822            row_dotn<TD, 4>(w, hq + (size_t) e * hb, nb, lane, o);
5823            if (lane == 0)
5824#pragma unroll
5825                for (int i = 0; i < 4; ++i) if (r0 + 8 * i < nrow) out[(size_t) ent_dst[e] * L.n_embd + r0 + 8 * i] = o[i];
5826        }
5827    } else {
5828        const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
5829        const int r0 = blockIdx.x * 16 + warp, r1 = r0 + 8;
5830        if (r0 >= nrow) return;
5831        const bool two = r1 < nrow;
5832        const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;
5833        const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;
5834        for (int e = e0; e < e1; ++e) {
5835            float a, b;
5836            row_dot2<TD>(w0, w1, hq + (size_t) e * hb, nb, lane, a, b);
5837            if (lane == 0) {
5838                out[(size_t) ent_dst[e] * L.n_embd + r0] = a;
5839                if (two) out[(size_t) ent_dst[e] * L.n_embd + r1] = b;
5840            }
5841        }
5842    }
5843}
5844// ---- 5 (LDS): gate/up of the grid formats (IQ2_S, IQ3_XXS, IQ3_S) with the codebook grid and the group's q8_1
5845// activations in LDS.  The bench showed gate/up compute-bound, not bandwidth-bound (T = 2 costs ~1.8x T = 1 on the
5846// same weights, 110-130 GB/s): each call issues its grid lookups and eight activation loads through the vector
5847// memory path after the weight load.  Same calls, same lane-strided k, same R2 row pairs, same warp_sum: the
5848// output is bitwise the mode-2 one.
5849template<int TY> struct GridOf;
5850template<> struct GridOf<22> { using T = uint64_t; static constexpr int N = 1024; __device__ static const T* src() { return iq2s_grid; } };
5851template<> struct GridOf<16> { using T = uint64_t; static constexpr int N = 256; __device__ static const T* src() { return iq2xxs_grid; } };
5852template<> struct GridOf<18> { using T = uint32_t; static constexpr int N = 256; __device__ static const T* src() { return iq3xxs_grid; } };
5853template<> struct GridOf<21> { using T = uint32_t; static constexpr int N = 512; __device__ static const T* src() { return iq3s_grid; } };
5854template<> struct GridOf<23> { using T = uint32_t; static constexpr int N = 1; __device__ static const T* src() { return iq3s_grid; } };   // IQ4_XS: no grid
5855
5856// SG = 1 (mode 6): the signs without byte-SIMD ops, which gfx906 lacks (strata_vcmpne4 / strata_vsub4 unpack to
5857// ~12 word ops each).  m = the sign nibble as 0x00/0xff bytes; (g ^ m) is g or -g-1 per byte, so
5858// dp4a(g ^ m, u) - dp4a(m, u) = sum(s g u) exactly - the same integers, the same floats.
5859__device__ __forceinline__ int nib_mask(uint32_t n) {
5860    const uint32_t b = __umul24(n & 0xFu, 0x204081u) & 0x01010101u;
5861    return (int) ((b << 8) - b);
5862}
5863template<int TY, int SG> struct DotG;
5864template<int SG> struct DotG<22, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
5865                                                      const uint64_t* grid) {
5866    const block_iq2_s* bq2 = (const block_iq2_s*) vbq + kbx;
5867    const int qs_packed = get_int_b2(bq2->qs, iqs / 2);
5868    const uint8_t* qs = (const uint8_t*) &qs_packed;
5869    const int qh = bq2->qh[iqs / 2];
5870    const int signs_packed_32 = get_int_b2(bq2->qs, QK_K / 32 + iqs / 2);
5871    const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
5872    const int ls0 = bq2->scales[iqs / 2] & 0x0F;
5873    const int ls1 = bq2->scales[iqs / 2] >> 4;
5874    int sumi0 = 0, sumi1 = 0;
5875#pragma unroll
5876    for (int l0 = 0; l0 < 8; l0 += 2) {
5877        const int* grid_pos = (const int*) (grid + (qs[l0 / 2] | ((qh << (8 - l0)) & 0x300)));
5878        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
5879        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
5880        int& acc = l0 < 4 ? sumi0 : sumi1;
5881        if constexpr (SG == 1) {
5882            const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);
5883            acc = ggml_cuda_dp4a(grid_pos[0] ^ m0, u0, acc);
5884            acc = ggml_cuda_dp4a(grid_pos[1] ^ m1, u1, acc);
5885            acc -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
5886        } else {
5887            const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
5888            const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
5889            const int grid_l = __vsub4(grid_pos[0] ^ signs0, signs0);
5890            const int grid_h = __vsub4(grid_pos[1] ^ signs1, signs1);
5891            acc = ggml_cuda_dp4a(grid_l, u0, acc);
5892            acc = ggml_cuda_dp4a(grid_h, u1, acc);
5893        }
5894    }
5895    const int sumi = (sumi0 * ls0 + sumi1 * ls1 + (sumi0 + sumi1) / 2) / 4;
5896    const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);
5897    return d * sumi;
5898} };
5899template<int SG> struct DotG<18, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
5900                                                      const uint32_t* grid) {
5901    const block_iq3_xxs* bq3 = (const block_iq3_xxs*) vbq + kbx;
5902    const int2 q3_packed = make_int2(get_int_b2(bq3->qs, iqs), get_int_b2(bq3->qs, iqs + 1));
5903    const uint8_t* q3 = (const uint8_t*) &q3_packed;
5904    const uint32_t aux32 = get_int_b2(bq3->qs, QK_K / 16 + iqs / 2);
5905    int sumi = 0;
5906#pragma unroll
5907    for (int l0 = 0; l0 < 8; l0 += 2) {
5908        const int2 grid_pos = make_int2(grid[q3[l0 + 0]], grid[q3[l0 + 1]]);
5909        const uint32_t signs = unpack_ksigns(aux32 >> (7 * l0 / 2));
5910        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
5911        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
5912        if constexpr (SG == 1) {
5913            const int m0 = nib_mask(signs), m1 = nib_mask(signs >> 4);
5914            sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);
5915            sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);
5916            sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
5917        } else {
5918            const int signs0 = __vcmpne4(signs & 0x08040201, 0);
5919            const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
5920            const int signs1 = __vcmpne4(signs & 0x80402010, 0);
5921            const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
5922            sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
5923            sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
5924        }
5925    }
5926    const int ls = aux32 >> 28;
5927    sumi = (ls * sumi + sumi / 2) / 2;
5928    const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
5929    return d * sumi;
5930} };
5931template<int SG> struct DotG<21, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
5932                                                      const uint32_t* grid) {
5933    const block_iq3_s* bq3 = (const block_iq3_s*) vbq + kbx;
5934    const int2 qs_packed = make_int2(get_int_b2(bq3->qs, iqs + 0), get_int_b2(bq3->qs, iqs + 1));
5935    const uint8_t* qs = (const uint8_t*) &qs_packed;
5936    const int qh = bq3->qh[iqs / 2];
5937    const int signs_packed_32 = get_int_b2(bq3->signs, iqs / 2);
5938    const uint8_t* signs_packed_8 = (const uint8_t*) &signs_packed_32;
5939    int sumi = 0;
5940#pragma unroll
5941    for (int l0 = 0; l0 < 8; l0 += 2) {
5942        const int2 grid_pos = make_int2(grid[qs[l0 + 0] | ((qh << (8 - l0)) & 0x100)],
5943                                        grid[qs[l0 + 1] | ((qh << (7 - l0)) & 0x100)]);
5944        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 0);
5945        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, l0 + 1);
5946        if constexpr (SG == 1) {
5947            const int m0 = nib_mask(signs_packed_8[l0 / 2]), m1 = nib_mask(signs_packed_8[l0 / 2] >> 4);
5948            sumi = ggml_cuda_dp4a(grid_pos.x ^ m0, u0, sumi);
5949            sumi = ggml_cuda_dp4a(grid_pos.y ^ m1, u1, sumi);
5950            sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
5951        } else {
5952            const int signs0 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x03) << 7) | ((signs_packed_8[l0 / 2] & 0x0C) << 21), 0x00000000);
5953            const int signs1 = __vcmpne4(((signs_packed_8[l0 / 2] & 0x30) << 3) | ((signs_packed_8[l0 / 2] & 0xC0) << 17), 0x00000000);
5954            const int grid_l = __vsub4(grid_pos.x ^ signs0, signs0);
5955            const int grid_h = __vsub4(grid_pos.y ^ signs1, signs1);
5956            sumi = ggml_cuda_dp4a(grid_l, u0, sumi);
5957            sumi = ggml_cuda_dp4a(grid_h, u1, sumi);
5958        }
5959    }
5960    sumi *= 1 + 2 * ((bq3->scales[iqs / 4] >> ((iqs << 1) & 0x04)) & 0x0F);
5961    const float d = __half2float(bq3->d) * __low2float(bq8_1[iqs / 2].ds);
5962    return d * sumi;
5963} };
5964
5965// IQ2_XXS: vec_dot_iq2_xxs_q8_1 with the grid in LDS - the same integers, the same floats
5966template<int SG> struct DotG<16, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
5967                                                      const uint64_t* grid) {
5968    const block_iq2_xxs* bq2 = (const block_iq2_xxs*) vbq + kbx;
5969    const int q2 = get_int_b2(bq2->qs, iqs);
5970    const uint8_t* aux8 = (const uint8_t*) &q2;
5971    const uint32_t aux32 = get_int_b2(bq2->qs, iqs + 1);
5972    int sumi = 0;
5973#pragma unroll
5974    for (int k0 = 0; k0 < 8; k0 += 2) {
5975        const uint2 grid_pos = *(const uint2*) (grid + aux8[k0 / 2]);
5976        const int u0 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 0);
5977        const int u1 = get_int_b4(bq8_1[iqs / 2].qs, k0 + 1);
5978        if constexpr (SG == 1) {
5979            const uint32_t v = (aux32 >> (7 * k0 / 2)) & 0x7F, sg = v | ((__popc(v) & 1) << 7);
5980            const int m0 = nib_mask(sg), m1 = nib_mask(sg >> 4);
5981            sumi = ggml_cuda_dp4a((int) grid_pos.x ^ m0, u0, sumi);
5982            sumi = ggml_cuda_dp4a((int) grid_pos.y ^ m1, u1, sumi);
5983            sumi -= ggml_cuda_dp4a(m1, u1, ggml_cuda_dp4a(m0, u0, 0));
5984        } else {
5985            const uint32_t signs = unpack_ksigns(aux32 >> (7 * k0 / 2));
5986            const int signs0 = __vcmpne4(signs & 0x08040201, 0);
5987            const int signs1 = __vcmpne4(signs & 0x80402010, 0);
5988            sumi = ggml_cuda_dp4a((int) __vsub4(grid_pos.x ^ signs0, signs0), u0, sumi);
5989            sumi = ggml_cuda_dp4a((int) __vsub4(grid_pos.y ^ signs1, signs1), u1, sumi);
5990        }
5991    }
5992    const int ls = aux32 >> 27 | 1;
5993    sumi = sumi * ls / 8;
5994    const float d = __half2float(bq2->d) * __low2float(bq8_1[iqs / 2].ds);
5995    return d * sumi;
5996} };
5997
5998template<int SG> struct DotG<23, SG> { __device__ static __forceinline__ float f(const void* vbq, const block_q8_1* bq8_1, int kbx, int iqs,
5999                                                      const uint32_t*) { return vec_dot_iq4_xs_q8_1(vbq, bq8_1, kbx, iqs); } };
6000
6001constexpr int LDS_RB = 64;    // gate/up rows per block (4 R2 passes of 16)
6002constexpr int LDS_NT = 4;     // entries whose activations sit in LDS at once
6003
6004template<int TG, int SG, bool TI = false>
6005__global__ void __launch_bounds__(256) native_gu_lds_kernel(const unsigned long long* __restrict__ grp_ptr,
6006                                                            const int32_t* __restrict__ grp_start,
6007                                                            const int32_t* __restrict__ n_groups,
6008                                                            const int32_t* __restrict__ ent_tok,
6009                                                            const block_q8_1* __restrict__ xq, NativeExpertLayout L,
6010                                                            float* __restrict__ gate, float* __restrict__ up) {
6011    using GT = typename GridOf<TG>::T;
6012    using F = Fmt<TG>;
6013    __shared__ GT sgrid[GridOf<TG>::N];
6014    extern __shared__ int sx_raw[];   // LDS_NT tokens x xb blocks of q8_1 (36 bytes = 9 ints each)
6015    const int g = blockIdx.y;
6016    if (g >= *n_groups) return;       // uniform over the block
6017    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
6018    const GT* gsrc = GridOf<TG>::src();
6019    for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];
6020    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
6021    const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32);
6022    const int e0 = grp_start[g], e1 = grp_start[g + 1];
6023    const int nrow = 2 * (int) L.n_ff;
6024    const block_q8_1* sx = (const block_q8_1*) sx_raw;
6025    auto wrow = [&](int row) -> const uint8_t* {
6026        const bool is_up = row >= L.n_ff;
6027        return blob + (is_up ? L.up_off : 0) + (size_t) (is_up ? row - (int) L.n_ff : row) * L.gu_row;
6028    };
6029    auto put = [&](int row, int e, float v) {
6030        const bool is_up = row >= L.n_ff;
6031        (is_up ? up : gate)[(size_t) e * L.n_ff + (is_up ? row - (int) L.n_ff : row)] = v;
6032    };
6033    for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
6034        const int cn = min(LDS_NT, e1 - c0);
6035        __syncthreads();
6036        for (int j = 0; j < cn; ++j) {
6037            const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);
6038            for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];
6039        }
6040        __syncthreads();
6041        for (int p = 0; p < LDS_RB / 16; ++p) {
6042            const int row0 = blockIdx.x * LDS_RB + p * 16 + warp, row1 = row0 + 8;
6043            if (row0 >= nrow) break;
6044            const bool two = row1 < nrow;
6045            const uint8_t* w0 = wrow(row0);
6046            const uint8_t* w1 = wrow(two ? row1 : row0);
6047            if constexpr (TI) {   // mode 7: the tokens inside the k loop - one weight load per k for all of them
6048                auto pass = [&](auto ntc) {
6049                    constexpr int NTC = decltype(ntc)::value;
6050                    float s0[NTC], s1[NTC];
6051#pragma unroll
6052                    for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
6053                    for (int k = lane; k < nb * F::ipb; k += 32) {
6054                        const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
6055#pragma unroll
6056                        for (int j = 0; j < NTC; ++j) {
6057                            const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);
6058                            const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);
6059                            const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);
6060                            s0[j] += a;
6061                            s1[j] += b;
6062                        }
6063                    }
6064#pragma unroll
6065                    for (int j = 0; j < NTC; ++j) {
6066                        const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
6067                        if (lane == 0) { put(row0, c0 + j, a); if (two) put(row1, c0 + j, b); }
6068                    }
6069                };
6070                switch (cn) {
6071                    case 1: pass(std::integral_constant<int, 1>{}); break;
6072                    case 2: pass(std::integral_constant<int, 2>{}); break;
6073                    case 3: pass(std::integral_constant<int, 3>{}); break;
6074                    default: pass(std::integral_constant<int, 4>{}); break;
6075                }
6076                continue;
6077            }
6078            for (int j = 0; j < cn; ++j) {
6079                const block_q8_1* x = sx + (size_t) j * xb;
6080                float s0 = 0.0f, s1 = 0.0f;
6081                for (int k = lane; k < nb * F::ipb; k += 32) {
6082                    const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
6083                    const block_q8_1* xk = x + kbx * (F::qk / 32);
6084                    const float a = DotG<TG, SG>::f(w0, xk, kbx, iqs, sgrid);
6085                    const float b = DotG<TG, SG>::f(w1, xk, kbx, iqs, sgrid);
6086                    s0 += a;
6087                    s1 += b;
6088                }
6089                s0 = warp_sum(s0);
6090                s1 = warp_sum(s1);
6091                if (lane == 0) { put(row0, c0 + j, s0); if (two) put(row1, c0 + j, s1); }
6092            }
6093        }
6094    }
6095}
6096
6097// ---- 7 (down): the group's q8_1 h rows in LDS, the tokens inside the k loop, the R2 row pairs of mode 2 -
6098// the same per-(row, entry) sums in the same order: bitwise the mode-2 output.
6099template<int TD>
6100__global__ void __launch_bounds__(256) native_down_lds_kernel(const unsigned long long* __restrict__ grp_ptr,
6101                                                              const int32_t* __restrict__ grp_start,
6102                                                              const int32_t* __restrict__ n_groups,
6103                                                              const int32_t* __restrict__ ent_dst,
6104                                                              const block_q8_1* __restrict__ hq, NativeExpertLayout L,
6105                                                              float* __restrict__ out) {
6106    using F = Fmt<TD>;
6107    extern __shared__ int sh_raw[];   // LDS_NT entries x hb blocks of q8_1
6108    const int g = blockIdx.y;
6109    if (g >= *n_groups) return;
6110    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
6111    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
6112    const int nb = (int) (L.n_ff / F::qk), hb = (int) (L.n_ff / 32);
6113    const int e0 = grp_start[g], e1 = grp_start[g + 1];
6114    const int nrow = (int) L.n_embd;
6115    const block_q8_1* sh = (const block_q8_1*) sh_raw;
6116    for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
6117        const int cn = min(LDS_NT, e1 - c0);
6118        __syncthreads();
6119        {
6120            const int* src = (const int*) (hq + (size_t) c0 * hb);   // the chunk's entries are contiguous
6121            for (int i = tid; i < cn * hb * 9; i += 256) sh_raw[i] = src[i];
6122        }
6123        __syncthreads();
6124        for (int p = 0; p < LDS_RB / 16; ++p) {
6125            const int r0 = blockIdx.x * LDS_RB + p * 16 + warp, r1 = r0 + 8;
6126            if (r0 >= nrow) break;
6127            const bool two = r1 < nrow;
6128            const uint8_t* w0 = blob + L.down_off + (size_t) r0 * L.d_row;
6129            const uint8_t* w1 = blob + L.down_off + (size_t) (two ? r1 : r0) * L.d_row;
6130            auto pass = [&](auto ntc) {
6131                constexpr int NTC = decltype(ntc)::value;
6132                float s0[NTC], s1[NTC];
6133#pragma unroll
6134                for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
6135                for (int k = lane; k < nb * F::ipb; k += 32) {
6136                    const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
6137#pragma unroll
6138                    for (int j = 0; j < NTC; ++j) {
6139                        const block_q8_1* xk = sh + (size_t) j * hb + kbx * (F::qk / 32);
6140                        const float a = F::dot(w0, xk, kbx, iqs);
6141                        const float b = F::dot(w1, xk, kbx, iqs);
6142                        s0[j] += a;
6143                        s1[j] += b;
6144                    }
6145                }
6146#pragma unroll
6147                for (int j = 0; j < NTC; ++j) {
6148                    const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
6149                    if (lane == 0) {
6150                        out[(size_t) ent_dst[c0 + j] * L.n_embd + r0] = a;
6151                        if (two) out[(size_t) ent_dst[c0 + j] * L.n_embd + r1] = b;
6152                    }
6153                }
6154            };
6155            switch (cn) {
6156                case 1: pass(std::integral_constant<int, 1>{}); break;
6157                case 2: pass(std::integral_constant<int, 2>{}); break;
6158                case 3: pass(std::integral_constant<int, 3>{}); break;
6159                default: pass(std::integral_constant<int, 4>{}); break;
6160            }
6161        }
6162    }
6163}
6164
6165// ---- 8: mode 7's gate/up with SwiGLU and the q8_1 quantization in the epilogue.  A block takes h rows
6166// [r0, r0 + 32): gate rows r0.. and up rows r0.. (64 weight rows, the same per-(row, entry) sums as mode 7), so
6167// one 32-lane warp per entry holds exactly one q8_1 block of h and runs quantize_q8_1_kernel's own code on it -
6168// bitwise the separate kernels' hq, two launches fewer per call.
6169template<int TG>
6170__global__ void __launch_bounds__(256) native_gu_fused_kernel(const unsigned long long* __restrict__ grp_ptr,
6171                                                              const int32_t* __restrict__ grp_start,
6172                                                              const int32_t* __restrict__ n_groups,
6173                                                              const int32_t* __restrict__ ent_tok,
6174                                                              const block_q8_1* __restrict__ xq, NativeExpertLayout L,
6175                                                              block_q8_1* __restrict__ hq) {
6176    using GT = typename GridOf<TG>::T;
6177    using F = Fmt<TG>;
6178    __shared__ GT sgrid[GridOf<TG>::N];
6179    __shared__ float res[LDS_NT][64];
6180    extern __shared__ int sx_raw[];
6181    const int g = blockIdx.y;
6182    if (g >= *n_groups) return;
6183    const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
6184    const GT* gsrc = GridOf<TG>::src();
6185    for (int i = tid; i < GridOf<TG>::N; i += 256) sgrid[i] = gsrc[i];
6186    const uint8_t* blob = (const uint8_t*) grp_ptr[g];
6187    const int nb = (int) (L.n_embd / F::qk), xb = (int) (L.n_embd / 32), hb = (int) (L.n_ff / 32);
6188    const int e0 = grp_start[g], e1 = grp_start[g + 1];
6189    const int r0 = blockIdx.x * 32;
6190    const block_q8_1* sx = (const block_q8_1*) sx_raw;
6191    auto wrow = [&](int i) -> const uint8_t* {   // i < 32: gate row r0 + i, else up row r0 + i - 32
6192        return blob + (i < 32 ? (size_t) 0 : L.up_off) + (size_t) (r0 + (i & 31)) * L.gu_row;
6193    };
6194    for (int c0 = e0; c0 < e1; c0 += LDS_NT) {
6195        const int cn = min(LDS_NT, e1 - c0);
6196        __syncthreads();
6197        for (int j = 0; j < cn; ++j) {
6198            const int* src = (const int*) (xq + (size_t) ent_tok[c0 + j] * xb);
6199            for (int i = tid; i < xb * 9; i += 256) sx_raw[j * xb * 9 + i] = src[i];
6200        }
6201        __syncthreads();
6202        for (int p = 0; p < 4; ++p) {
6203            const int i0 = p * 16 + warp, i1 = i0 + 8;
6204            const uint8_t* w0 = wrow(i0);
6205            const uint8_t* w1 = wrow(i1);
6206            auto pass = [&](auto ntc) {
6207                constexpr int NTC = decltype(ntc)::value;
6208                float s0[NTC], s1[NTC];
6209#pragma unroll
6210                for (int j = 0; j < NTC; ++j) { s0[j] = 0.0f; s1[j] = 0.0f; }
6211                for (int k = lane; k < nb * F::ipb; k += 32) {
6212                    const int kbx = k / F::ipb, iqs = F::step * (k % F::ipb);
6213#pragma unroll
6214                    for (int j = 0; j < NTC; ++j) {
6215                        const block_q8_1* xk = sx + (size_t) j * xb + kbx * (F::qk / 32);
6216                        const float a = DotG<TG, 1>::f(w0, xk, kbx, iqs, sgrid);
6217                        const float b = DotG<TG, 1>::f(w1, xk, kbx, iqs, sgrid);
6218                        s0[j] += a;
6219                        s1[j] += b;
6220                    }
6221                }
6222#pragma unroll
6223                for (int j = 0; j < NTC; ++j) {
6224                    const float a = warp_sum(s0[j]), b = warp_sum(s1[j]);
6225                    if (lane == 0) { res[j][i0] = a; res[j][i1] = b; }
6226                }
6227            };
6228            switch (cn) {
6229                case 1: pass(std::integral_constant<int, 1>{}); break;
6230                case 2: pass(std::integral_constant<int, 2>{}); break;
6231                case 3: pass(std::integral_constant<int, 3>{}); break;
6232                default: pass(std::integral_constant<int, 4>{}); break;
6233            }
6234        }
6235        __syncthreads();
6236        if (warp < cn) {   // swiglu_entries_kernel + quantize_q8_1_kernel, one block of 32 h values per entry
6237            const float gg = res[warp][lane], uu = res[warp][32 + lane];
6238            const float xi = (gg / (1.0f + __expf(-gg))) * uu;
6239            float amax = fabsf(xi), sum = xi;
6240#pragma unroll
6241            for (int o = 16; o > 0; o >>= 1) {
6242                amax = fmaxf(amax, __shfl_xor_sync(0xffffffffu, amax, o));
6243                sum += __shfl_xor_sync(0xffffffffu, sum, o);
6244            }
6245            const float d = q8_1_finite(amax / 127.0f);   // #606, as q8_1_store: finite blocks bit for bit
6246            const int8_t q = q8_1_quant(xi, d, amax);
6247            block_q8_1* y = hq + (size_t) (c0 + warp) * hb + blockIdx.x;
6248            y->qs[lane] = q;
6249            if (lane == 0) y->ds = q8_1_ds(d, sum);
6250        }
6251    }
6252}
6253
6254// dflash2-kern: Strix Halo (gfx1151) takes mode 8 (gate/up + SwiGLU + q8_1 in one launch, the group's activations in LDS) for the
6255// IQ packs' gate/up: native_expert_bench on the IQ3_S pack's real rows, 45 groups of one entry (a 8-token verify window's call),
6256// gate/up -25% (IQ2_S), -8% (IQ3_XXS), -6% (IQ3_S), bitwise equal to mode 0.  STRATA_GFX1151_EXP8=0 keeps the old layout.
6257bool gfx1151_exp8(int dev) {
6258#if defined(__HIPCC__) && !defined(STRATA_HIP_GFX906)
6259    static int per_dev[64];   // 0 unknown, 1 no, 2 yes
6260    if (dev < 0 || dev >= 64) return false;
6261    if (!per_dev[dev]) {
6262        const char* v = std::getenv("STRATA_GFX1151_EXP8");
6263        cudaDeviceProp p;
6264        per_dev[dev] = !(v != nullptr && v[0] == '0') && cudaGetDeviceProperties(&p, dev) == cudaSuccess &&
6265                               strata::kernels::gfx_arch_is_gfx1151(p.gcnArchName) ? 2 : 1;
6266        (void) cudaGetLastError();
6267    }
6268    return per_dev[dev] == 2;
6269#else
6270    (void) dev;
6271    return false;
6272#endif
6273}
6274int g_exp_mode = -1;   // native_expert_set_mode (the bench); -1 = STRATA_EXP_MODE, else the card's default
6275int exp_mode() {
6276    static const int m = [] { const char* v = std::getenv("STRATA_EXP_MODE"); return v ? std::atoi(v) : -1; }();
6277    if (g_exp_mode >= 0) return g_exp_mode;
6278    if (m >= 0) return m;
6279#if defined(STRATA_HIP_GFX906)
6280    return kExpModeDefault;
6281#else
6282    // Mode 8 keeps the grid and the group's activations in shared memory with SwiGLU + q8_1 fused.  Volta can opt in;
6283    // GB10 takes it with the sm_121 defaults (IQ3_S, fixed 512-token MTP workload, 8 balanced pairs: decode +11.7%
6284    // paired median, 6/8 wins, identical output).  Every other CUDA card keeps the CUDA layout.
6285    static int per_dev[64];   // 0 unknown, else mode + 1
6286    int dev = 0;
6287    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return kExpModeDefault;
6288    if (!per_dev[dev] && gfx1151_exp8(dev)) per_dev[dev] = 1 + 8;
6289    if (!per_dev[dev]) {
6290        int major = 0, minor = 0;
6291        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
6292        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
6293        const char* sm70 = std::getenv("STRATA_SM70_TABLE");   // PR 1401: Volta's mode 8 is opt-in until confirmed on a V100
6294        // Pascal GP100 (sm_60): mode 8 too, on by default (Tesla P100: bitwise equal on the model's layers, the down
6295        // projection 116 -> 94 us and IQ3_S gate/up 360 -> 229 us in a 28-group VRAM call); STRATA_SM60_TABLE=0 keeps the CUDA layout
6296        const char* sm60 = std::getenv("STRATA_SM60_TABLE");
6297        const bool p100 = major == 6 && minor == 0 && (sm60 == nullptr || std::atoi(sm60) != 0);
6298        // Pascal with dp4a (sm_61): mode 8 as well, on by default (Tesla P40, native_expert_bench on the IQ3_S pack's
6299        // layers, an 18-group call at 2 tokens: IQ3_S 390 -> 255 us, IQ3_XXS 345 -> 252 us, IQ2_S 290 -> 238 us,
6300        // IQ4_XS 328 -> 261 us, bitwise equal); STRATA_SM61_TABLE=0 keeps the CUDA layout
6301        const char* sm61 = std::getenv("STRATA_SM61_TABLE");
6302        const bool p40 = major == 6 && minor == 1 && (sm61 == nullptr || std::atoi(sm61) != 0);
6303        const char* sm121 = std::getenv("STRATA_SM121_PERF");
6304        const bool gb10 = major == 12 && minor == 1 && !strata::qwen_defaults_026() &&
6305                          (sm121 == nullptr || std::atoi(sm121) != 0);
6306        // Turing (sm_75): mode 4 (native_expert_bench, real Q2_0 rows of Flash-Next, bitwise equal to mode 0 on an RTX
6307        // 2080 Ti: 10 experts x 1 entry 47.3 -> 41.4 us, 30 x 1 120.2 -> 100.2 us); the down projection keeps the CUDA
6308        // layout in windows of 4+ tokens (sm75_down_em below).  STRATA_SM75_EXP=0 keeps the CUDA layout.
6309        // (off unless STRATA_SM75_PERF=1; STRATA_SM75_EXP=0 / 1 forces it off / on)
6310        const bool turing = strata::sm75_switch("STRATA_SM75_EXP", major, minor);
6311        per_dev[dev] = 1 + ((major == 7 && minor == 0 && sm70 != nullptr && std::atoi(sm70) != 0) || p100 || p40 || gb10 ? 8 : turing ? 4 : kExpModeDefault);
6312    }
6313    return per_dev[dev] - 1;
6314#endif
6315}
6316#endif
6317int g_exp_phase = 0;   // the bench: 0 all, 1 gate/up + swiglu + quantize only, 2 down only, 3 gate/up only
6318#if STRATA_EXP_LAYOUTS && !defined(__HIPCC__)
6319// The down projection's mode on Turing's default: mode 4 is slower than the CUDA layout once groups have 3+ entries
6320// (12 x 3: 36.5 -> 40.8 us, 16 x 4: 56.9 -> 68.9) - windows of 4+ tokens (cap_groups > 30) keep mode 0 there.
6321int sm75_down_em(int em0, int64_t cap_groups) {
6322    if (em0 != 4 || g_exp_mode >= 0 || std::getenv("STRATA_EXP_MODE") != nullptr || cap_groups <= 30) return em0;
6323    int dev = 0, major = 0, minor = 0;
6324    if (cudaGetDevice(&dev) != cudaSuccess) return em0;
6325    cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
6326    cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
6327    return strata::is_sm75(major, minor) ? 0 : em0;
6328}
6329#else
6330int sm75_down_em(int em0, int64_t) { return em0; }
6331#endif
6332
6333void native_expert_set_mode(int mode, int phase) {
6334#if STRATA_EXP_LAYOUTS
6335    g_exp_mode = mode;
6336#else
6337    (void) mode;
6338#endif
6339    g_exp_phase = phase;
6340}
6341
6342namespace {
6343bool g_grouped_v1 = env_on("STRATA_GROUPED_V1");
6344#include "i8_expert.cuh"   // OWN-I8: our own int8 dot-product kernels (native_expert_i8 below)
6345// OWN-I8: STRATA_EXPERT_I8, read once: 1 = on, 0 = off, -1 = not set (then the card class decides: i8_expert_rule.hpp)
6346std::atomic<bool> g_i8_mmq_free{false};   // set before main by a build without MMQ (native_expert_i8_set_mmq_free)
6347int i8_switch_raw() {
6348    static const int s = strata::kernels::i8_switch_parse(std::getenv("STRATA_EXPERT_I8"));
6349    return s;
6350}
6351int i8_switch_state() { return strata::kernels::i8_switch_effective(i8_switch_raw(), g_i8_mmq_free.load(std::memory_order_relaxed)); }
6352// the current device's gcnArchName, read once per device (a HIP card; "" on a CUDA card)
6353const char* i8_device_gcn() {
6354#if defined(__HIPCC__)
6355    static std::mutex mu;
6356    static char names[16][64];
6357    static bool done[16];
6358    int dev = 0;
6359    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return "";
6360    std::lock_guard<std::mutex> lk(mu);
6361    if (!done[dev]) {
6362        cudaDeviceProp p{};
6363        if (cudaGetDeviceProperties(&p, dev) == cudaSuccess) std::snprintf(names[dev], sizeof(names[dev]), "%s", p.gcnArchName);
6364        done[dev] = true;
6365    }
6366    return names[dev];
6367#else
6368    return "";
6369#endif
6370}
6371}  // namespace
6372
6373void native_grouped_set_v1(bool v1) { g_grouped_v1 = v1; }
6374
6375size_t native_expert_i8_smem_limit() noexcept { return i8_smem_limit(); }
6376
6377NativeExpertI8Launch native_expert_i8_last_launch() noexcept {
6378    return {g_i8_last.tile, g_i8_last.gu_bytes, g_i8_last.down_bytes, g_i8_last.gu_err, g_i8_last.down_err};
6379}
6380
6381int native_expert_i8_probe_launch(size_t bytes) noexcept {
6382#if !defined(__HIPCC__)
6383    return i8_smem_launches(bytes) ? 1 : 0;
6384#else
6385    (void) bytes;
6386    return -1;
6387#endif
6388}
6389
6390bool native_expert_i8_prompt(const NativeExpertLayout& L, int64_t group_entries) noexcept {
6391    const int st = i8_switch_state();
6392    if (st == 0 || group_entries < kI8MinGroupEntries) return false;   // before any device query
6393    return i8_expert_takes(st, i8_device_gcn(), group_entries, native_expert_i8_supported(L));
6394}
6395
6396bool native_expert_i8_by_default() noexcept { return i8_expert_class_default(i8_switch_raw(), i8_device_gcn(), g_i8_mmq_free.load(std::memory_order_relaxed)); }
6397void native_expert_i8_set_mmq_free() noexcept { g_i8_mmq_free.store(true, std::memory_order_relaxed); }
6398// The P100 class rule (i8_expert_rule.hpp, i8_chunk_default_allows; declared in prefill.cpp, the one caller): is the int8 DEFAULT of this process the one that gives way to the FP16
6399// path from the stream floor up?  True only on a Tesla P100 (compute capability 6.0) in a build without MMQ with STRATA_EXPERT_I8 not set; a set value, a build with MMQ, any other
6400// card and a HIP card: false (no size limit).
6401bool native_expert_i8_floor_gated() noexcept {
6402    if (i8_switch_raw() != -1 || !g_i8_mmq_free.load(std::memory_order_relaxed)) return false;   // before any device query
6403#if !defined(__HIPCC__)
6404    int dev = 0, major = 0, minor = 0;
6405    if (cudaGetDevice(&dev) != cudaSuccess) return false;
6406    cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
6407    cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
6408    return major == 6 && minor == 0;
6409#else
6410    return false;
6411#endif
6412}
6413
6414// OWN-I8 few-rows route: STRATA_I8_FEWROWS read once (not set = the card's class default, 0 = off, N = a limit of N rows per expert); the class default asks the
6415// current device's compute capability (a HIP card has none that matters: the CUDA rule's 10)
6416int native_expert_i8_few_rows_limit() noexcept {
6417    static const char* const text = std::getenv("STRATA_I8_FEWROWS");
6418    if (i8_switch_state() == 0) return 0;
6419    int major = 0, minor = 0;
6420#if !defined(__HIPCC__)
6421    int dev = 0;
6422    if (cudaGetDevice(&dev) == cudaSuccess) {
6423        cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev);
6424        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
6425    }
6426#endif
6427    return i8_fewrows_limit(text, i8_fewrows_class_default(major, minor));
6428}
6429
6430size_t native_expert_i8_scratch_bytes(int64_t cap_entries, int64_t cap_groups, int64_t n_ff) {
6431    const size_t hqb = ((size_t) cap_entries * (size_t) (n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255;   // as native_expert_i8 carves it
6432    return hqb + (size_t) (cap_groups + 1) * sizeof(int32_t);
6433}
6434
6435bool native_expert_i8_supported(const NativeExpertLayout& L) noexcept {
6436    return i8_gu_type(L.gu_type) && i8_d_type(L.d_type) && !L.gu_nib && L.tail_off == 0 && L.had_block == 0 && L.n_embd % 256 == 0 &&
6437           L.n_ff % 128 == 0 && ((L.d_type != 13 && L.d_type != 14) || L.n_ff % 256 == 0) && L.n_embd % 64 == 0 && L.bytes < ((size_t) 1 << 32) &&   // 32-bit byte offsets inside one expert's blob
6438           i8_smem_bytes(L.gu_type, L.d_type, 2) <= i8_smem_limit();                  // the smallest tile fits the device's shared memory per block
6439}
6440
6441void native_expert_i8_quantize(const float* x, int64_t n_rows, int64_t n_cols, void* y, void* stream) {
6442    const long long n = (long long) n_rows * n_cols;
6443    if (n <= 0) return;
6444    if (n_cols % 32 != 0) { std::fprintf(stderr, "native_expert_i8_quantize: %lld columns\n", (long long) n_cols); std::exit(1); }
6445    i8_quantize_kernel<<<(unsigned) ((n + 255) / 256), 256, 0, (cudaStream_t) stream>>>(x, (block_q8_1*) y, n);
6446    check("native_expert_i8_quantize");
6447}
6448
6449void native_expert_i8(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start, const int32_t* n_groups,
6450                      const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups, int64_t cap_entries, const void* x_q8_1,
6451                      void* scratch, float* out, void* stream) {
6452    if (cap_groups <= 0 || cap_entries <= 0) return;
6453    if (!native_expert_i8_supported(L)) {
6454        std::fprintf(stderr, "native_expert_i8: gate/up type %d, down type %d at %lld x %lld is not covered\n", L.gu_type, L.d_type,
6455                     (long long) L.n_embd, (long long) L.n_ff);
6456        std::exit(1);
6457    }
6458    if ((size_t) cap_entries * (size_t) (std::max(L.n_embd, L.n_ff) / 32 * 36) >= ((size_t) 1 << 32)) {   // 32-bit byte offsets of the activation rows
6459        std::fprintf(stderr, "native_expert_i8: %lld entries at %lld x %lld exceed 4 GiB of activation rows\n", (long long) cap_entries,
6460                     (long long) L.n_embd, (long long) L.n_ff);
6461        std::exit(1);
6462    }
6463    cudaStream_t s = (cudaStream_t) stream;
6464    // scratch: the H blocks (q8_1, one per 32 features and entry), then the tile table (cap_groups + 1 ints)
6465    block_q8_1* hq = (block_q8_1*) scratch;
6466    const size_t hqb = ((size_t) cap_entries * (size_t) (L.n_ff / 32) * sizeof(block_q8_1) + 255) & ~(size_t) 255;
6467    int32_t* tile_off = (int32_t*) ((uint8_t*) scratch + hqb);
6468    int tm = i8_env_int("STRATA_I8_TM", 0);   // research: the tile code (2, 3 or 4 rows of 16 entries per thread -> 32, 48 or 64 entries; 8 = variant B, 128 entries)
6469    const int64_t avg = cap_entries / cap_groups;
6470    const bool b_ok = L.n_embd % 128 == 0 && L.n_ff % 64 == 0;
6471    if (tm <= 0) tm = (avg >= 96 && b_ok) ? 8 : (int) std::max<int64_t>(2, std::min<int64_t>(4, (avg + 8) / 16));
6472    tm = tm <= 2 ? 2 : tm == 3 ? 3 : tm >= 8 && b_ok && i8_tile8_type(L.gu_type) && i8_tile8_type(L.d_type) ? 8 : 4;   // (the K-quants and Q5_1 have no tile 8)
6473    const size_t smem_limit = i8_smem_limit();   // a tile that does not fit the device's shared memory per block falls to the next smaller one
6474    while (tm > 2 && i8_smem_bytes(L.gu_type, L.d_type, tm) > smem_limit) tm = tm == 8 ? 4 : tm - 1;
6475    const int bm = tm == 8 ? 128 : 16 * tm;
6476    i8_tiles_kernel<<<1, 256, 0, s>>>(grp_start, n_groups, bm, tile_off);
6477    I8Args a{grp_ptr, grp_start, n_groups, tile_off, ent_tok, ent_dst, (const block_q8_1*) x_q8_1, hq, out, L,
6478             cap_entries / bm + cap_groups, i8_env_int("STRATA_I8_BISECT", 0), i8_n8_takes(i8_switch_parse(std::getenv("STRATA_I8_N8")), tm)};   // 8-entry slices: tile 2 by default, 2-4 with STRATA_I8_N8=1, none with 0
6479    switch (L.gu_type) {
6480        case 16: i8_launch<16, true>(tm, a, s); break;
6481        case 17: i8_launch<17, true>(tm, a, s); break;
6482        case 18: i8_launch<18, true>(tm, a, s); break;
6483        case 21: i8_launch<21, true>(tm, a, s); break;
6484        case 23: i8_launch<23, true>(tm, a, s); break;
6485        case 29: i8_launch<29, true>(tm, a, s); break;
6486        case 42: i8_launch<42, true>(tm, a, s); break;
6487        case 12: i8_launch<12, true>(tm, a, s); break;
6488        case 13: i8_launch<13, true>(tm, a, s); break;
6489        case 14: i8_launch<14, true>(tm, a, s); break;
6490        case 8: i8_launch<8, true>(tm, a, s); break;
6491        default: i8_launch<22, true>(tm, a, s); break;
6492    }
6493    check("native_expert_i8/gu");
6494    if (L.d_type == 20) i8_launch<20, false>(tm, a, s);
6495    else if (L.d_type == 6) i8_launch<6, false>(tm, a, s);
6496    else if (L.d_type == 8) i8_launch<8, false>(tm, a, s);
6497    else if (L.d_type == 7) i8_launch<7, false>(tm, a, s);
6498    else if (L.d_type == 13) i8_launch<13, false>(tm, a, s);
6499    else if (L.d_type == 14) i8_launch<14, false>(tm, a, s);
6500    else i8_launch<42, false>(tm, a, s);
6501    check("native_expert_i8/down");
6502}
6503
6504void native_expert_set_expdec(int on) { g_expdec = on < 0 ? -1 : (on ? 1 : 0); }
6505int native_expert_expdec() { return expdec_mode(); }
6506void native_expert_set_expdec_params(const NativeExpertExpdecParams& p) {
6507    if (p.gu_rows_per_lane > 0) g_expdec_r = p.gu_rows_per_lane;
6508    if (p.down_rows_per_lane > 0) g_expdec_dr = p.down_rows_per_lane;
6509    if (p.gu_min_blocks_per_sm > 0) g_expdec_minb = p.gu_min_blocks_per_sm;
6510    if (p.down_iq4_nl >= 0) g_expdec_d20 = p.down_iq4_nl;
6511    if (p.down >= 0) g_expdec_down = p.down;
6512    if (p.gu_rows_per_block >= 0) g_expdec_rb = p.gu_rows_per_block;
6513    if (p.down_rows_per_block >= 0) g_expdec_drb = p.down_rows_per_block;
6514    if (p.min_blocks > 0) g_expdec_minblk = p.min_blocks;
6515}
6516NativeExpertExpdecParams native_expert_expdec_params() {
6517    NativeExpertExpdecParams p;
6518    p.gu_rows_per_lane = expdec_r();
6519    p.down_rows_per_lane = expdec_dr();
6520    p.gu_min_blocks_per_sm = g_expdec_minb >= 4 ? 4 : 2;
6521    p.down_iq4_nl = g_expdec_d20 ? 1 : 0;
6522    p.down = expdec_down_on() ? 1 : 0;
6523    p.gu_rows_per_block = g_expdec_rb;
6524    p.down_rows_per_block = g_expdec_drb;
6525    p.min_blocks = g_expdec_minblk;
6526    return p;
6527}
6528bool native_expert_expdec_takes(const NativeExpertLayout& L, bool& gu, bool& down) {
6529    gu = expdec_gu_ok(L);
6530    down = expdec_down_ok(L);
6531    return gu || down;
6532}
6533
6534void native_expert_grouped(const NativeExpertLayout& L, const unsigned long long* grp_ptr, const int32_t* grp_start,
6535                           const int32_t* n_groups, const int32_t* ent_dst, const int32_t* ent_tok, int64_t cap_groups,
6536                           int64_t cap_entries, const void* x_q8_1, void* scratch, float* out, void* stream,
6537                           int64_t grid_groups) {
6538    if (cap_groups <= 0 || cap_entries <= 0) return;
6539    strata::dispatch::kernel(strata::dispatch::kExpert, 0, L.gu_type, (int) L.n_embd, (int) L.n_ff, L.d_type);   // BW-MEASURE: one grouped expert call
6540    if (L.n_ff % 32 != 0) { std::fprintf(stderr, "native_expert_grouped: n_ff %lld\n", (long long) L.n_ff); std::exit(1); }
6541    // (OWN-I8: this fallback no longer hands its calls to native_expert_i8: that kernel reads its own activation image, native_expert_i8_quantize's, and this call's rows are q8_1
6542    //  blocks.  The prompt path's MMQ groups, where the kernel was measured, quantize the image themselves.)
6543    cudaStream_t s = (cudaStream_t) stream;
6544    const size_t f = (size_t) cap_entries * (size_t) L.n_ff * sizeof(float), fa = (f + 255) & ~(size_t) 255;
6545    float* gate = (float*) scratch;
6546    float* up = (float*) ((uint8_t*) scratch + fa);
6547    float* h = (float*) ((uint8_t*) scratch + 2 * fa);
6548    block_q8_1* hq = (block_q8_1*) ((uint8_t*) scratch + 3 * fa);
6549    const auto* X = (const block_q8_1*) x_q8_1;
6550#if !STRATA_EXPERT_NIBBLE_BUILT
6551    if (L.gu_nib) {   // STRATA_EXPERT_NIBBLE's slots: the switch is refused at start in a build without the kernels
6552        std::fprintf(stderr, "native_expert_grouped: 4-bit gate/up slots are not built into this engine\n");
6553        std::exit(1);
6554    }
6555#endif
6556    // STRATA_EXPERT_NIBBLE (nib_layout): only the gate/up step below takes another kernel (launch_gu_nib, in place of
6557    // launch_gu); SwiGLU, the q8_1 quantization and the down rows (GGUF, at L.down_off) are the layout's own
6558    static const bool v2 = [] { const char* v = std::getenv("STRATA_EXPERT_V2"); return v && v[0] == '1'; }();
6559    if (v2 && !nib_layout(L) && L.gu_type == 21 && L.d_type == 20 && L.n_embd == 2560 && L.n_ff == 640) {   // S26: see s26_gu_l_kernel
6560        // S26 STRATA_TSUM=1: the sums as one transposed butterfly per warp (s26_tsum.cuh; bitwise the same values)
6561        static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();
6562        // (+ down rows' items spread evenly over the lanes, one load group: bitwise, harness 1.09-1.12x vs 1.03-1.06x;
6563        // the same for gate / up was 0.6-0.8x)
6564        if (ts) s26_launch_l<true, true, 4, 4, true, true, true, 1>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h,
6565                                                             hq, out, (long long) cap_entries * L.n_ff);
6566        else s26_launch_l<true, true, 4, 4, true, true>(L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h,
6567                                                        hq, out, (long long) cap_entries * L.n_ff);
6568        check("native_expert_grouped (v2)");
6569        return;
6570    }
6571    // stream B: UD-Q4_K_XL's Q4_K / Q5_K gate/up and Q5_1 / Q8_0 down (see S27 above)
6572    // MODEL-UPDATE: on by default on gfx12 (every output the old kernels' bits; R9700, UD-Q4_K_XL decode, 5 interleaved
6573    // pairs: story +1.2% 5/5, code +0.8% 5/5, after 6K +0.2% 4/5) and, since round 0215, on Windows gfx1151 (below);
6574    // STRATA_EXPERT_V2K=0 turns it off, =1 turns it on elsewhere (not measured on other cards)
6575    static const bool v2k = [] {
6576        const char* v = std::getenv("STRATA_EXPERT_V2K");
6577        if (v != nullptr && v[0] != '\0') return v[0] == '1';
6578#if defined(__HIPCC__) && !defined(STRATA_HIP_GFX906)
6579        int dev = 0;
6580        cudaDeviceProp p;
6581        const bool ok = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess;
6582        const bool g12 = ok && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName);
6583#if defined(_WIN32)
6584        // round 0215 (Strix Halo, Windows gfx1151, UD-Q4_K_XL, DFlash2 serve, 16 request pairs): window time -4.0 % (16 of 16 pairs faster,
6585        // mean x1.040, range x1.020-1.056, the same window and token count in every pair); STRATA_EXPERT_V2K=0 turns it off
6586        const bool strix = ok && strata::kernels::gfx_arch_is_gfx1151(p.gcnArchName);
6587#else
6588        const bool strix = false;
6589#endif
6590        (void) cudaGetLastError();
6591        return g12 || strix;
6592#else
6593        return false;
6594#endif
6595    }();
6596    // Qwen3.6-35B-A3B (n_embd 2048, n_ff 512, Q4_K / Q5_K gate+up, Q5_K down): the same kernels, the geometry only sizes the grid
6597    const bool q36geo = L.n_embd == 2048 && L.n_ff == 512 && L.d_type == 13;
6598    if (v2k && (L.gu_type == 12 || L.gu_type == 13) &&
6599        (((L.d_type == 7 || L.d_type == 8) && L.n_embd == 2560 && L.n_ff == 640) || q36geo)) {
6600        static const bool ts = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();
6601        const long long nh = (long long) cap_entries * L.n_ff;
6602#define STRATA_V2K(G, D) s27_launch_ts<G, D>(ts, L, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, ent_tok, X, gate, up, h, hq, out, nh)
6603        if (q36geo) {
6604            // the gate/up of the V2K path (4 rows per warp, the chunk's activations in LDS) + SwiGLU/q8_1, and the old down kernel:
6605            // for n_ff 512 the new down kernel measured slower (15.1 vs 13.4 us per layer on gfx1201, R9700)
6606            const dim3 ggu((unsigned) (2 * L.n_ff / (GU_ROWS * 4)), (unsigned) cap_groups);
6607            if (L.gu_type == 12) s27_gu_kernel<12, true, 4, false><<<ggu, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
6608            else s27_gu_kernel<13, true, 4, false><<<ggu, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up);
6609            s26_swiglu_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, hq, nh);
6610            const dim3 gd((unsigned) ((L.n_embd + 7) / 8), (unsigned) cap_groups);
6611            launch_down<13>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
6612        }
6613        else if (L.gu_type == 12 && L.d_type == 7) STRATA_V2K(12, 7);
6614        else if (L.gu_type == 12) STRATA_V2K(12, 8);
6615        else if (L.d_type == 7) STRATA_V2K(13, 7);
6616        else STRATA_V2K(13, 8);
6617#undef STRATA_V2K
6618        check("native_expert_grouped (v2k)");
6619        return;
6620    }
6621    const bool v1 = g_grouped_v1;
6622    const int64_t gy = (v1 || grid_groups <= 0 || grid_groups > cap_groups) ? cap_groups : grid_groups;
6623    const int gu_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_embd == 2560 && gu_split(L.gu_type) &&
6624                         gu_qk(L.gu_type) != 128 && L.gu_type != 12 && L.gu_type != 13) ? 16 : GU_ROWS;   // qk 128 (APR trellis): no sub-16 rows, see launch_gu
6625    const dim3 ggu((unsigned) ((2 * L.n_ff + gu_rows - 1) / gu_rows), (unsigned) gy);
6626#if STRATA_EXP_LAYOUTS
6627#if defined(STRATA_HIP_GFX906)
6628    const int em0 = exp_mode();
6629#else
6630    // CUDA: the AMD layouts launch a block row per possible group, so a call that strides (a verify window's PCIe
6631    // call, grid_groups 1..cap) keeps the CUDA layout: V100, 0 groups 11.3 vs 6.5 us, 1 group of 2 29.6 vs 21.3
6632    const int em0 = (grid_groups > 0 && grid_groups < cap_groups) ? 0 : exp_mode();
6633#endif
6634#endif
6635#if STRATA_EXP_LAYOUTS
6636    const bool fused_gu = !nib_layout(L) && em0 == 8 && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23) &&
6637                          L.n_ff % 32 == 0;
6638    if (fused_gu && g_exp_phase != 2) {
6639        const dim3 gl((unsigned) (L.n_ff / 32), (unsigned) cap_groups);
6640        const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);
6641        switch (L.gu_type) {
6642            case 16: native_gu_fused_kernel<16><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
6643            case 18: native_gu_fused_kernel<18><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
6644            case 21: native_gu_fused_kernel<21><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
6645            case 23: native_gu_fused_kernel<23><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
6646            default: native_gu_fused_kernel<22><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, hq); break;
6647        }
6648        check("native_expert_grouped/gu fused");
6649    }
6650#endif
6651    // 147-verify STRATA_GU_SWIGLU=1: gate/up + SwiGLU + q8_1 in one launch where the CUDA layout's 16-lane kernel would run
6652    bool gs_done = false;
6653#if STRATA_EXP_LAYOUTS
6654    const bool gs_layout = !fused_gu && em0 == 0;
6655#else
6656    const bool gs_layout = true;
6657#endif
6658    if (gs_layout && !nib_layout(L) && g_exp_phase == 0 && !v1 && gu_swiglu_on() && !(expdec_mode() && !g_old_kernels && expdec_gu_ok(L))) {
6659        switch (L.gu_type) {
6660#define STRATA_GS(T) case T: gs_done = launch_gu_swiglu<T>(L, gy, s, grp_ptr, grp_start, n_groups, ent_tok, X, hq); break;
6661            STRATA_GU_FMTS(STRATA_GS)
6662#undef STRATA_GS
6663            default: break;
6664        }
6665        if (gs_done) check("native_expert_grouped/gu+swiglu");
6666    }
6667    {   // BW-MEASURE: which gate/up form ran: 1 = fused gate/up/SwiGLU/q8_1 (em 8), 2 = GU_SWIGLU one launch, 3 = separate gate/up + SwiGLU launches
6668#if STRATA_EXP_LAYOUTS
6669        const int gu_form = fused_gu ? 1 : (gs_done ? 2 : 3);
6670#else
6671        const int gu_form = gs_done ? 2 : 3;
6672#endif
6673        strata::dispatch::kernel(strata::dispatch::kExpert, gu_form, L.gu_type, (int) L.n_embd, (int) L.n_ff, L.d_type);
6674    }
6675#if STRATA_EXP_LAYOUTS
6676    if (g_exp_phase != 2 && !fused_gu && !gs_done) {
6677#else
6678    if (g_exp_phase != 2 && !gs_done) {
6679#endif
6680#if STRATA_EXP_LAYOUTS
6681    const bool lds_gu = !nib_layout(L) && (em0 == 5 || em0 == 6 || em0 == 7 || em0 == 8) && ((kExpLds16 && L.gu_type == 16) || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 || L.gu_type == 23);
6682    if (lds_gu) {
6683        const dim3 gl((unsigned) ((2 * L.n_ff + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);
6684        const size_t sh = (size_t) LDS_NT * (size_t) (L.n_embd / 32) * sizeof(block_q8_1);
6685        switch (L.gu_type) {
6686            case 16: if (em0 >= 7) native_gu_lds_kernel<16, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<16, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<16, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
6687            case 18: if (em0 >= 7) native_gu_lds_kernel<18, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<18, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<18, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
6688            case 21: if (em0 >= 7) native_gu_lds_kernel<21, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<21, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<21, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
6689            case 23: if (em0 >= 7) native_gu_lds_kernel<23, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<23, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
6690            default: if (em0 >= 7) native_gu_lds_kernel<22, 1, true><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else if (em0 == 6) native_gu_lds_kernel<22, 1><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); else native_gu_lds_kernel<22, 0><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
6691        }
6692    } else {
6693    const int em = em0 >= 5 ? kExpFallback : em0;
6694    const dim3 ggu_amd((unsigned) ((2 * L.n_ff + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);
6695#define STRATA_GU_AMD(T) \
6696    case T: if (em == 1) native_gu_amd_kernel<T, 1><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \
6697            else if (em == 4) native_gu_amd_kernel<T, 4><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); \
6698            else native_gu_amd_kernel<T, 2><<<ggu_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
6699    // the AMD layouts cover the IQ packs' gate/up types; Unsloth's Q4_K / Q5_K take the CUDA layout below
6700    const bool amd_gu = L.gu_type == 16 || L.gu_type == 17 || L.gu_type == 18 || L.gu_type == 21 || L.gu_type == 22 ||
6701                        L.gu_type == 23 || L.gu_type == 29 || L.gu_type == 42;
6702    if ((em == 1 || em == 2 || em == 4) && amd_gu && !nib_layout(L)) {
6703        switch (L.gu_type) {
6704            STRATA_GU_AMD(16) STRATA_GU_AMD(17) STRATA_GU_AMD(18) STRATA_GU_AMD(21) STRATA_GU_AMD(22) STRATA_GU_AMD(23)
6705            STRATA_GU_AMD(29) STRATA_GU_AMD(42)
6706        }
6707    } else
6708#undef STRATA_GU_AMD
6709#endif
6710#if STRATA_EXPERT_NIBBLE_BUILT
6711    if (nib_layout(L))   // STRATA_EXPERT_NIBBLE: a converted layer's VRAM slots, native_gu_multi_kernel's grid and bits
6712        launch_gu_nib(L, dim3((unsigned) (strata::core::nibble::kRows / 16), (unsigned) gy), s, grp_ptr, grp_start,
6713                      n_groups, ent_tok, X, gate, up);
6714    else
6715#endif
6716    if (!expdec_gu(L, gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_tok, X, gate, up))   // STRATA_EXPDEC=1
6717    switch (L.gu_type) {
6718#define STRATA_GU(T) case T: launch_gu<T>(ggu, s, grp_ptr, grp_start, n_groups, ent_tok, X, L, gate, up); break;
6719        STRATA_GU_FMTS(STRATA_GU)
6720#undef STRATA_GU
6721        default: std::fprintf(stderr, "native_expert_grouped: gate/up type %d\n", L.gu_type); std::exit(1);
6722    }
6723#if STRATA_EXP_LAYOUTS
6724    }
6725#endif
6726    check("native_expert_grouped/gu");
6727    if (g_exp_phase == 3) return;   // the bench: gate/up only
6728    const long long nh = (long long) cap_entries * L.n_ff;
6729#if defined(STRATA_HIP_GFX906)
6730    // gfx906: the separate SwiGLU and q8_1 passes stay the default (the A/B baseline); the RDNA one-pass
6731    // kernel (bitwise the same) with STRATA_HIP_SWIGLU_FUSED=1
6732    static const bool sw_fused = env_on("STRATA_HIP_SWIGLU_FUSED");
6733    const bool sw_v1 = v1 || !sw_fused;
6734#else
6735    const bool sw_v1 = v1;
6736#endif
6737    // APR: Hadamard-folded down weights take the rotated h, so h exists as floats first (the separate passes)
6738    if (sw_v1 || L.had_block > 0) {
6739        swiglu_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, h, nh);
6740        if (L.had_block > 0)   // APR: the down weights are Hadamard-folded, so is their input (in place, every entry row)
6741            hadamard_rows(h, h, cap_entries, L.n_ff, L.had_block, L.d_signs, s);
6742        quantize_q8_1_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(h, hq, nh);
6743    } else {
6744        swiglu_q8_1_entries_kernel<<<(unsigned) ((nh + 255) / 256), 256, 0, s>>>(gate, up, grp_start, n_groups,
6745                                                                                (int) L.n_ff, hq);
6746    }
6747    check("native_expert_grouped/swiglu");
6748    }
6749    if (g_exp_phase == 1) return;
6750    // STRATA_LAT_DOWN_S26 (opt-in): the S26 down rows for a geometry the S26 path's n_embd 2560 gate excludes - the
6751    // latent pack's 1280 / n_ff 640.  s26_down_l_kernel carries no n_embd constant (r0, live and the output row are all
6752    // runtime) and its LDS row is n_ff/32 = 20 blocks, so it is the IQ4_NL latent down as it stands: the fp4 latent
6753    // kernel's 1280/640 structure, with 16-byte weight blocks instead of the 2-byte loads native_down_multi_kernel
6754    // issues one item at a time.  Bitwise native_down_multi_kernel's (S26 harness).
6755    static const bool lat_down_s26 = env_on("STRATA_LAT_DOWN_S26");
6756    if (lat_down_s26 && L.d_type == 20 && L.n_ff == 640 && L.n_embd > 0 && L.n_embd % 32 == 0) {
6757        const dim3 gl((unsigned) ((L.n_embd + 31) / 32), (unsigned) cap_groups);
6758        s26_down_l_kernel<true, 4><<<gl, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
6759        check("native_expert_grouped/down lat s26");
6760        return;
6761    }
6762    const bool tq_sub8 = (L.d_type == 144 || L.d_type == 146) && !g_old_kernels && !g_no_sub16_gu && L.n_ff == 640 && (tq_stage_on() || tq_sub8_on());   // the trellis down rows as 8-lane rows
6763    const int d_rows = (!g_old_kernels && !g_no_sub16_gu && L.n_ff == 640) ? (L.d_type == 20 || L.d_type == 40 || tq_sub8 ? 32 : (L.d_type == 42 ? 16 : 8)) : 8;
6764    const int tq_ch = tq_sub8 ? tq_row_chunks() : 1;   // the staged trellis down kernel takes this many 32-row chunks a block
6765    const dim3 gd((unsigned) (((L.n_embd + d_rows - 1) / d_rows + tq_ch - 1) / tq_ch), (unsigned) gy);
6766#if STRATA_DOWN_WS_BUILT
6767    if (down_ws_on(L)) {   // STRATA_DOWN_WS=1 (cc 6.0): the staged down rows, bitwise native_down_multi_kernel's
6768        launch_down_ws(L, gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, out);
6769        check("native_expert_grouped/down ws");
6770        return;
6771    }
6772#endif
6773#if STRATA_EXP_LAYOUTS
6774    const int em0d = sm75_down_em(em0, cap_groups);
6775    int dev_d = 0;
6776    cudaGetDevice(&dev_d);
6777    // gfx1151: the LDS down kernel is slower than the CUDA layout for IQ4_NL (86 vs 63 us, 24 groups) and faster for Q2_0 (-18%)
6778    const bool lds_down_ok = L.d_type == 42 || (L.d_type == 20 && !gfx1151_exp8(dev_d));
6779    if ((em0d == 7 || em0d == 8) && lds_down_ok) {
6780        const dim3 gl((unsigned) ((L.n_embd + LDS_RB - 1) / LDS_RB), (unsigned) cap_groups);
6781        const size_t sh = (size_t) LDS_NT * (size_t) (L.n_ff / 32) * sizeof(block_q8_1);
6782        if (L.d_type == 20) native_down_lds_kernel<20><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
6783        else native_down_lds_kernel<42><<<gl, 256, sh, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out);
6784        check("native_expert_grouped/down");
6785        return;
6786    }
6787    const int em = em0d >= 5 ? kExpFallback : em0d;
6788    const dim3 gd_amd((unsigned) ((L.n_embd + (em == 1 ? 3 : em == 4 ? 31 : 15)) / (em == 1 ? 4 : em == 4 ? 32 : 16)), (unsigned) cap_groups);
6789#define STRATA_D_AMD(T) \
6790    case T: if (em == 1) native_down_amd_kernel<T, 1><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \
6791            else if (em == 4) native_down_amd_kernel<T, 4><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \
6792            else native_down_amd_kernel<T, 2><<<gd_amd, 256, 0, s>>>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
6793    // the AMD layouts cover the IQ packs' down types; the others (Unsloth's Q4_K / Q5_K / Q5_1 / Q8_0) take the
6794    // CUDA layout below
6795    if ((em == 1 || em == 2 || em == 4) && (L.d_type == 20 || L.d_type == 23 || L.d_type == 42)) {
6796        switch (L.d_type) {
6797            STRATA_D_AMD(20) STRATA_D_AMD(23) STRATA_D_AMD(42)
6798        }
6799    } else
6800#undef STRATA_D_AMD
6801#endif
6802    if (!expdec_down(L, gy, cap_groups, s, grp_ptr, grp_start, n_groups, ent_dst, hq, out))   // STRATA_EXPDEC=1
6803    switch (L.d_type) {
6804#define STRATA_DOWN(T) case T: launch_down<T>(gd, s, grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); break;
6805        STRATA_D_FMTS(STRATA_DOWN)
6806#undef STRATA_DOWN
6807        default: std::fprintf(stderr, "native_expert_grouped: down type %d\n", L.d_type); std::exit(1);
6808    }
6809    check("native_expert_grouped/down");
6810}
6811
6812}  // namespace strata::kernels
6813
6814// ---------------------------------------------------------------- STRATA_EXPERT_NIBBLE: expert_nibble.hpp's functions
6815namespace strata::core::nibble {
6816
6817#if STRATA_EXPERT_NIBBLE_BUILT
6818namespace {
6819int g_rev_ready[64];   // per device: 0 not built, 1 built, 2 a grid entry not unique (refused)
6820
6821bool rev_ready() {
6822    int dev = 0;
6823    return cudaGetDevice(&dev) == cudaSuccess && dev >= 0 && dev < 64 && g_rev_ready[dev] == 1;
6824}
6825}  // namespace
6826#endif
6827
6828int prepare(void* stream) {
6829#if STRATA_EXPERT_NIBBLE_BUILT
6830    int dev = 0;
6831    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return (int) cudaErrorInvalidDevice;
6832    if (g_rev_ready[dev] == 1) return 0;
6833    if (g_rev_ready[dev] == 2) return (int) cudaErrorInvalidValue;
6834    cudaStream_t s = (cudaStream_t) stream;
6835    strata::kernels::nib_rev_clear_kernel<<<(strata::kernels::kNibRev22 + 255) / 256, 256, 0, s>>>();
6836    strata::kernels::nib_rev_fill_kernel<<<(1024 + 256 + 512 + 255) / 256, 256, 0, s>>>();
6837    cudaError_t e = cudaGetLastError();
6838    unsigned long long bad = 0;
6839    if (e == cudaSuccess) e = cudaStreamSynchronize(s);
6840    if (e == cudaSuccess) e = cudaMemcpyFromSymbol(&bad, strata::kernels::g_nib_rev_bad, sizeof bad);
6841    if (e != cudaSuccess) return (int) e;
6842    g_rev_ready[dev] = bad == 0 ? 1 : 2;
6843    return bad == 0 ? 0 : (int) cudaErrorInvalidValue;
6844#else
6845    (void) stream;
6846    return 1;   // cudaErrorInvalidValue: not in this build
6847#endif
6848}
6849
6850int transcode(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs,
6851              unsigned long long* bad, void* stream) {
6852#if STRATA_EXPERT_NIBBLE_BUILT
6853    if (n <= 0) return 0;
6854    if (!L.on || !fmt_built(L.gu_type) || L.raw_gu_row != raw_gu_row(L.gu_type) ||
6855        L.raw_up_off != (uint64_t) kNFf * L.raw_gu_row || L.raw_bytes < 2 * L.raw_up_off)
6856        return (int) cudaErrorInvalidValue;
6857    const long long nthr = (long long) n * kRows * kItems;
6858    const dim3 grid((unsigned) ((nthr + 255) / 256));
6859    cudaStream_t s = (cudaStream_t) stream;
6860    const uint8_t* src = (const uint8_t*) staging;
6861#define STRATA_NIB_TC(TG) \
6862    strata::kernels::nib_transcode_kernel<TG><<<grid, 256, 0, s>>>(src, L.raw_bytes, L.raw_gu_row, L.raw_up_off, slot_ptrs, n, bad)
6863    switch (L.gu_type) {
6864        case kIQ2_S: STRATA_NIB_TC(22); break;
6865        case kIQ3_XXS: STRATA_NIB_TC(18); break;
6866        case kIQ3_S: STRATA_NIB_TC(21); break;
6867        default: return (int) cudaErrorInvalidValue;
6868    }
6869#undef STRATA_NIB_TC
6870    return (int) cudaGetLastError();
6871#else
6872    (void) L; (void) staging; (void) n; (void) slot_ptrs; (void) bad; (void) stream;
6873    return 1;   // cudaErrorInvalidValue: not in this build
6874#endif
6875}
6876
6877#if STRATA_EXPERT_NIBBLE_BUILT
6878namespace {
6879int launch_gguf(const LayerVram& L, strata::kernels::NibGgufArgs& a, bool check, cudaStream_t s) {
6880    namespace K = strata::kernels;
6881    if (!L.on || !fmt_built(L.gu_type) || L.raw_gu_row != raw_gu_row(L.gu_type) || L.down_bytes % 16 != 0 ||
6882        L.raw_up_off != (uint64_t) kNFf * L.raw_gu_row || L.raw_down_off != 2 * L.raw_up_off)
6883        return (int) cudaErrorInvalidValue;
6884    if (!rev_ready()) return (int) cudaErrorNotReady;   // prepare() was not run on this device
6885    a.gu_row = L.raw_gu_row;
6886    a.down16 = L.down_bytes / 16;
6887    const int64_t tail = (int64_t) (a.down16 + 2 * a.zero16);
6888    const int64_t per = (int64_t) K::kNibGgufThreads * K::kNibGgufWords;
6889    const dim3 grid((unsigned) (kRows / K::kNibGgufRows + (tail + per - 1) / per), (unsigned) (a.n - a.first));
6890#define STRATA_NIB_GG(TG) \
6891    (check ? K::nib_gguf_kernel<TG, true><<<grid, K::kNibGgufThreads, 0, s>>>(a) \
6892           : K::nib_gguf_kernel<TG, false><<<grid, K::kNibGgufThreads, 0, s>>>(a))
6893    switch (L.gu_type) {
6894        case kIQ2_S: STRATA_NIB_GG(22); break;
6895        case kIQ3_XXS: STRATA_NIB_GG(18); break;
6896        case kIQ3_S: STRATA_NIB_GG(21); break;
6897        default: return (int) cudaErrorInvalidValue;
6898    }
6899#undef STRATA_NIB_GG
6900    return (int) cudaGetLastError();
6901}
6902}  // namespace
6903#endif
6904
6905int check_gguf(const LayerVram& L, const void* staging, int64_t n, const unsigned long long* slot_ptrs,
6906               unsigned long long* bad, void* stream) {
6907#if STRATA_EXPERT_NIBBLE_BUILT
6908    if (n <= 0) return 0;
6909    if (n > 65535) return (int) cudaErrorInvalidValue;
6910    strata::kernels::NibGgufArgs a{};
6911    a.dev = slot_ptrs;
6912    a.first = 0;
6913    a.n = (int) n;
6914    a.gu = (uint8_t*) staging;
6915    a.gu_stride = L.raw_bytes;
6916    a.d = (uint8_t*) staging + L.raw_down_off;
6917    a.d_stride = L.raw_bytes;
6918    a.zero16 = 0;
6919    a.bad = bad;
6920    if (((uintptr_t) staging | L.raw_bytes) % 16 != 0) return (int) cudaErrorInvalidValue;
6921    return launch_gguf(L, a, true, (cudaStream_t) stream);
6922#else
6923    (void) L; (void) staging; (void) n; (void) slot_ptrs; (void) bad; (void) stream;
6924    return 1;   // cudaErrorInvalidValue: not in this build
6925#endif
6926}
6927
6928int gather_gguf(const LayerVram& L, const uint8_t* const* slots, int first, int n, void* gu_dst, uint64_t gu_stride,
6929                void* d_dst, uint64_t d_stride, uint64_t zero_bytes, void* stream) {
6930#if STRATA_EXPERT_NIBBLE_BUILT
6931    if (first < 0 || n <= first || n > 16) return (int) cudaErrorInvalidValue;
6932    uintptr_t al = (uintptr_t) gu_dst | (uintptr_t) d_dst | gu_stride | d_stride | zero_bytes;
6933    for (int q = first; q < n; ++q) al |= (uintptr_t) slots[q];
6934    if (al % 16 != 0 || gu_stride < (uint64_t) kRows * L.raw_gu_row || d_stride < L.down_bytes) return (int) cudaErrorInvalidValue;
6935    strata::kernels::NibGgufArgs a{};
6936    a.dev = nullptr;
6937    for (int q = first; q < n; ++q) a.p[q] = slots[q];
6938    a.first = first;
6939    a.n = n;
6940    a.gu = (uint8_t*) gu_dst;
6941    a.gu_stride = gu_stride;
6942    a.d = (uint8_t*) d_dst;
6943    a.d_stride = d_stride;
6944    a.zero16 = zero_bytes / 16;
6945    a.bad = nullptr;
6946    return launch_gguf(L, a, false, (cudaStream_t) stream);
6947#else
6948    (void) L; (void) slots; (void) first; (void) n; (void) gu_dst; (void) gu_stride; (void) d_dst; (void) d_stride;
6949    (void) zero_bytes; (void) stream;
6950    return 1;   // cudaErrorInvalidValue: not in this build
6951#endif
6952}
6953
6954int hash_slots(const LayerVram& L, const unsigned long long* slot_ptrs, int64_t n, unsigned long long* out, void* stream) {
6955#if STRATA_EXPERT_NIBBLE_BUILT
6956    if (n <= 0) return 0;
6957    if (L.hashed == 0) return (int) cudaErrorInvalidValue;
6958    cudaStream_t s = (cudaStream_t) stream;
6959    const cudaError_t e = cudaMemsetAsync(out, 0, (size_t) n * sizeof(unsigned long long), s);
6960    if (e != cudaSuccess) return (int) e;
6961    // ~2.7 MB a slot: 32 blocks of 256 threads each, ~21 16-byte loads a thread
6962    strata::kernels::nib_hash_kernel<<<dim3(32, (unsigned) n), 256, 0, s>>>(slot_ptrs, L.hashed, out);
6963    return (int) cudaGetLastError();
6964#else
6965    (void) L; (void) slot_ptrs; (void) n; (void) out; (void) stream;
6966    return 1;   // cudaErrorInvalidValue: not in this build
6967#endif
6968}
6969
6970}  // namespace strata::core::nibble
6971
6972// ---- Volta prompt experts (STRATA_PF_WMMA): a group's experts as one launch of FP16 tensor-core tiles, the weights
6973// dequantized into shared memory by dq_dispatch (the FP16 path's own formulas), the activations FP16, FP32 sums.
6974// Replaces MMQ's dp4a products on sm_70, and the FP16 path's dequantize-to-global + one cuBLAS call per expert.
6975#if !defined(__HIPCC__)
6976#include <mma.h>
6977namespace strata::kernels {
6978namespace {
6979constexpr int WG_BM = 64, WG_BN = 128, WG_THREADS = 256, WG_XK = 128, WG_MT = 4;
6980// A block: BN = 128 weight rows of one expert x up to WG_MT * BM = 256 of its token rows (blockIdx.y walks an expert's
6981// rows in such chunks), so every weight superblock is dequantized ONCE per chunk into shared memory (WK 256: an IQ
6982// superblock through dq_dispatch; WK 128: two Q2_0 blocks, or four IQ4_NL blocks); the activations stream through a
6983// BM x 128 tile.  8 warps of 32 x 32 per m-tile (2 x 2 fragments), FP32 accumulators for the chunk's m-tiles in registers.
6984template<int WK, bool Q20, bool IQNL = false>
6985__global__ void __launch_bounds__(WG_THREADS) gemm_iq_f16_grouped_kernel(int ty, const uint8_t* __restrict__ W,
6986                                                                         size_t expert_bytes, size_t row_bytes, int K,
6987                                                                         const __half* __restrict__ X, int ldx,
6988                                                                         const int32_t* __restrict__ bounds, int ch_per_e,
6989                                                                         float* __restrict__ Y, int ldy) {
6990#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700   // the sm_60 pass of a multi-arch build has no nvcuda::wmma (the host never launches these there)
6991    using namespace nvcuda;
6992    constexpr int LDW = WK + 8, LDX = WG_XK + 8;
6993    extern __shared__ __align__(16) unsigned char wg_smem[];
6994    __half* sw = reinterpret_cast<__half*>(wg_smem);            // [BN][LDW]
6995    __half* sx = sw + WG_BN * LDW;                               // [BM][LDX]
6996    const int e = blockIdx.y / ch_per_e, ch = blockIdx.y % ch_per_e;
6997    const int c0 = bounds[e] + ch * WG_MT * WG_BM, r1 = bounds[e + 1];
6998    if (c0 >= r1) return;
6999    const int crow = min(WG_MT * WG_BM, r1 - c0);
7000    const int nmt = (crow + WG_BM - 1) / WG_BM;
7001    const int n0 = blockIdx.x * WG_BN;
7002    const uint8_t* we = W + (size_t) e * expert_bytes;
7003    const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31;
7004    const int wm = warp >> 2, wn = warp & 3;                     // rows wm*32, cols wn*32 of an m-tile
7005    wmma::fragment<wmma::accumulator, 16, 16, 16, float> acc[WG_MT][2][2];
7006#pragma unroll
7007    for (int t = 0; t < WG_MT; ++t)
7008#pragma unroll
7009        for (int a = 0; a < 2; ++a)
7010#pragma unroll
7011            for (int b = 0; b < 2; ++b) wmma::fill_fragment(acc[t][a][b], 0.0f);
7012    // the activation tiles in order (k0, m-tile, half): the next one's 4 uint4 per thread are loaded into registers
7013    // while the current one is multiplied (the first before the weights' dequantization)
7014    constexpr int XQ = WG_BM * (WG_XK / 8) / WG_THREADS;        // 4
7015    const int nx = WK / WG_XK, per_k = nmt * nx, total = (K / WK) * per_k;
7016    uint4 xr[XQ];
7017    auto load_x = [&](int it) {
7018        const int kb = it / per_k, rem = it % per_k, t = rem / nx, xh = rem % nx;
7019        const int rows = min(WG_BM, crow - t * WG_BM);
7020#pragma unroll
7021        for (int q = 0; q < XQ; ++q) {
7022            const int i = tid + q * WG_THREADS, r = i / (WG_XK / 8), c = (i % (WG_XK / 8)) * 8;
7023            xr[q] = r < rows ? *reinterpret_cast<const uint4*>(X + (size_t) (c0 + t * WG_BM + r) * ldx + kb * WK + xh * WG_XK + c)
7024                             : make_uint4(0, 0, 0, 0);
7025        }
7026    };
7027    load_x(0);
7028    int it = 0;
7029    for (int k0 = 0; k0 < K; k0 += WK) {
7030        if constexpr (IQNL) {
7031            // IQ4_NL down (WK 128 = 4 x block_iq4_nl): one thread per (row, 64-value half) - the four blocks of the
7032            // 128-value window sit in two halves of two blocks, and each thread's values are exactly dq_iq4_nl's
7033            const int r = tid >> 1, half = tid & 1;
7034            const block_iq4_nl* bp = reinterpret_cast<const block_iq4_nl*>(we + (size_t) (n0 + r) * row_bytes) + k0 / 32 + half * 2;
7035            __half* o = sw + r * LDW + half * 64;
7036#pragma unroll
7037            for (int bl = 0; bl < 2; ++bl) {
7038                const block_iq4_nl* b = bp + bl;
7039                const float d = (float) b->d;
7040#pragma unroll
7041                for (int p = 0; p < 16; ++p) {
7042                    o[bl * 32 + p] = cvt<__half>(d * kvalues_iq4nl[b->qs[p] & 0xf]);
7043                    o[bl * 32 + p + 16] = cvt<__half>(d * kvalues_iq4nl[b->qs[p] >> 4]);
7044                }
7045            }
7046        } else if constexpr (!Q20) {
7047            for (int r = warp; r < WG_BN; r += WG_THREADS / 32)
7048                dq_dispatch<__half>(ty, we + (size_t) (n0 + r) * row_bytes, k0 / 256, sw + r * LDW, lane);
7049        } else {
7050            const int r = tid >> 1, blk = tid & 1;   // one thread per (row, 64-value block)
7051            const block_q2_0* b = reinterpret_cast<const block_q2_0*>(we + (size_t) (n0 + r) * row_bytes) + k0 / 64 + blk;
7052            const float d = (float) b->d;
7053            uint4 q4;
7054            memcpy(&q4, b->qs, 16);
7055            const uint8_t* qb = reinterpret_cast<const uint8_t*>(&q4);
7056            __half* o = sw + r * LDW + blk * 64;
7057#pragma unroll
7058            for (int c = 0; c < 16; ++c) {
7059                const int v = qb[c];
7060                *reinterpret_cast<__half2*>(o + 4 * c) = __floats2half2_rn(d * (float) ((v & 3) - 1), d * (float) (((v >> 2) & 3) - 1));
7061                *reinterpret_cast<__half2*>(o + 4 * c + 2) = __floats2half2_rn(d * (float) (((v >> 4) & 3) - 1), d * (float) (((v >> 6) & 3) - 1));
7062            }
7063        }
7064#pragma unroll
7065        for (int t = 0; t < WG_MT; ++t) {
7066            if (t >= nmt) break;
7067#pragma unroll 1
7068            for (int xh = 0; xh < WK / WG_XK; ++xh, ++it) {
7069                __syncthreads();                                 // the previous X tile is consumed (and W is written)
7070#pragma unroll
7071                for (int q = 0; q < XQ; ++q) {
7072                    const int i = tid + q * WG_THREADS, r = i / (WG_XK / 8), c = (i % (WG_XK / 8)) * 8;
7073                    *reinterpret_cast<uint4*>(sx + r * LDX + c) = xr[q];
7074                }
7075                __syncthreads();
7076                if (it + 1 < total) load_x(it + 1);
7077#pragma unroll
7078                for (int kk = 0; kk < WG_XK; kk += 16) {
7079                    wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> a[2];
7080                    wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::col_major> b[2];
7081#pragma unroll
7082                    for (int f = 0; f < 2; ++f) {
7083                        wmma::load_matrix_sync(a[f], sx + (wm * 32 + f * 16) * LDX + kk, LDX);
7084                        wmma::load_matrix_sync(b[f], sw + (wn * 32 + f * 16) * LDW + xh * WG_XK + kk, LDW);
7085                    }
7086#pragma unroll
7087                    for (int fa = 0; fa < 2; ++fa)
7088#pragma unroll
7089                        for (int fb = 0; fb < 2; ++fb) wmma::mma_sync(acc[t][fa][fb], a[fa], b[fb], acc[t][fa][fb]);
7090                }
7091            }
7092        }
7093        __syncthreads();                                         // W is consumed before the next superblock
7094    }
7095    float* so = reinterpret_cast<float*>(wg_smem);               // [BM][BN + 4] per m-tile
7096    constexpr int LDO = WG_BN + 4;
7097#pragma unroll
7098    for (int t = 0; t < WG_MT; ++t) {
7099        if (t >= nmt) break;
7100        const int rows = min(WG_BM, crow - t * WG_BM);
7101#pragma unroll
7102        for (int fa = 0; fa < 2; ++fa)
7103#pragma unroll
7104            for (int fb = 0; fb < 2; ++fb)
7105                wmma::store_matrix_sync(so + (wm * 32 + fa * 16) * LDO + wn * 32 + fb * 16, acc[t][fa][fb], LDO, wmma::mem_row_major);
7106        __syncthreads();
7107        for (int i = tid; i < rows * (WG_BN / 4); i += WG_THREADS) {
7108            const int r = i / (WG_BN / 4), c = (i % (WG_BN / 4)) * 4;
7109            *reinterpret_cast<float4*>(Y + (size_t) (c0 + t * WG_BM + r) * ldy + n0 + c) = *reinterpret_cast<const float4*>(so + r * LDO + c);
7110        }
7111        __syncthreads();
7112    }
7113#endif
7114}
7115
7116// ---- STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down, tiled like a Volta MoE kernel in the
7117// PR author's own unpublished llama.cpp patches.
7118// A block: W2_RB = 128 weight rows of one expert x W2_CB = 64 of its sorted rows, K stages of W2_KT = 64. Thread t dequantizes
7119// row t % 128, 32-value sub-block t / 128 of each K stage from the raw stage in shared memory (one IQ2_S super-block or four IQ4_NL
7120// blocks per row, read by the whole block as 4-byte words, the next one already in registers). 8 warps = 4 (32 weight rows) x 2
7121// (32 sorted rows), 2 x 2 wmma 16x16x16 fragments each, FP32 sums.
7122constexpr int W2_RB = 128, W2_CB = 64, W2_KT = 64, W2_NT = 256, W2_LD = W2_KT + 8;
7123template <int TY> struct w2_traits;
7124template <> struct w2_traits<22> { static constexpr int raw_k = 256, raw_b = 82, segw = 21, segw_s = 21, ntab = 1024 + 16; };
7125template <> struct w2_traits<20> { static constexpr int raw_k = 128, raw_b = 72, segw = 18, segw_s = 19, ntab = 128; };
7126template <int TY> __host__ __device__ constexpr int w2_nl() { return (W2_RB * w2_traits<TY>::segw + W2_NT - 1) / W2_NT; }
7127
7128__device__ __forceinline__ uint32_t w2_ld_b2(const uint8_t* p) {   // 4 bytes at a 2-byte aligned address
7129    const uint16_t* q = reinterpret_cast<const uint16_t*>(p);
7130    return (uint32_t) q[0] | ((uint32_t) q[1] << 16);
7131}
7132__device__ __forceinline__ half2 w2_h2(uint32_t v) { half2 h; memcpy(&h, &v, 4); return h; }
7133__device__ __forceinline__ uint32_t w2_u32(half2 h) { uint32_t v; memcpy(&v, &h, 4); return v; }
7134
7135// the raw stage rs of the block's 128 rows: segw words per row from the 4-byte aligned start at or below rs * raw_b
7136template <int TY>
7137__device__ __forceinline__ void w2_raw_ld(uint32_t (&R)[w2_nl<TY>()], const uint8_t* __restrict__ xb, size_t row_bytes, int rs, int tid) {
7138    using tr = w2_traits<TY>;
7139    const int off = (rs * tr::raw_b) & ~3;
7140#pragma unroll
7141    for (int i = 0; i < w2_nl<TY>(); ++i) {
7142        const int w = tid + i * W2_NT;
7143        if ((W2_RB * tr::segw) % W2_NT == 0 || w < W2_RB * tr::segw)
7144            R[i] = *reinterpret_cast<const uint32_t*>(xb + (size_t) (w / tr::segw) * row_bytes + off + 4 * (w % tr::segw));
7145    }
7146}
7147template <int TY>
7148__device__ __forceinline__ void w2_raw_st(const uint32_t (&R)[w2_nl<TY>()], uint32_t* __restrict__ raw, int tid) {
7149    using tr = w2_traits<TY>;
7150#pragma unroll
7151    for (int i = 0; i < w2_nl<TY>(); ++i) {
7152        const int w = tid + i * W2_NT;
7153        if ((W2_RB * tr::segw) % W2_NT == 0 || w < W2_RB * tr::segw) raw[(w / tr::segw) * tr::segw_s + w % tr::segw] = R[i];
7154    }
7155}
7156
7157// sub-block `sb` (0..7) of the IQ2_S super-block at rr -> 32 halves at o, natural order, bit for bit dq_iq2_s's values:
7158// cvt<__half>(dl * grid[j] * +-1) with dl = d * (0.5 + scale) * 0.25 in FP32 (the sign flips the rounded half, which is the same)
7159__device__ __forceinline__ float w2_b2f(uint32_t w, int j) { return __int_as_float(0x4B000000 | ((w >> 8 * j) & 0xff)) - 8388608.0f; }
7160__device__ __forceinline__ void w2_dq_iq2_s(const uint8_t* rr, int sb, __half* o, const uint2* __restrict__ tab) {
7161    const uint2* sgn = tab + 1024;
7162    const uint32_t sc = rr[2 + 64 + 8 + sb], qh = rr[2 + 64 + sb];
7163    const uint32_t qs = w2_ld_b2(rr + 2 + 4 * sb), sg = w2_ld_b2(rr + 2 + 32 + 4 * sb);
7164    const float d = __half2float(__ushort_as_half(*reinterpret_cast<const uint16_t*>(rr)));
7165    const float dl0 = d * (0.5f + (float) (sc & 0xf)) * 0.25f;
7166    const float dl1 = d * (0.5f + (float) (sc >> 4)) * 0.25f;
7167#pragma unroll
7168    for (int il = 0; il < 4; ++il) {
7169        const float dl = il < 2 ? dl0 : dl1;
7170        const int idx = (int) (((qs >> 8 * il) & 0xff) | ((qh << (8 - 2 * il)) & 0x300));
7171        const uint2 gw = tab[idx];
7172        const uint32_t sbits = (sg >> 8 * il) & 0xff;
7173        const uint2 s0 = sgn[sbits & 15], s1 = sgn[sbits >> 4];
7174        uint4 out;
7175        out.x = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.x, 0), dl * w2_b2f(gw.x, 1))) ^ s0.x;
7176        out.y = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.x, 2), dl * w2_b2f(gw.x, 3))) ^ s0.y;
7177        out.z = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.y, 0), dl * w2_b2f(gw.y, 1))) ^ s1.x;
7178        out.w = w2_u32(__floats2half2_rn(dl * w2_b2f(gw.y, 2), dl * w2_b2f(gw.y, 3))) ^ s1.y;
7179        *reinterpret_cast<uint4*>(o + 8 * il) = out;
7180    }
7181}
7182// IQ4_NL block at b -> 32 halves at o, natural order (value j: the low nibble of byte j, value j + 16: its high nibble); the product
7183// of two exact halves rounded once, as cvt<__half>(d * kvalues_iq4nl[q])
7184__device__ __forceinline__ void w2_dq_iq4_nl(const uint8_t* b, __half* o, const half2* __restrict__ kv) {
7185    const half2 d2 = __half2half2(__ushort_as_half(*reinterpret_cast<const uint16_t*>(b)));
7186#pragma unroll
7187    for (int i = 0; i < 4; ++i) {
7188        const uint32_t q = w2_ld_b2(b + 2 + 4 * i);
7189        const half2 t0 = kv[q & 0xff], t1 = kv[(q >> 8) & 0xff], t2 = kv[(q >> 16) & 0xff], t3 = kv[q >> 24];
7190        uint2 lo, hi;
7191        lo.x = w2_u32(__hmul2(__lows2half2(t0, t1), d2));
7192        lo.y = w2_u32(__hmul2(__lows2half2(t2, t3), d2));
7193        hi.x = w2_u32(__hmul2(__highs2half2(t0, t1), d2));
7194        hi.y = w2_u32(__hmul2(__highs2half2(t2, t3), d2));
7195        *reinterpret_cast<uint2*>(o + 4 * i) = lo;
7196        *reinterpret_cast<uint2*>(o + 16 + 4 * i) = hi;
7197    }
7198}
7199
7200template <int TY>
7201__global__ void __launch_bounds__(W2_NT, 2) gemm_iq_f16_w2_kernel(const uint8_t* __restrict__ W, size_t expert_bytes, size_t row_bytes,
7202                                                                  int K, const __half* __restrict__ X, int ldx,
7203                                                                  const int32_t* __restrict__ bounds, int ch_per_e,
7204                                                                  float* __restrict__ Y, int ldy) {
7205#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ >= 700   // the sm_60 pass of a multi-arch build has no nvcuda::wmma (the host never launches these there)
7206    using namespace nvcuda;
7207    using tr = w2_traits<TY>;
7208    constexpr int NL = w2_nl<TY>(), NSUB = tr::raw_k / W2_KT;
7209    __shared__ __align__(128) __half xs[W2_RB * W2_LD];
7210    __shared__ __align__(128) __half ys[W2_CB * W2_LD];
7211    __shared__ uint2 tab[tr::ntab];
7212    __shared__ uint32_t raw[W2_RB * tr::segw_s];
7213
7214    const int e = blockIdx.y / ch_per_e, ch = blockIdx.y % ch_per_e;
7215    const int c0 = bounds[e] + ch * W2_CB, r1 = bounds[e + 1];
7216    if (c0 >= r1) return;
7217    const int ncol = min(W2_CB, r1 - c0);
7218    const int n0 = blockIdx.x * W2_RB;
7219    const int tid = threadIdx.x, warp = tid >> 5, lane = tid & 31;
7220    const int wr = warp & 3, wc = warp >> 2;                     // weight rows wr*32, sorted rows wc*32
7221    const uint8_t* xb = W + (size_t) e * expert_bytes + (size_t) n0 * row_bytes;
7222    const int nrs = K / tr::raw_k;
7223
7224    uint32_t R[NL];
7225    w2_raw_ld<TY>(R, xb, row_bytes, 0, tid);
7226    const int yq = tid & 7, yc = tid >> 3;                       // 16-byte part yq of sorted rows yc and yc + 32
7227    uint4 Yr[2];
7228    auto load_y = [&](int k0) {
7229#pragma unroll
7230        for (int u = 0; u < 2; ++u) {
7231            const int c = yc + 32 * u;
7232            Yr[u] = c < ncol ? *reinterpret_cast<const uint4*>(X + (size_t) (c0 + c) * ldx + k0 + 8 * yq) : make_uint4(0, 0, 0, 0);
7233        }
7234    };
7235    load_y(0);
7236    if constexpr (TY == 20) {
7237        reinterpret_cast<half2*>(tab)[tid] = __halves2half2(__int2half_rn(kvalues_iq4nl[tid & 15]), __int2half_rn(kvalues_iq4nl[tid >> 4]));
7238    } else {
7239        for (int i = tid; i < 1024; i += W2_NT) tab[i] = reinterpret_cast<const uint2*>(iq2s_grid)[i];
7240        if (tid < 16)   // a sign nibble -> masks of its bits 0-1 and 2-3 (bit 2p -> bit 15, bit 2p + 1 -> bit 31)
7241            tab[1024 + tid] = make_uint2(((tid >> 0) & 1u) << 15 | ((tid >> 1) & 1u) << 31, ((tid >> 2) & 1u) << 15 | ((tid >> 3) & 1u) << 31);
7242    }
7243    w2_raw_st<TY>(R, raw, tid);
7244    if (nrs > 1) w2_raw_ld<TY>(R, xb, row_bytes, 1, tid);
7245    __syncthreads();
7246
7247    wmma::fragment<wmma::accumulator, 16, 16, 16, float> acc[2][2];
7248#pragma unroll
7249    for (int a = 0; a < 2; ++a)
7250#pragma unroll
7251        for (int b = 0; b < 2; ++b) wmma::fill_fragment(acc[a][b], 0.0f);
7252    const int xr = tid % W2_RB, sub = tid / W2_RB;
7253    __half* xrow = xs + xr * W2_LD + 32 * sub;
7254    const uint8_t* rawrow = reinterpret_cast<const uint8_t*>(raw + xr * tr::segw_s);
7255
7256    for (int rs = 0; rs < nrs; ++rs) {
7257        const uint8_t* rr = rawrow + ((rs * tr::raw_b) & 3);
7258#pragma unroll
7259        for (int h = 0; h < NSUB; ++h) {
7260            const int k0 = (rs * NSUB + h) * W2_KT;
7261            if constexpr (TY == 20) w2_dq_iq4_nl(rr + 18 * (2 * h + sub), xrow, reinterpret_cast<const half2*>(tab));
7262            else w2_dq_iq2_s(rr, 2 * h + sub, xrow, tab);
7263#pragma unroll
7264            for (int u = 0; u < 2; ++u) *reinterpret_cast<uint4*>(ys + (yc + 32 * u) * W2_LD + 8 * yq) = Yr[u];
7265            __syncthreads();
7266            if (k0 + W2_KT < K) load_y(k0 + W2_KT);
7267            if (wc * 32 < ncol) {                                // warp-uniform: sorted rows past the expert's skip their mma
7268#pragma unroll
7269                for (int kk = 0; kk < W2_KT; kk += 16) {
7270                    wmma::fragment<wmma::matrix_a, 16, 16, 16, __half, wmma::row_major> a[2];
7271                    wmma::fragment<wmma::matrix_b, 16, 16, 16, __half, wmma::col_major> b[2];
7272#pragma unroll
7273                    for (int f = 0; f < 2; ++f) {
7274                        wmma::load_matrix_sync(a[f], ys + (wc * 32 + f * 16) * W2_LD + kk, W2_LD);
7275                        wmma::load_matrix_sync(b[f], xs + (wr * 32 + f * 16) * W2_LD + kk, W2_LD);
7276                    }
7277#pragma unroll
7278                    for (int fa = 0; fa < 2; ++fa) {
7279                        if (wc * 32 + fa * 16 >= ncol) break;
7280#pragma unroll
7281                        for (int fb = 0; fb < 2; ++fb) wmma::mma_sync(acc[fa][fb], a[fa], b[fb], acc[fa][fb]);
7282                    }
7283                }
7284            }
7285            if (h == NSUB - 1 && rs + 1 < nrs) {                 // nobody reads raw between the barrier above and the one below
7286                w2_raw_st<TY>(R, raw, tid);
7287                if (rs + 2 < nrs) w2_raw_ld<TY>(R, xb, row_bytes, rs + 2, tid);
7288            }
7289            __syncthreads();
7290        }
7291    }
7292    // full 16-row tiles straight to Y; the expert's last partial one through the warp's 16 x 16 scratch (ys is free now)
7293    float* scr = reinterpret_cast<float*>(ys) + warp * 256;
7294#pragma unroll
7295    for (int fa = 0; fa < 2; ++fa) {
7296        const int t0 = wc * 32 + fa * 16;
7297        if (t0 >= ncol) break;
7298#pragma unroll
7299        for (int fb = 0; fb < 2; ++fb) {
7300            const int nb = n0 + wr * 32 + fb * 16;
7301            if (t0 + 16 <= ncol) {
7302                wmma::store_matrix_sync(Y + (size_t) (c0 + t0) * ldy + nb, acc[fa][fb], ldy, wmma::mem_row_major);
7303            } else {
7304                wmma::store_matrix_sync(scr, acc[fa][fb], 16, wmma::mem_row_major);
7305                __syncwarp();
7306                for (int i = lane; i < 256; i += 32)
7307                    if (t0 + i / 16 < ncol) Y[(size_t) (c0 + t0 + i / 16) * ldy + nb + i % 16] = scr[i];
7308                __syncwarp();
7309            }
7310        }
7311    }
7312#endif
7313}
7314
7315bool w2_on() {
7316    static const bool v = [] { const char* e = std::getenv("STRATA_PF_WMMA2"); return e && e[0] == '1'; }();
7317    return v;
7318}
7319}  // namespace
7320
7321bool gemm_iq_f16_grouped(int ty, const void* W, size_t expert_bytes, int n_out, int K, const void* X, int ldx,
7322                         const int32_t* bounds, int n_experts, int max_rows, float* Y, int ldy, void* stream) {
7323    if (n_out % WG_BN != 0 || n_experts <= 0 || max_rows <= 0 || ldy % 4 != 0) return false;
7324    {   // the tiles are tensor-core kernels: a pre-Volta card has no body for them (the sm_60 pass compiles them empty)
7325        int cur = 0, major = 0;
7326        if (cudaGetDevice(&cur) != cudaSuccess || cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, cur) != cudaSuccess ||
7327            major < 7)
7328            return false;
7329    }
7330    // STRATA_PF_WMMA2=1 (opt-in): IQ2_S gate/up and IQ4_NL down through gemm_iq_f16_w2_kernel (above)
7331    if (w2_on() && n_out % W2_RB == 0 && ldx % 8 == 0 && ldy % 8 == 0 && (uintptr_t) X % 16 == 0 && (uintptr_t) Y % 32 == 0 &&
7332        (uintptr_t) W % 4 == 0 && expert_bytes % 4 == 0 && ((ty == 22 && K % 512 == 0) || (ty == 20 && K % 128 == 0))) {
7333        const size_t rb = iq_row_bytes(ty, K);
7334        const int ch = (max_rows + W2_CB - 1) / W2_CB;
7335        if (rb % 4 == 0 && (long long) n_experts * ch <= 65535) {
7336            const dim3 grid2((unsigned) (n_out / W2_RB), (unsigned) (n_experts * ch));
7337            cudaStream_t s2 = (cudaStream_t) stream;
7338            if (ty == 22)
7339                gemm_iq_f16_w2_kernel<22><<<grid2, W2_NT, 0, s2>>>((const uint8_t*) W, expert_bytes, rb, K, (const __half*) X, ldx, bounds, ch, Y, ldy);
7340            else
7341                gemm_iq_f16_w2_kernel<20><<<grid2, W2_NT, 0, s2>>>((const uint8_t*) W, expert_bytes, rb, K, (const __half*) X, ldx, bounds, ch, Y, ldy);
7342            return cudaGetLastError() == cudaSuccess;
7343        }
7344    }
7345    const bool q20 = ty == 42;
7346    const bool nl = ty == 20 && K % 256 != 0;   // IQ4_NL down (K=640): there is no WK=256 path for this K
7347    if (q20 || nl ? K % 128 != 0 : (K % 256 != 0 || !is_iq(ty))) return false;
7348    const size_t row_bytes = iq_row_bytes(ty, K);
7349    const int mt = (max_rows + WG_MT * WG_BM - 1) / (WG_MT * WG_BM);   // row chunks per expert
7350    const dim3 grid((unsigned) (n_out / WG_BN), (unsigned) (n_experts * mt));
7351    cudaStream_t s = (cudaStream_t) stream;
7352    auto smem = [](int wk) { return (size_t) WG_BN * (wk + 8) * 2 + (size_t) WG_BM * (WG_XK + 8) * 2; };
7353    // the shared-memory attribute belongs to the current device, so it is set on each card: with one flag for the
7354    // process a layer split's second card launched without it and the prompt stopped ("the WMMA expert tiles could not launch")
7355    static bool attr[64];
7356    int dev = 0;
7357    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 64) return false;
7358    if (!attr[dev]) {
7359        cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<256, false>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(256));
7360        cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<128, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(128));
7361        cudaFuncSetAttribute(gemm_iq_f16_grouped_kernel<128, false, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, (int) smem(128));
7362        attr[dev] = true;
7363    }
7364    if (q20)
7365        gemm_iq_f16_grouped_kernel<128, true><<<grid, WG_THREADS, smem(128), s>>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K,
7366                                                                                 (const __half*) X, ldx, bounds, mt, Y, ldy);
7367    else if (nl)
7368        gemm_iq_f16_grouped_kernel<128, false, true><<<grid, WG_THREADS, smem(128), s>>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K,
7369                                                                                         (const __half*) X, ldx, bounds, mt, Y, ldy);
7370    else
7371        gemm_iq_f16_grouped_kernel<256, false><<<grid, WG_THREADS, smem(256), s>>>(ty, (const uint8_t*) W, expert_bytes, row_bytes, K,
7372                                                                                  (const __half*) X, ldx, bounds, mt, Y, ldy);
7373    return cudaGetLastError() == cudaSuccess;
7374}
7375}  // namespace strata::kernels
7376#else
7377namespace strata::kernels {
7378bool gemm_iq_f16_grouped(int, const void*, size_t, int, int, const void*, int, const int32_t*, int, int, float*, int, void*) {
7379    return false;
7380}
7381}  // namespace strata::kernels
7382#endif