okami.mom/strata

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

Niko1221Int3 merge f-0291-bw-next (4c5a55491); generate.cpp: req_df2 and draft_long both keptde856c7b8

main
193.5 KiB4005 linesraw
1// Adapted from llama.cpp 3cf03257f219afbe7334045ff7c6a06ac68c627d:
2// ggml/src/ggml-cuda/{quantize.cu,vecdotq.cuh,mmvq.cu,common.cuh}
3// and ggml/src/ggml-common.h. See docs/native-mmvq.md for exact scope.
4//
5// MIT License
6// Copyright (c) 2023-2026 The ggml authors
7//
8// Permission is hereby granted, free of charge, to any person obtaining a copy
9// of this software and associated documentation files (the "Software"), to deal
10// in the Software without restriction, including without limitation the rights
11// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12// copies of the Software, and to permit persons to whom the Software is
13// furnished to do so, subject to the following conditions:
14//
15// The above copyright notice and this permission notice shall be included in all
16// copies or substantial portions of the Software.
17//
18// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24// SOFTWARE.
25
26#include "strata/kernels/native_mmvq.hpp"
27#include "strata/kernels/dp4a.hpp"
28#include "strata/kernels/q8_1_finite.hpp"
29#include "strata/kernels/iq_kernels.hpp"
30#include "strata/kernels/gfx_arch.hpp"
31#include "strata/core/sm75_series.hpp"
32#include "strata/core/sm120_series.hpp"
33#include "strata/core/dispatch_stats.hpp"
34#include "strata/core/defaults_026.hpp"
35#include "s26_tsum.cuh"
36#if !defined(__HIPCC__)
37#include "q8_1_il.cuh"
38#endif
39#include "strata/kernels/pdl.hpp"
40
41#include <cuda_fp16.h>
42#include <cuda_runtime.h>
43
44#include <algorithm>
45#include <cstdint>
46#include <cstdlib>
47#include <cstring>
48#include <limits>
49#include <stdexcept>
50#include <type_traits>
51#include <string>
52#include <unordered_map>
53#include <cstdio>
54#include <vector>
55
56namespace strata::kernels {
57namespace {
58
59constexpr int QK = 256;
60constexpr int Q8K = 32;
61constexpr int QI = 32;
62constexpr int VDR = 2;
63constexpr int WARPS = 4;
64constexpr int WARP = 32;
65constexpr int QUANT_THREADS = 256;
66
67struct Q5KBlock {
68    half2 dm;
69    uint8_t scales[12];
70    uint8_t qh[32];
71    uint8_t qs[128];
72};
73struct Q81Block {
74    half2 ds;
75    int8_t qs[32];
76};
77struct Q20Block {
78    half d;
79    uint8_t qs[16];
80};
81struct Q3KBlock {
82    uint8_t hmask[32];
83    uint8_t qs[64];
84    uint8_t scales[12];
85    half d;
86};
87struct IQ4XSBlock {
88    half d;
89    uint16_t scales_h;
90    uint8_t scales_l[4];
91    uint8_t qs[128];
92};
93struct Q4KBlock {
94    half2 dm;
95    uint8_t scales[12];
96    uint8_t qs[128];
97};
98struct Q6KBlock {
99    uint8_t ql[128];
100    uint8_t qh[64];
101    int8_t scales[16];
102    half d;
103};
104struct Q40Block {
105    half d;
106    uint8_t qs[16];
107};
108struct Q50Block {
109    half d;
110    uint8_t qh[4];
111    uint8_t qs[16];
112};
113struct Q80Block {
114    half d;
115    int8_t qs[32];
116};
117struct IQ4NLBlock {
118    half d;
119    uint8_t qs[16];
120};
121static_assert(sizeof(Q5KBlock) == 176 && alignof(Q5KBlock) == 4);
122static_assert(sizeof(Q81Block) == 36 && alignof(Q81Block) == 4);
123static_assert(sizeof(Q20Block) == 18 && alignof(Q20Block) == 2 && offsetof(Q20Block, qs) == 2);
124static_assert(sizeof(Q3KBlock) == 110 && alignof(Q3KBlock) == 2 && offsetof(Q3KBlock, qs) == 32 &&
125              offsetof(Q3KBlock, scales) == 96 && offsetof(Q3KBlock, d) == 108);
126static_assert(sizeof(IQ4XSBlock) == 136 && alignof(IQ4XSBlock) == 2 &&
127              offsetof(IQ4XSBlock, scales_h) == 2 && offsetof(IQ4XSBlock, scales_l) == 4 &&
128              offsetof(IQ4XSBlock, qs) == 8);
129static_assert(offsetof(Q5KBlock, scales) == 4 && offsetof(Q5KBlock, qh) == 16 &&
130              offsetof(Q5KBlock, qs) == 48 && offsetof(Q81Block, qs) == 4);
131static_assert(sizeof(Q4KBlock) == 144 && alignof(Q4KBlock) == 4 &&
132              offsetof(Q4KBlock, scales) == 4 && offsetof(Q4KBlock, qs) == 16);
133static_assert(sizeof(Q6KBlock) == 210 && alignof(Q6KBlock) == 2 &&
134              offsetof(Q6KBlock, qh) == 128 && offsetof(Q6KBlock, scales) == 192 &&
135              offsetof(Q6KBlock, d) == 208);
136static_assert(sizeof(Q40Block) == 18 && alignof(Q40Block) == 2 && offsetof(Q40Block, qs) == 2);
137static_assert(sizeof(Q50Block) == 22 && alignof(Q50Block) == 2 &&
138              offsetof(Q50Block, qh) == 2 && offsetof(Q50Block, qs) == 6);
139static_assert(sizeof(Q80Block) == 34 && alignof(Q80Block) == 2 && offsetof(Q80Block, qs) == 2);
140static_assert(sizeof(IQ4NLBlock) == 18 && alignof(IQ4NLBlock) == 2 && offsetof(IQ4NLBlock, qs) == 2);
141
142__device__ __forceinline__ float warp_sum(float x) {
143#pragma unroll
144    for (int offset = WARP / 2; offset > 0; offset >>= 1) {
145        x += __shfl_xor_sync(0xffffffff, x, offset, WARP);
146    }
147    return x;
148}
149
150__device__ __forceinline__ float warp_max(float x) {
151#pragma unroll
152    for (int offset = WARP / 2; offset > 0; offset >>= 1) {
153        x = fmaxf(x, __shfl_xor_sync(0xffffffff, x, offset, WARP));
154    }
155    return x;
156}
157
158__launch_bounds__(QUANT_THREADS, 1)
159__global__ void native_quantize_q8_1_kernel(const float* x_, Q81Block* y_, int n_in) {
160    const float* STRATA_PDL_RESTRICT x = x_;   // __restrict__ below sm_70 only (pdl.hpp, #1469)
161    Q81Block* STRATA_PDL_RESTRICT y = y_;
162    pdl_trigger();   // PDL (pdl.hpp): the projection after this one may start loading its weights
163    pdl_wait();
164    const int i = int(blockIdx.x) * QUANT_THREADS + int(threadIdx.x);
165    if (i >= n_in) return; // n_in is a multiple of 32: only whole warps return.
166    const float xi = x[i];
167    const float amax = warp_max(fabsf(xi));
168    const float sum = warp_sum(xi);
169    const float d = q8_1_finite(amax / 127.0f);   // #606: q8_1_finite.hpp - the same bits for every finite block
170    const int8_t q = q8_1_quant(xi, d, amax);
171    y[i / Q8K].qs[i % Q8K] = q;
172    if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum);
173}
174
175__launch_bounds__(QUANT_THREADS, 1)
176__global__ void native_swiglu_quantize_q8_1_kernel(const float* __restrict__ gate,
177                                                   const float* __restrict__ up,
178                                                   Q81Block* __restrict__ y, int n_in) {
179    const int i = int(blockIdx.x) * QUANT_THREADS + int(threadIdx.x);
180    if (i >= n_in) return; // n_in is a multiple of 32: only whole warps return.
181    const float gi = gate[i];
182    const float xi = __fmul_rn(__fdividef(gi, __fadd_rn(1.0f, __expf(-gi))), up[i]);
183    const float amax = warp_max(fabsf(xi));
184    const float sum = warp_sum(xi);
185    const float d = q8_1_finite(amax / 127.0f);   // #606, as native_quantize_q8_1_kernel: finite blocks bit for bit
186    const int8_t q = q8_1_quant(xi, d, amax);
187    y[i / Q8K].qs[i % Q8K] = q;
188    if (i % Q8K == 0) y[i / Q8K].ds = q8_1_ds(d, sum);
189}
190
191// Exact pinned vec_dot_q5_K_q8_1_impl_vmmq expression and integer dot order.
192__device__ __forceinline__ float q5_q8_dot_impl(
193    const int* __restrict__ vl, const int* __restrict__ vh, const int* __restrict__ u,
194    const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, const half2& dm5,
195    const float* __restrict__ d8) {
196    float sumf_d = 0.0f;
197    float sumf_m = 0.0f;
198#pragma unroll
199    for (int i = 0; i < 2; ++i) {
200        const int vl0i = (vl[0] >> (4 * i)) & 0x0f0f0f0f;
201        const int vl1i = (vl[1] >> (4 * i)) & 0x0f0f0f0f;
202        const int vh0i = ((vh[0] >> i) << 4) & 0x10101010;
203        const int vh1i = ((vh[1] >> i) << 4) & 0x10101010;
204        const int v0i = vl0i | vh0i;
205        const int v1i = vl1i | vh1i;
206        const int dot1 = STRATA_DP4A(v0i, u[2 * i], STRATA_DP4A(v1i, u[2 * i + 1], 0));
207        const int dot2 = STRATA_DP4A(0x01010101, u[2 * i], STRATA_DP4A(0x01010101, u[2 * i + 1], 0));
208        sumf_d += d8[i] * (dot1 * sc[i]);
209        sumf_m += d8[i] * (dot2 * m[i]);
210    }
211    const float2 dm5f = __half22float2(dm5);
212    return dm5f.x * sumf_d - dm5f.y * sumf_m;
213}
214
215__device__ __forceinline__ float q5_q8_dot(const Q5KBlock* __restrict__ bq5,
216                                          const Q81Block* __restrict__ bq8, int iqs) {
217    int vl[2];
218    int vh[2];
219    int u[4];
220    float d8[2];
221    const int bq8_offset = 2 * ((iqs / 2) / 4);
222    const int* ql = reinterpret_cast<const int*>(bq5->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
223    const int* qh = reinterpret_cast<const int*>(bq5->qh + 4 * ((iqs / 2) % 4));
224    vl[0] = ql[0];
225    vl[1] = ql[4];
226    vh[0] = qh[0] >> bq8_offset;
227    vh[1] = qh[4] >> bq8_offset;
228
229    const uint16_t* scales = reinterpret_cast<const uint16_t*>(bq5->scales);
230    const int j = bq8_offset / 2;
231    const int jm = j & 1;
232    const uint32_t s0 = scales[jm];
233    const uint32_t s2 = scales[jm + 2];
234    const uint32_t s4 = scales[jm + 4];
235    const uint32_t hi = uint32_t(-int32_t(j >= 2));
236    uint16_t aux[2];
237    aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) |
238                     ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
239    aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) |
240                     ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
241    const uint8_t* sc = reinterpret_cast<const uint8_t*>(aux);
242    const uint8_t* m = sc + 2;
243#pragma unroll
244    for (int i = 0; i < 2; ++i) {
245        const Q81Block* bq8i = bq8 + bq8_offset + i;
246        d8[i] = __low2float(bq8i->ds);
247        const int* q8 = reinterpret_cast<const int*>(bq8i->qs) + ((iqs / 2) % 4);
248        u[2 * i] = q8[0];
249        u[2 * i + 1] = q8[4];
250    }
251    return q5_q8_dot_impl(vl, vh, u, sc, m, bq5->dm, d8);
252}
253
254// The generic ncols=1 oracle uses 4 warps and 1 row (or 4 rows for small K),
255// eight weight blocks per K iteration, warp-ascending shared sum, then XOR tree.
256template<bool SmallK>
257__launch_bounds__(WARPS * WARP, 1)
258__global__ void native_q5_k_mmvq_kernel(const Q5KBlock* __restrict__ w,
259                                        const Q81Block* __restrict__ x,
260                                        float* __restrict__ y, int n_in, int n_out) {
261    constexpr int ROWS = SmallK ? WARPS : 1;
262    constexpr int BLOCKS_PER_ITER = VDR * WARPS * WARP / QI;
263    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
264    const int row0 = ROWS * int(blockIdx.x);
265    const int blocks_per_row = n_in / QK;
266    float tmp[ROWS] = {};
267    for (int kbx = tid / (QI / VDR); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
268        const int kby = kbx * (QK / Q8K);
269        const int kqs = VDR * (tid % (QI / VDR));
270#pragma unroll
271        for (int i = 0; i < ROWS; ++i) {
272            // The source assumes allocator padding for partial row groups. This
273            // guard preserves every valid row's math without an out-of-bounds read.
274            if (row0 + i < n_out) {
275                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
276                tmp[i] += q5_q8_dot(w + block, x + kby, kqs);
277            }
278        }
279    }
280    __shared__ float partial[WARPS - 1][ROWS][WARP];
281    if (threadIdx.y > 0) {
282#pragma unroll
283        for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i];
284    }
285    __syncthreads();
286    if (threadIdx.y > 0) return;
287#pragma unroll
288    for (int i = 0; i < ROWS; ++i) {
289#pragma unroll
290        for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x];
291        tmp[i] = warp_sum(tmp[i]);
292        if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i];
293    }
294}
295
296// Exact pinned vec_dot_q2_0_q8_1: each thread handles one 32-element chunk.
297// The weight block is only 2-byte aligned, so qs is intentionally loaded as
298// int16_t, unlike the naturally 4-byte aligned activation codes.
299__device__ __forceinline__ float q2_q8_dot(const Q20Block* __restrict__ w,
300                                          const Q81Block* __restrict__ x, int iqs) {
301    const float d2 = w->d;
302    const int16_t* qs = reinterpret_cast<const int16_t*>(w->qs) + iqs * 4;
303    const Q81Block* chunk = x + iqs;
304    const int* q8 = reinterpret_cast<const int*>(chunk->qs);
305    int sumi = 0;
306#pragma unroll
307    for (int j = 0; j < 4; ++j) {
308        const int q = qs[j];
309        const int u = q8[j * 2];
310        const int v = q8[j * 2 + 1];
311        const int qe = __byte_perm(0x020100ff, 0x020100ff, q >> 0);
312        const int qo = __byte_perm(0x020100ff, 0x020100ff, q >> 2);
313        const int qx = __byte_perm(qe, qo, 0x5140);
314        const int qy = __byte_perm(qe, qo, 0x7362);
315        sumi = STRATA_DP4A(u, qx, sumi);
316        sumi = STRATA_DP4A(v, qy, sumi);
317    }
318    const float d8 = __low2float(chunk->ds);
319    return d2 * d8 * sumi;
320}
321
322// Q2_0 generic MMVQ: QK=64, QI=2, VDR=1, 64 blocks per iteration.
323// Preserve the same outer accumulation and cross-warp reduction as the oracle.
324template<bool SmallK>
325__launch_bounds__(WARPS * WARP, 1)
326__global__ void native_q2_0_mmvq_kernel(const Q20Block* __restrict__ w,
327                                        const Q81Block* __restrict__ x,
328                                        float* __restrict__ y, int n_in, int n_out) {
329    constexpr int ROWS = SmallK ? WARPS : 1;
330    constexpr int BLOCKS_PER_ITER = WARPS * WARP / 2;
331    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
332    const int row0 = ROWS * int(blockIdx.x);
333    const int blocks_per_row = n_in / 64;
334    float tmp[ROWS] = {};
335    for (int kbx = tid / 2; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
336        const int kby = kbx * 2;
337        const int kqs = tid % 2;
338#pragma unroll
339        for (int i = 0; i < ROWS; ++i) {
340            if (row0 + i < n_out) {
341                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
342                tmp[i] += q2_q8_dot(w + block, x + kby, kqs);
343            }
344        }
345    }
346    __shared__ float partial[WARPS - 1][ROWS][WARP];
347    if (threadIdx.y > 0) {
348#pragma unroll
349        for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i];
350    }
351    __syncthreads();
352    if (threadIdx.y > 0) return;
353#pragma unroll
354    for (int i = 0; i < ROWS; ++i) {
355#pragma unroll
356        for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x];
357        tmp[i] = warp_sum(tmp[i]);
358        if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i];
359    }
360}
361
362// Q3_K's 110-byte stride gives alternate blocks only two-byte alignment.
363// Preserve the pinned helper's pair of 16-bit loads and little-endian combine.
364__device__ __forceinline__ int load_int_b2(const void* ptr, int i32) {
365    const auto* x = static_cast<const uint16_t*>(ptr);
366    int value = x[2 * i32] << 0;
367    value |= x[2 * i32 + 1] << 16;
368    return value;
369}
370
371__device__ __forceinline__ float q3_q8_dot_impl(int vl, int vh, const int* __restrict__ u,
372                                              const uint8_t* __restrict__ scales,
373                                              int scale_offset, float d3,
374                                              const float* __restrict__ d8) {
375    float sumf = 0.0f;
376#pragma unroll
377    for (int i = 0; i < 4; ++i) {
378        const int isc = scale_offset + 2 * i;
379        const int isc_low = isc % 8;
380        const int sc_shift_low = 4 * (isc / 8);
381        const int sc_low = (scales[isc_low] >> sc_shift_low) & 0xf;
382        const int isc_high = isc % 4;
383        const int sc_shift_high = 2 * (isc / 4);
384        const int sc_high = ((scales[8 + isc_high] >> sc_shift_high) & 3) << 4;
385        const int sc = (sc_low | sc_high) - 32;
386        const int vil = (vl >> (2 * i)) & 0x03030303;
387        const int vih = ((vh >> i) << 2) & 0x04040404;
388        const int vi = __vsubss4(vil, vih);
389        sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);
390    }
391    return d3 * sumf;
392}
393
394__device__ __forceinline__ float q3_q8_dot(const Q3KBlock* __restrict__ w,
395                                          const Q81Block* __restrict__ x, int iqs) {
396    const int bq8_offset = 4 * (iqs / 8);
397    const int scale_offset = iqs - iqs % 8 + (iqs % 8) / 4;
398    const float d = w->d;
399    const int vl = load_int_b2(w->qs, iqs);
400    const int vh = ~load_int_b2(w->hmask, iqs % 8) >> bq8_offset;
401    int u[4];
402    float d8[4];
403#pragma unroll
404    for (int i = 0; i < 4; ++i) {
405        u[i] = reinterpret_cast<const int*>(x[bq8_offset + i].qs)[iqs % 8];
406        d8[i] = __low2float(x[bq8_offset + i].ds);
407    }
408    return q3_q8_dot_impl(vl, vh, u, w->scales, scale_offset, d, d8);
409}
410
411// Q3_K generic MMVQ: QK=256, QI=16, VDR=1, eight blocks per iteration.
412template<bool SmallK>
413__launch_bounds__(WARPS * WARP, 1)
414__global__ void native_q3_k_mmvq_kernel(const Q3KBlock* __restrict__ w,
415                                        const Q81Block* __restrict__ x,
416                                        float* __restrict__ y, int n_in, int n_out) {
417    constexpr int ROWS = SmallK ? WARPS : 1;
418    constexpr int BLOCKS_PER_ITER = WARPS * WARP / 16;
419    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
420    const int row0 = ROWS * int(blockIdx.x);
421    const int blocks_per_row = n_in / 256;
422    float tmp[ROWS] = {};
423    for (int kbx = tid / 16; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
424        const int kby = kbx * 8;
425        const int kqs = tid % 16;
426#pragma unroll
427        for (int i = 0; i < ROWS; ++i) {
428            if (row0 + i < n_out) {
429                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
430                tmp[i] += q3_q8_dot(w + block, x + kby, kqs);
431            }
432        }
433    }
434    __shared__ float partial[WARPS - 1][ROWS][WARP];
435    if (threadIdx.y > 0) {
436#pragma unroll
437        for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i];
438    }
439    __syncthreads();
440    if (threadIdx.y > 0) return;
441#pragma unroll
442    for (int i = 0; i < ROWS; ++i) {
443#pragma unroll
444        for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x];
445        tmp[i] = warp_sum(tmp[i]);
446        if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i];
447    }
448}
449
450// The pinned nonlinear IQ4 codebook and its CUDA two-stage byte lookup. The
451// explicit alignment satisfies the four 32-bit table loads; values are unchanged.
452__device__ __align__(4) int8_t iq4nl_values[16] = {
453    -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113
454};
455
456__device__ __forceinline__ int2 iq4_table_lookup(int q4) {
457#if defined(STRATA_HIP_GFX906)
458    // AMD: llama.cpp's HIP lookup (see iq_kernels.cu get_int_from_table_16): 4 v_perm_b32 per 8 values
459    const uint32_t* v32 = reinterpret_cast<const uint32_t*>(iq4nl_values);
460    const uint32_t q_even = (uint32_t) q4, q_odd = (uint32_t) q4 >> 4;
461    const uint32_t el = __builtin_amdgcn_perm(v32[1], v32[0], q_even & 0x07070707u);
462    const uint32_t ol = __builtin_amdgcn_perm(v32[1], v32[0], q_odd & 0x07070707u);
463    const uint32_t eh = __builtin_amdgcn_perm(v32[3], v32[2], q_even & 0x07070707u);
464    const uint32_t oh = __builtin_amdgcn_perm(v32[3], v32[2], q_odd & 0x07070707u);
465    return make_int2((int) __builtin_amdgcn_perm(eh, el, 0x03020100u | ((q_even & 0x08080808u) >> 1)),
466                     (int) __builtin_amdgcn_perm(oh, ol, 0x03020100u | ((q_odd & 0x08080808u) >> 1)));
467#else
468    const uint32_t* table32 = reinterpret_cast<const uint32_t*>(iq4nl_values);
469    uint32_t tmp[2];
470    const uint32_t low_high_selection_indices = 0x32103210 | ((q4 & 0x88888888) >> 1);
471#pragma unroll
472    for (uint32_t i = 0; i < 2; ++i) {
473        const uint32_t shift = 16 * i;
474        const uint32_t low = __byte_perm(table32[0], table32[1], q4 >> shift);
475        const uint32_t high = __byte_perm(table32[2], table32[3], q4 >> shift);
476        tmp[i] = __byte_perm(low, high, low_high_selection_indices >> shift);
477    }
478    return make_int2(__byte_perm(tmp[0], tmp[1], 0x6420), __byte_perm(tmp[0], tmp[1], 0x7531));
479#endif
480}
481
482// Exact pinned vec_dot_iq4_xs_q8_1: a lane consumes one 32-element subblock,
483// computes integer dot products, applies signed scale in the integer domain,
484// then multiplies the two half scales and integer sum in the original order.
485__device__ __forceinline__ float iq4_xs_q8_dot(const IQ4XSBlock* __restrict__ w,
486                                              const Q81Block* __restrict__ x, int iqs) {
487    int sumi = 0;
488#pragma unroll
489    for (int j = 0; j < 4; ++j) {
490        const int aux_q4 = reinterpret_cast<const int*>(w->qs)[iqs + j];
491        const int2 v = iq4_table_lookup(aux_q4);
492        const int u0 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j];
493        const int u1 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j + 4];
494        sumi = STRATA_DP4A(v.x, u0, sumi);
495        sumi = STRATA_DP4A(v.y, u1, sumi);
496    }
497    const int ls = ((w->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0f) |
498                   (((w->scales_h >> (iqs / 2)) & 0x03) << 4);
499    sumi *= ls - 32;
500    const float d = __half2float(w->d) * __low2float(x[iqs / 4].ds);
501    return d * sumi;
502}
503
504// IQ4_XS generic MMVQ: QK=256, QI=32, VDR=4,16 blocks per iteration.
505template<bool SmallK>
506__launch_bounds__(WARPS * WARP, 1)
507__global__ void native_iq4_xs_mmvq_kernel(const IQ4XSBlock* __restrict__ w,
508                                         const Q81Block* __restrict__ x,
509                                         float* __restrict__ y, int n_in, int n_out) {
510    constexpr int ROWS = SmallK ? WARPS : 1;
511    constexpr int BLOCKS_PER_ITER = 4 * WARPS * WARP / 32;
512    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
513    const int row0 = ROWS * int(blockIdx.x);
514    const int blocks_per_row = n_in / 256;
515    float tmp[ROWS] = {};
516    for (int kbx = tid / 8; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
517        const int kby = kbx * 8;
518        const int kqs = 4 * (tid % 8);
519#pragma unroll
520        for (int i = 0; i < ROWS; ++i) {
521            if (row0 + i < n_out) {
522                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
523                tmp[i] += iq4_xs_q8_dot(w + block, x + kby, kqs);
524            }
525        }
526    }
527    __shared__ float partial[WARPS - 1][ROWS][WARP];
528    if (threadIdx.y > 0) {
529#pragma unroll
530        for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i];
531    }
532    __syncthreads();
533    if (threadIdx.y > 0) return;
534#pragma unroll
535    for (int i = 0; i < ROWS; ++i) {
536#pragma unroll
537        for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x];
538        tmp[i] = warp_sum(tmp[i]);
539        if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i];
540    }
541}
542
543// Exact pinned vec_dot_q4_K_q8_1_impl_vmmq expression and integer dot order.
544__device__ __forceinline__ float q4_q8_dot_impl(
545    const int* __restrict__ v, const int* __restrict__ u,
546    const uint8_t* __restrict__ sc, const uint8_t* __restrict__ m, const half2& dm4,
547    const float* __restrict__ d8) {
548    float sumf_d = 0.0f;
549    float sumf_m = 0.0f;
550#pragma unroll
551    for (int i = 0; i < 2; ++i) {
552        const int v0i = (v[0] >> (4 * i)) & 0x0f0f0f0f;
553        const int v1i = (v[1] >> (4 * i)) & 0x0f0f0f0f;
554        const int dot1 = STRATA_DP4A(v1i, u[2 * i + 1], STRATA_DP4A(v0i, u[2 * i], 0));
555        const int dot2 = STRATA_DP4A(0x01010101, u[2 * i + 1], STRATA_DP4A(0x01010101, u[2 * i], 0));
556        sumf_d += d8[i] * (dot1 * sc[i]);
557        sumf_m += d8[i] * (dot2 * m[i]);
558    }
559    const float2 dm4f = __half22float2(dm4);
560    return dm4f.x * sumf_d - dm4f.y * sumf_m;
561}
562
563__device__ __forceinline__ float q4_q8_dot(const Q4KBlock* __restrict__ bq4,
564                                          const Q81Block* __restrict__ bq8, int iqs) {
565    int v[2];
566    int u[4];
567    float d8[2];
568    const int bq8_offset = 2 * ((iqs / 2) / 4);
569    const int* ql = reinterpret_cast<const int*>(bq4->qs + 16 * bq8_offset + 4 * ((iqs / 2) % 4));
570    v[0] = ql[0];
571    v[1] = ql[4];
572
573    const uint16_t* scales = reinterpret_cast<const uint16_t*>(bq4->scales);
574    const int j = bq8_offset / 2;
575    const int jm = j & 1;
576    const uint32_t s0 = scales[jm];
577    const uint32_t s2 = scales[jm + 2];
578    const uint32_t s4 = scales[jm + 4];
579    const uint32_t hi = uint32_t(-int32_t(j >= 2));
580    uint16_t aux[2];
581    aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) |
582                     ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
583    aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) |
584                     ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
585    const uint8_t* sc = reinterpret_cast<const uint8_t*>(aux);
586    const uint8_t* m = sc + 2;
587#pragma unroll
588    for (int i = 0; i < 2; ++i) {
589        const Q81Block* bq8i = bq8 + bq8_offset + i;
590        d8[i] = __low2float(bq8i->ds);
591        const int* q8 = reinterpret_cast<const int*>(bq8i->qs) + ((iqs / 2) % 4);
592        u[2 * i] = q8[0];
593        u[2 * i + 1] = q8[4];
594    }
595    return q4_q8_dot_impl(v, u, sc, m, bq4->dm, d8);
596}
597
598// The generic ncols=1 oracle uses 4 warps and 1 row (or 4 rows for small K),
599// eight weight blocks per K iteration, warp-ascending shared sum, then XOR tree.
600template<bool SmallK>
601__launch_bounds__(WARPS * WARP, 1)
602__global__ void native_q4_k_mmvq_kernel(const Q4KBlock* __restrict__ w,
603                                        const Q81Block* __restrict__ x,
604                                        float* __restrict__ y, int n_in, int n_out) {
605    constexpr int ROWS = SmallK ? WARPS : 1;
606    constexpr int BLOCKS_PER_ITER = VDR * WARPS * WARP / QI;
607    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
608    const int row0 = ROWS * int(blockIdx.x);
609    const int blocks_per_row = n_in / QK;
610    float tmp[ROWS] = {};
611    for (int kbx = tid / (QI / VDR); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
612        const int kby = kbx * (QK / Q8K);
613        const int kqs = VDR * (tid % (QI / VDR));
614#pragma unroll
615        for (int i = 0; i < ROWS; ++i) {
616            // The source assumes allocator padding for partial row groups. This
617            // guard preserves every valid row's math without an out-of-bounds read.
618            if (row0 + i < n_out) {
619                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
620                tmp[i] += q4_q8_dot(w + block, x + kby, kqs);
621            }
622        }
623    }
624    __shared__ float partial[WARPS - 1][ROWS][WARP];
625    if (threadIdx.y > 0) {
626#pragma unroll
627        for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i];
628    }
629    __syncthreads();
630    if (threadIdx.y > 0) return;
631#pragma unroll
632    for (int i = 0; i < ROWS; ++i) {
633#pragma unroll
634        for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x];
635        tmp[i] = warp_sum(tmp[i]);
636        if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i];
637    }
638}
639
640// Exact pinned vec_dot_q6_K_q8_1: keep signed per-16-element scales,
641// signed-byte subtraction, DP4A order, and the float accumulation sequence.
642__device__ __forceinline__ float q6_q8_dot_impl(int vl, int vh, const int* __restrict__ u,
643                                              const int8_t* __restrict__ scales,
644                                              float d, const float* __restrict__ d8) {
645    float sumf = 0.0f;
646#pragma unroll
647    for (int i = 0; i < 2; ++i) {
648        const int sc = scales[4 * i];
649        const int vil = (vl >> (4 * i)) & 0x0f0f0f0f;
650        const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;
651        const int vi = __vsubss4(vil | vih, 0x20202020);
652        sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);
653    }
654    return d * sumf;
655}
656#if !defined(__HIPCC__)   // CUDA only: the native_mmvq_il_pf_kernel family below (itself CUDA only) is the only user
657// q6_q8_dot_impl with the two scales already in registers (the interleaved kernels' hoisted loads, P1): the same
658// expression in the same order
659__device__ __forceinline__ float q6_q8_dot_sc(int vl, int vh, const int* __restrict__ u, int sc0, int sc1, float d,
660                                            const float* __restrict__ d8) {
661    float sumf = 0.0f;
662    const int scs[2] = {sc0, sc1};
663#pragma unroll
664    for (int i = 0; i < 2; ++i) {
665        const int sc = scs[i];
666        const int vil = (vl >> (4 * i)) & 0x0f0f0f0f;
667        const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;
668        const int vi = __vsubss4(vil | vih, 0x20202020);
669        sumf += d8[i] * (STRATA_DP4A(vi, u[i], 0) * sc);
670    }
671    return d * sumf;
672}
673
674// P1: loads the compiler may not sink into a later branch (it moved the Q6_K scale and d loads of the hoisted group
675// into the dot sections, where each one is a dependent L1 round trip); the same ld.global.nc the __restrict__ loads use
676__device__ __forceinline__ int ldg_nc_u16(const void* p) { unsigned v; asm volatile("ld.global.nc.u16 %0, [%1];" : "=r"(v) : "l"(p)); return int(v); }
677__device__ __forceinline__ int ldg_nc_s8(const void* p) { int v; asm volatile("ld.global.nc.s8 %0, [%1];" : "=r"(v) : "l"(p)); return v; }
678__device__ __forceinline__ int ldg_nc_u8(const void* p) { unsigned v; asm volatile("ld.global.nc.u8 %0, [%1];" : "=r"(v) : "l"(p)); return int(v); }
679__device__ __forceinline__ int ldg_nc_s32(const void* p) { int v; asm volatile("ld.global.nc.s32 %0, [%1];" : "=r"(v) : "l"(p)); return v; }
680__device__ __forceinline__ int ldg_nc_b2(const void* p, int i32) {   // load_int_b2 pinned: two u16, little-endian
681    const auto* x = static_cast<const uint16_t*>(p) + 2 * i32;
682    return ldg_nc_u16(x) | (ldg_nc_u16(x + 1) << 16);
683}
684// P1: base + k * stride as one IMAD.WIDE.U32 (an asm so the front end does not share k * stride between pointers and
685// turn each into a 64-bit add pair)
686__device__ __forceinline__ const void* madw(const void* base, int k, int stride) {
687    const void* r;
688    asm("mad.wide.u32 %0, %1, %2, %3;" : "=l"(r) : "r"(k), "r"(stride), "l"(base));
689    return r;
690}
691// P2: (float) p for |p| < 2^22 as an add on the FMA pipe instead of the quarter-rate I2F: p + 1.5 * 2^23
692// as float bits is exactly 1.5 * 2^23 + p (unit ulp), and the subtraction is exact (Sterbenz), so the value is the
693// conversion's, +0 included
694__device__ __forceinline__ float i2f_small(int p_plus_magic) { return __int_as_float(p_plus_magic) - 12582912.0f; }
695constexpr int kI2fMagic = 0x4B400000;
696// P2: __vsubss4(x, 0x20202020) for bytes of x in [0, 63] (Q6_K's codes, so nothing saturates): x | 0x80 is x + 0x80 per
697// byte, minus 0x20 never borrows (0x60..0x9f), and the xor takes the 0x80 back: the same int8 bytes, 2 instructions
698// instead of ptxas's 8 for the saturating subtract sm_80 lacks
699__device__ __forceinline__ int sub32_bytes(int x) { return (x + 0x60606060) ^ 0x80808080; }
700// q6_q8_dot_sc with P2's integer forms: the dp4a inputs are the same 32-bit values, (dp * sc) the same int, and
701// i2f_small its exact float (|dp * sc| <= 4 * 32 * 127 * 128 = 2.1M < 2^22), so every FFMA sees the bits q6_q8_dot_impl's does
702__device__ __forceinline__ float q6_q8_dot_fast(int vl, int vh, const int* __restrict__ u, int sc0, int sc1, float d,
703                                              const float* __restrict__ d8) {
704    float sumf = 0.0f;
705    const int scs[2] = {sc0, sc1};
706#pragma unroll
707    for (int i = 0; i < 2; ++i) {
708        const int vil = (vl >> (4 * i)) & 0x0f0f0f0f;
709        const int vih = ((vh >> (4 * i)) << 4) & 0x30303030;
710        const int vi = sub32_bytes(vil | vih);
711        sumf += d8[i] * i2f_small(STRATA_DP4A(vi, u[i], 0) * scs[i] + kI2fMagic);
712    }
713    return d * sumf;
714}
715#endif  // !__HIPCC__
716
717__device__ __forceinline__ float q6_q8_dot(const Q6KBlock* __restrict__ w,
718                                          const Q81Block* __restrict__ x, int iqs) {
719    const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8;
720    const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4;
721    const int vh_shift = 2 * ((iqs % 16) / 8);
722    const int vl = load_int_b2(w->ql, iqs);
723    const int vh = load_int_b2(w->qh, 8 * (iqs / 16) + iqs % 8) >> vh_shift;
724    int u[2];
725    float d8[2];
726#pragma unroll
727    for (int i = 0; i < 2; ++i) {
728        u[i] = reinterpret_cast<const int*>(x[bq8_offset + 2 * i].qs)[iqs % 8];
729        d8[i] = __low2float(x[bq8_offset + 2 * i].ds);
730    }
731    return q6_q8_dot_impl(vl, vh, u, w->scales + scale_offset, w->d, d8);
732}
733
734// Q6_K generic MMVQ: QK=256, QI=32, VDR=1, four blocks per iteration.
735template<bool SmallK>
736__launch_bounds__(WARPS * WARP, 1)
737__global__ void native_q6_k_mmvq_kernel(const Q6KBlock* __restrict__ w,
738                                        const Q81Block* __restrict__ x,
739                                        float* __restrict__ y, int n_in, int n_out) {
740    constexpr int ROWS = SmallK ? WARPS : 1;
741    constexpr int BLOCKS_PER_ITER = WARPS * WARP / 32;
742    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
743    const int row0 = ROWS * int(blockIdx.x);
744    const int blocks_per_row = n_in / 256;
745    float tmp[ROWS] = {};
746    for (int kbx = tid / 32; kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
747        const int kby = kbx * 8;
748        const int kqs = tid % 32;
749#pragma unroll
750        for (int i = 0; i < ROWS; ++i) {
751            if (row0 + i < n_out) {
752                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
753                tmp[i] += q6_q8_dot(w + block, x + kby, kqs);
754            }
755        }
756    }
757    __shared__ float partial[WARPS - 1][ROWS][WARP];
758    if (threadIdx.y > 0) {
759#pragma unroll
760        for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i];
761    }
762    __syncthreads();
763    if (threadIdx.y > 0) return;
764#pragma unroll
765    for (int i = 0; i < ROWS; ++i) {
766#pragma unroll
767        for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x];
768        tmp[i] = warp_sum(tmp[i]);
769        if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i];
770    }
771}
772
773// The four 32-element formats use native two-byte loads and VDR=2. The affine
774// Q4_0/Q5_0 correction consumes the original-input sum stored in Q8_1, exactly
775// as the pinned CUDA dot does; a signed-integer code substitution would differ.
776__device__ __forceinline__ float small_q8_dot(const Q40Block* __restrict__ w,
777                                             const Q81Block* __restrict__ x, int iqs) {
778    int sumi = 0;
779#pragma unroll
780    for (int i = 0; i < 2; ++i) {
781        const int v = load_int_b2(w->qs, iqs + i);
782        const int vi0 = (v >> 0) & 0x0f0f0f0f;
783        const int vi1 = (v >> 4) & 0x0f0f0f0f;
784        sumi = STRATA_DP4A(vi0, reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
785        sumi = STRATA_DP4A(vi1, reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
786    }
787    const float2 ds = __half22float2(x->ds);
788    const float d = w->d;
789    return d * (sumi * ds.x - 4 * ds.y);
790}
791
792__device__ __forceinline__ float small_q8_dot(const Q50Block* __restrict__ w,
793                                             const Q81Block* __restrict__ x, int iqs) {
794    int sumi = 0;
795#pragma unroll
796    for (int i = 0; i < 2; ++i) {
797        const int vl = load_int_b2(w->qs, iqs + i);
798        const int vh = load_int_b2(w->qh, 0) >> (4 * (iqs + i));
799        int vi0 = (vl >> 0) & 0x0f0f0f0f;
800        vi0 |= (vh << 4) & 0x00000010;
801        vi0 |= (vh << 11) & 0x00001000;
802        vi0 |= (vh << 18) & 0x00100000;
803        vi0 |= (vh << 25) & 0x10000000;
804        sumi = STRATA_DP4A(vi0, reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
805        int vi1 = (vl >> 4) & 0x0f0f0f0f;
806        vi1 |= (vh >> 12) & 0x00000010;
807        vi1 |= (vh >> 5) & 0x00001000;
808        vi1 |= (vh << 2) & 0x00100000;
809        vi1 |= (vh << 9) & 0x10000000;
810        sumi = STRATA_DP4A(vi1, reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
811    }
812    const float2 ds = __half22float2(x->ds);
813    const float d = w->d;
814    return d * (sumi * ds.x - 8 * ds.y);
815}
816
817__device__ __forceinline__ float small_q8_dot(const Q80Block* __restrict__ w,
818                                             const Q81Block* __restrict__ x, int iqs) {
819    int sumi = 0;
820#pragma unroll
821    for (int i = 0; i < 2; ++i) {
822        const int v = load_int_b2(w->qs, iqs + i);
823        const int u = reinterpret_cast<const int*>(x->qs)[iqs + i];
824        sumi = STRATA_DP4A(v, u, sumi);
825    }
826    const float d0 = w->d;
827    const float d1 = __low2float(x->ds);
828    return d0 * d1 * float(sumi);
829}
830
831__device__ __forceinline__ float small_q8_dot(const IQ4NLBlock* __restrict__ w,
832                                             const Q81Block* __restrict__ x, int iqs) {
833    const int* q8 = reinterpret_cast<const int*>(x->qs) + iqs;
834    int sumi = 0;
835#pragma unroll
836    for (int i = 0; i < 2; ++i) {
837        const int2 v = iq4_table_lookup(load_int_b2(w->qs, iqs + i));
838        sumi = STRATA_DP4A(v.x, q8[i], sumi);
839        sumi = STRATA_DP4A(v.y, q8[i + 4], sumi);
840    }
841    const float d = __half2float(w->d) * __low2float(x->ds);
842    return d * sumi;
843}
844
845// QI=4 for Q4_0/Q5_0/IQ4_NL and QI=8 for Q8_0. With VDR=2 this preserves
846// the pinned 64/32-block iteration and 2048/1024-element small-K thresholds.
847template<typename Weight, int Qi, bool SmallK>
848__launch_bounds__(WARPS * WARP, 1)
849__global__ void native_small_mmvq_kernel(const Weight* __restrict__ w,
850                                         const Q81Block* __restrict__ x,
851                                         float* __restrict__ y, int n_in, int n_out) {
852    constexpr int ROWS = SmallK ? WARPS : 1;
853    constexpr int BLOCKS_PER_ITER = 2 * WARPS * WARP / Qi;
854    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
855    const int row0 = ROWS * int(blockIdx.x);
856    const int blocks_per_row = n_in / 32;
857    float tmp[ROWS] = {};
858    for (int kbx = tid / (Qi / 2); kbx < blocks_per_row; kbx += BLOCKS_PER_ITER) {
859        const int kqs = 2 * (tid % (Qi / 2));
860#pragma unroll
861        for (int i = 0; i < ROWS; ++i) {
862            if (row0 + i < n_out) {
863                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
864                tmp[i] += small_q8_dot(w + block, x + kbx, kqs);
865            }
866        }
867    }
868    __shared__ float partial[WARPS - 1][ROWS][WARP];
869    if (threadIdx.y > 0) {
870#pragma unroll
871        for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][i][threadIdx.x] = tmp[i];
872    }
873    __syncthreads();
874    if (threadIdx.y > 0) return;
875#pragma unroll
876    for (int i = 0; i < ROWS; ++i) {
877#pragma unroll
878        for (int l = 0; l < WARPS - 1; ++l) tmp[i] += partial[l][i][threadIdx.x];
879        tmp[i] = warp_sum(tmp[i]);
880        if (threadIdx.x == i && row0 + i < n_out) y[row0 + i] = tmp[i];
881    }
882}
883
884// ============================ plan v0.3 P3: ncols = 2..8 (speculative verify, small batches) ============================
885//
886// One generic kernel for every format, parameterized by the format's iteration traits below, which are
887// transcribed from the ncols = 1 kernels above (same thread-to-block mapping, same blocks per iteration, same
888// small-K rule). Column j reads activation blocks x + j * (n_in / 32) and writes y + j * n_out. Each (column,
889// row) value is accumulated over kbx in the same order, summed across warps in the same order and reduced with
890// the same warp tree as the ncols = 1 kernel, so every column is BITWISE equal to a single-column call on that
891// column (checked by bench/micro/native_mmvq_multi.cpp). The ncols = 1 kernels are untouched.
892// Columns one launch takes: 8, the 0.2.7 limit, or 16 where windows are wide (window_limits.hpp: the cases 9..16 are
893// compiled only then, so an engine built with STRATA_WINDOW_MAX_T=8 has exactly the kernels it had).  A window has one
894// column per row.  The wide launches read every weight once for all their columns; running 16 columns as two 8-column
895// passes (native_mmvq below does it for more than MAX_NCOLS) reads the dense weights twice and measured slower than 8 rows.
896constexpr int MAX_NCOLS = STRATA_VERIFY_MAX_T > 8 ? STRATA_VERIFY_MAX_T : 8;
897
898// Each format splits its dot product into `load` (everything that depends only on the weight block: codes,
899// unpacked scales, block scale) and `apply` (the activation loads and the original *_impl expression). `load` runs
900// once per (row, block) and `apply` once per column, so adding columns adds only activation work. `apply` calls
901// the same impl functions, in the same order, with the same values as the ncols = 1 dot, which is what keeps
902// every column bitwise equal to it.
903struct Q5KTraits {
904    using Block = Q5KBlock;
905    [[maybe_unused]] static constexpr int TYPE = 13;   // ggml type
906    static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI;
907    __device__ static int kqs(int tid) { return VDR * (tid % (QI / VDR)); }
908    struct W { int vl[2], vh[2]; uint16_t aux[2]; half2 dm; int bq8_offset; };
909    __device__ static W load(const Block* __restrict__ bq5, int iqs) {
910        W r;
911        r.bq8_offset = 2 * ((iqs / 2) / 4);
912        const int* ql = reinterpret_cast<const int*>(bq5->qs + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4));
913        const int* qh = reinterpret_cast<const int*>(bq5->qh + 4 * ((iqs / 2) % 4));
914        r.vl[0] = ql[0];
915        r.vl[1] = ql[4];
916        r.vh[0] = qh[0] >> r.bq8_offset;
917        r.vh[1] = qh[4] >> r.bq8_offset;
918        const uint16_t* scales = reinterpret_cast<const uint16_t*>(bq5->scales);
919        const int j = r.bq8_offset / 2;
920        const int jm = j & 1;
921        const uint32_t s0 = scales[jm];
922        const uint32_t s2 = scales[jm + 2];
923        const uint32_t s4 = scales[jm + 4];
924        const uint32_t hi = uint32_t(-int32_t(j >= 2));
925        r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
926        r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
927        r.dm = bq5->dm;
928        return r;
929    }
930    __device__ static float apply(const W& r, const Q81Block* __restrict__ bq8, int iqs) {
931        int u[4];
932        float d8[2];
933#pragma unroll
934        for (int i = 0; i < 2; ++i) {
935            const Q81Block* bq8i = bq8 + r.bq8_offset + i;
936            d8[i] = __low2float(bq8i->ds);
937            const int* q8 = reinterpret_cast<const int*>(bq8i->qs) + ((iqs / 2) % 4);
938            u[2 * i] = q8[0];
939            u[2 * i + 1] = q8[4];
940        }
941        const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux);
942        return q5_q8_dot_impl(r.vl, r.vh, u, sc, sc + 2, r.dm, d8);
943    }
944};
945struct Q4KTraits {
946    using Block = Q4KBlock;
947    [[maybe_unused]] static constexpr int TYPE = 12;   // ggml type
948    static constexpr int DIV = QK, T = QI / VDR, KBY = QK / Q8K, BPI = VDR * WARPS * WARP / QI;
949    __device__ static int kqs(int tid) { return VDR * (tid % (QI / VDR)); }
950    struct W { int v[2]; uint16_t aux[2]; half2 dm; int bq8_offset; };
951    __device__ static W load(const Block* __restrict__ bq4, int iqs) {
952        W r;
953        r.bq8_offset = 2 * ((iqs / 2) / 4);
954        const int* ql = reinterpret_cast<const int*>(bq4->qs + 16 * r.bq8_offset + 4 * ((iqs / 2) % 4));
955        r.v[0] = ql[0];
956        r.v[1] = ql[4];
957        const uint16_t* scales = reinterpret_cast<const uint16_t*>(bq4->scales);
958        const int j = r.bq8_offset / 2;
959        const int jm = j & 1;
960        const uint32_t s0 = scales[jm];
961        const uint32_t s2 = scales[jm + 2];
962        const uint32_t s4 = scales[jm + 4];
963        const uint32_t hi = uint32_t(-int32_t(j >= 2));
964        r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
965        r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
966        r.dm = bq4->dm;
967        return r;
968    }
969    __device__ static float apply(const W& r, const Q81Block* __restrict__ bq8, int iqs) {
970        int u[4];
971        float d8[2];
972#pragma unroll
973        for (int i = 0; i < 2; ++i) {
974            const Q81Block* bq8i = bq8 + r.bq8_offset + i;
975            d8[i] = __low2float(bq8i->ds);
976            const int* q8 = reinterpret_cast<const int*>(bq8i->qs) + ((iqs / 2) % 4);
977            u[2 * i] = q8[0];
978            u[2 * i + 1] = q8[4];
979        }
980        const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux);
981        return q4_q8_dot_impl(r.v, u, sc, sc + 2, r.dm, d8);
982    }
983};
984struct Q20Traits {
985    using Block = Q20Block;
986    static constexpr int DIV = 64, T = 2, KBY = 2, BPI = WARPS * WARP / 2;
987    __device__ static int kqs(int tid) { return tid % 2; }
988    struct W { int qx[4], qy[4]; float d2; };
989    __device__ static W load(const Block* __restrict__ w, int iqs) {
990        W r;
991        r.d2 = w->d;
992        const int16_t* qs = reinterpret_cast<const int16_t*>(w->qs) + iqs * 4;
993#pragma unroll
994        for (int j = 0; j < 4; ++j) {
995            const int q = qs[j];
996            const int qe = __byte_perm(0x020100ff, 0x020100ff, q >> 0);
997            const int qo = __byte_perm(0x020100ff, 0x020100ff, q >> 2);
998            r.qx[j] = __byte_perm(qe, qo, 0x5140);
999            r.qy[j] = __byte_perm(qe, qo, 0x7362);
1000        }
1001        return r;
1002    }
1003    __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1004        const Q81Block* chunk = x + iqs;
1005        const int* q8 = reinterpret_cast<const int*>(chunk->qs);
1006        int sumi = 0;
1007#pragma unroll
1008        for (int j = 0; j < 4; ++j) {
1009            sumi = STRATA_DP4A(q8[j * 2], r.qx[j], sumi);
1010            sumi = STRATA_DP4A(q8[j * 2 + 1], r.qy[j], sumi);
1011        }
1012        const float d8 = __low2float(chunk->ds);
1013        return r.d2 * d8 * sumi;
1014    }
1015};
1016struct Q3KTraits {
1017    using Block = Q3KBlock;
1018    [[maybe_unused]] static constexpr int TYPE = 11;   // ggml type
1019    static constexpr int DIV = 256, T = 16, KBY = 8, BPI = WARPS * WARP / 16;
1020    __device__ static int kqs(int tid) { return tid % 16; }
1021    struct W { int vl, vh; float d; const uint8_t* scales; int scale_offset, bq8_offset; };
1022    __device__ static W load(const Block* __restrict__ w, int iqs) {
1023        W r;
1024        r.bq8_offset = 4 * (iqs / 8);
1025        r.scale_offset = iqs - iqs % 8 + (iqs % 8) / 4;
1026        r.d = w->d;
1027        r.vl = load_int_b2(w->qs, iqs);
1028        r.vh = ~load_int_b2(w->hmask, iqs % 8) >> r.bq8_offset;
1029        r.scales = w->scales;
1030        return r;
1031    }
1032    __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1033        int u[4];
1034        float d8[4];
1035#pragma unroll
1036        for (int i = 0; i < 4; ++i) {
1037            u[i] = reinterpret_cast<const int*>(x[r.bq8_offset + i].qs)[iqs % 8];
1038            d8[i] = __low2float(x[r.bq8_offset + i].ds);
1039        }
1040        return q3_q8_dot_impl(r.vl, r.vh, u, r.scales, r.scale_offset, r.d, d8);
1041    }
1042};
1043struct Q6KTraits {
1044    using Block = Q6KBlock;
1045    [[maybe_unused]] static constexpr int TYPE = 14;   // ggml type
1046    static constexpr int DIV = 256, T = 32, KBY = 8, BPI = WARPS * WARP / 32;
1047    __device__ static int kqs(int tid) { return tid % 32; }
1048    struct W { int vl, vh; float d; const int8_t* scales; int bq8_offset; };
1049    __device__ static W load(const Block* __restrict__ w, int iqs) {
1050        W r;
1051        r.bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8;
1052        const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4;
1053        const int vh_shift = 2 * ((iqs % 16) / 8);
1054        r.vl = load_int_b2(w->ql, iqs);
1055        r.vh = load_int_b2(w->qh, 8 * (iqs / 16) + iqs % 8) >> vh_shift;
1056        r.scales = w->scales + scale_offset;
1057        r.d = w->d;
1058        return r;
1059    }
1060    __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1061        int u[2];
1062        float d8[2];
1063#pragma unroll
1064        for (int i = 0; i < 2; ++i) {
1065            u[i] = reinterpret_cast<const int*>(x[r.bq8_offset + 2 * i].qs)[iqs % 8];
1066            d8[i] = __low2float(x[r.bq8_offset + 2 * i].ds);
1067        }
1068        return q6_q8_dot_impl(r.vl, r.vh, u, r.scales, r.d, d8);
1069    }
1070};
1071struct IQ4XSTraits {
1072    using Block = IQ4XSBlock;
1073    [[maybe_unused]] static constexpr int TYPE = 23;   // ggml type
1074    static constexpr int DIV = 256, T = 8, KBY = 8, BPI = 4 * WARPS * WARP / 32;
1075    __device__ static int kqs(int tid) { return 4 * (tid % 8); }
1076    struct W { int2 v[4]; int ls; float dw; };
1077    __device__ static W load(const Block* __restrict__ w, int iqs) {
1078        W r;
1079#pragma unroll
1080        for (int j = 0; j < 4; ++j) r.v[j] = iq4_table_lookup(reinterpret_cast<const int*>(w->qs)[iqs + j]);
1081        r.ls = ((w->scales_l[iqs / 8] >> (iqs & 0x04)) & 0x0f) | (((w->scales_h >> (iqs / 2)) & 0x03) << 4);
1082        r.dw = __half2float(w->d);
1083        return r;
1084    }
1085    __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1086        int sumi = 0;
1087#pragma unroll
1088        for (int j = 0; j < 4; ++j) {
1089            const int u0 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j];
1090            const int u1 = reinterpret_cast<const int*>(x[iqs / 4].qs)[j + 4];
1091            sumi = STRATA_DP4A(r.v[j].x, u0, sumi);
1092            sumi = STRATA_DP4A(r.v[j].y, u1, sumi);
1093        }
1094        sumi *= r.ls - 32;
1095        const float d = r.dw * __low2float(x[iqs / 4].ds);
1096        return d * sumi;
1097    }
1098};
1099// The four 32-element formats: `load` decodes the two 32-bit weight chunks and block scale once per (row, block),
1100// and `apply` runs the exact same STRATA_DP4A and scale arithmetic per activation column as `small_q8_dot`.
1101template<typename Weight, int Qi>
1102struct SmallTraits;
1103
1104template<>
1105struct SmallTraits<Q40Block, 4> {
1106    using Block = Q40Block;
1107    static constexpr int DIV = 32, T = 2, KBY = 1, BPI = 2 * WARPS * WARP / 4;
1108    __device__ static int kqs(int tid) { return 2 * (tid % 2); }
1109    struct W { int vi0[2], vi1[2]; float d; };
1110    __device__ static W load(const Block* __restrict__ w, int iqs) {
1111        W r;
1112#pragma unroll
1113        for (int i = 0; i < 2; ++i) {
1114            const int v = load_int_b2(w->qs, iqs + i);
1115            r.vi0[i] = (v >> 0) & 0x0f0f0f0f;
1116            r.vi1[i] = (v >> 4) & 0x0f0f0f0f;
1117        }
1118        r.d = w->d;
1119        return r;
1120    }
1121    __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1122        int sumi = 0;
1123#pragma unroll
1124        for (int i = 0; i < 2; ++i) {
1125            sumi = STRATA_DP4A(r.vi0[i], reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
1126            sumi = STRATA_DP4A(r.vi1[i], reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
1127        }
1128        const float2 ds = __half22float2(x->ds);
1129        return r.d * (sumi * ds.x - 4 * ds.y);
1130    }
1131};
1132
1133template<>
1134struct SmallTraits<Q50Block, 4> {
1135    using Block = Q50Block;
1136    static constexpr int DIV = 32, T = 2, KBY = 1, BPI = 2 * WARPS * WARP / 4;
1137    __device__ static int kqs(int tid) { return 2 * (tid % 2); }
1138    struct W { int vi0[2], vi1[2]; float d; };
1139    __device__ static W load(const Block* __restrict__ w, int iqs) {
1140        W r;
1141        const int qh = load_int_b2(w->qh, 0);
1142#pragma unroll
1143        for (int i = 0; i < 2; ++i) {
1144            const int vl = load_int_b2(w->qs, iqs + i);
1145            const int vh = qh >> (4 * (iqs + i));
1146            int vi0 = (vl >> 0) & 0x0f0f0f0f;
1147            vi0 |= (vh << 4) & 0x00000010;
1148            vi0 |= (vh << 11) & 0x00001000;
1149            vi0 |= (vh << 18) & 0x00100000;
1150            vi0 |= (vh << 25) & 0x10000000;
1151            r.vi0[i] = vi0;
1152            int vi1 = (vl >> 4) & 0x0f0f0f0f;
1153            vi1 |= (vh >> 12) & 0x00000010;
1154            vi1 |= (vh >> 5) & 0x00001000;
1155            vi1 |= (vh << 2) & 0x00100000;
1156            vi1 |= (vh << 9) & 0x10000000;
1157            r.vi1[i] = vi1;
1158        }
1159        r.d = w->d;
1160        return r;
1161    }
1162    __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1163        int sumi = 0;
1164#pragma unroll
1165        for (int i = 0; i < 2; ++i) {
1166            sumi = STRATA_DP4A(r.vi0[i], reinterpret_cast<const int*>(x->qs)[iqs + i], sumi);
1167            sumi = STRATA_DP4A(r.vi1[i], reinterpret_cast<const int*>(x->qs)[iqs + i + 4], sumi);
1168        }
1169        const float2 ds = __half22float2(x->ds);
1170        return r.d * (sumi * ds.x - 8 * ds.y);
1171    }
1172};
1173
1174template<>
1175struct SmallTraits<Q80Block, 8> {
1176    using Block = Q80Block;
1177    static constexpr int DIV = 32, T = 4, KBY = 1, BPI = 2 * WARPS * WARP / 8;
1178    __device__ static int kqs(int tid) { return 2 * (tid % 4); }
1179    struct W { int v[2]; float d0; };
1180    __device__ static W load(const Block* __restrict__ w, int iqs) {
1181        W r;
1182#pragma unroll
1183        for (int i = 0; i < 2; ++i) r.v[i] = load_int_b2(w->qs, iqs + i);
1184        r.d0 = w->d;
1185        return r;
1186    }
1187    __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1188        int sumi = 0;
1189#pragma unroll
1190        for (int i = 0; i < 2; ++i) {
1191            const int u = reinterpret_cast<const int*>(x->qs)[iqs + i];
1192            sumi = STRATA_DP4A(r.v[i], u, sumi);
1193        }
1194        const float d1 = __low2float(x->ds);
1195        return r.d0 * d1 * float(sumi);
1196    }
1197};
1198
1199template<>
1200struct SmallTraits<IQ4NLBlock, 4> {
1201    using Block = IQ4NLBlock;
1202    static constexpr int DIV = 32, T = 2, KBY = 1, BPI = 2 * WARPS * WARP / 4;
1203    __device__ static int kqs(int tid) { return 2 * (tid % 2); }
1204    struct W { int2 v[2]; float dw; };
1205    __device__ static W load(const Block* __restrict__ w, int iqs) {
1206        W r;
1207#pragma unroll
1208        for (int i = 0; i < 2; ++i) r.v[i] = iq4_table_lookup(load_int_b2(w->qs, iqs + i));
1209        r.dw = __half2float(w->d);
1210        return r;
1211    }
1212    __device__ static float apply(const W& r, const Q81Block* __restrict__ x, int iqs) {
1213        const int* q8 = reinterpret_cast<const int*>(x->qs) + iqs;
1214        int sumi = 0;
1215#pragma unroll
1216        for (int i = 0; i < 2; ++i) {
1217            sumi = STRATA_DP4A(r.v[i].x, q8[i], sumi);
1218            sumi = STRATA_DP4A(r.v[i].y, q8[i + 4], sumi);
1219        }
1220        const float d = r.dw * __low2float(x->ds);
1221        return d * sumi;
1222    }
1223};
1224
1225// NW warps per block and ROWS rows per block. The EXACT layout (NW = 4, ROWS = 1, or 4 for small K) is the
1226// ncols = 1 layout and keeps every column bitwise equal to a single-column call. The UPSTREAM layout is
1227// llama.cpp's generic multi-column table (ncols 2-4: 4 warps; 5-8: 2 warps; always 2 rows per block): faster,
1228// equal to ncols = 1 only to float rounding (the cross-warp reduction groups partial sums differently).
1229bool g_multi_exact = true;   // until the upstream layout is timed on an idle GPU (plan rule: default only what is measured)
1230// B6 STRATA_B6_MMVQ_ROWS (lab, default 0 = off): see native_mmvq_set_b6_rows
1231// read at first use (not at load): a per-architecture default set at start (nv_defaults.hpp) must be seen
1232int g_b6_rows = -1;
1233int b6_rows_mode() { if (g_b6_rows < 0) { const char* v = std::getenv("STRATA_B6_MMVQ_ROWS"); g_b6_rows = v ? std::atoi(v) : 0; } return g_b6_rows; }
1234
1235// S26 STRATA_TSUM=1 (TS): warp 0's NCOLS x ROWS sums as one transposed butterfly (s26_tsum.cuh), bitwise the same
1236static bool s26_tsum_on() {
1237    static const bool on = [] { const char* v = std::getenv("STRATA_TSUM"); return v && v[0] == '1'; }();
1238    return on;
1239}
1240
1241// S26 STRATA_LFUSE (PAIR): blocks n_out.. compute the same rows of w2 into y2 (two matrices of one shape on one
1242// input in one launch; each output's code is the single matrix's)
1243template<typename F, int NCOLS, int NW, int ROWS, bool TS = false, bool PAIR = false>
1244__launch_bounds__(NW * WARP, (ROWS <= 2 ? 4 : 1))
1245__global__ void native_mmvq_multi_kernel(const typename F::Block* __restrict__ w, const Q81Block* x_, float* y_,
1246                                         int n_in, int n_out,
1247                                         const typename F::Block* __restrict__ w2 = nullptr, float* __restrict__ y2 = nullptr) {
1248    const Q81Block* STRATA_PDL_RESTRICT x = x_;   // __restrict__ below sm_70 only (pdl.hpp, #1469)
1249    float* STRATA_PDL_RESTRICT y = y_;
1250    constexpr int BPI = F::BPI * NW / WARPS;           // blocks per iteration scale with the warp count
1251    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
1252    int bxi = int(blockIdx.x);
1253    if constexpr (PAIR) {
1254        if (bxi >= n_out / ROWS) { bxi -= n_out / ROWS; w = w2; y = y2; }
1255    }
1256    const int row0 = ROWS * bxi;
1257    const int blocks_per_row = n_in / F::DIV;
1258    const int x_stride = n_in / Q8K;                   // Q8_1 blocks per activation column
1259    float tmp[NCOLS][ROWS] = {};
1260    int kbx = tid / F::T;
1261    if constexpr (kPdlPrefetch) {
1262        // PDL (pdl.hpp): the first block's weights are loaded before waiting for the activations, then that block
1263        // is applied exactly as the loop below would apply it (the same rows, columns and order)
1264        typename F::W w0[ROWS];
1265        const int kqs = F::kqs(tid);
1266        if (kbx < blocks_per_row) {
1267#pragma unroll
1268            for (int i = 0; i < ROWS; ++i)
1269                if (row0 + i < n_out) w0[i] = F::load(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs);
1270        }
1271        pdl_trigger();
1272        pdl_wait();
1273        if (kbx < blocks_per_row) {
1274            const int kby = kbx * F::KBY;
1275#pragma unroll
1276            for (int i = 0; i < ROWS; ++i) {
1277                if (row0 + i < n_out) {
1278#pragma unroll
1279                    for (int j = 0; j < NCOLS; ++j)
1280                        tmp[j][i] += F::apply(w0[i], x + std::size_t(j) * x_stride + kby, kqs);
1281                }
1282            }
1283        }
1284        kbx += BPI;
1285    }
1286    for (; kbx < blocks_per_row; kbx += BPI) {
1287        const int kby = kbx * F::KBY;
1288        const int kqs = F::kqs(tid);
1289#pragma unroll
1290        for (int i = 0; i < ROWS; ++i) {
1291            if (row0 + i < n_out) {
1292                const std::size_t block = std::size_t(row0 + i) * blocks_per_row + kbx;
1293                const typename F::W wv = F::load(w + block, kqs);      // once per (row, block)
1294#pragma unroll
1295                for (int j = 0; j < NCOLS; ++j)                         // then per column
1296                    tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);
1297            }
1298        }
1299    }
1300    __shared__ float partial[NW - 1 > 0 ? NW - 1 : 1][NCOLS][ROWS][WARP];
1301    if (threadIdx.y > 0) {
1302#pragma unroll
1303        for (int j = 0; j < NCOLS; ++j)
1304#pragma unroll
1305            for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][j][i][threadIdx.x] = tmp[j][i];
1306    }
1307    __syncthreads();
1308    if (threadIdx.y > 0) return;
1309    if constexpr (TS) {
1310        constexpr int V = NCOLS * ROWS, P = s26ts::pow2_ceil(V);
1311        float v[P];
1312#pragma unroll
1313        for (int j = 0; j < NCOLS; ++j)
1314#pragma unroll
1315            for (int i = 0; i < ROWS; ++i) {
1316#pragma unroll
1317                for (int l = 0; l < NW - 1; ++l) tmp[j][i] += partial[l][j][i][threadIdx.x];
1318                v[j * ROWS + i] = tmp[j][i];
1319            }
1320#pragma unroll
1321        for (int k = V; k < P; ++k) v[k] = 0.0f;
1322        const float sum = s26ts::tsum<P>(v, int(threadIdx.x));
1323        const int k = s26ts::tsum_token<P>(int(threadIdx.x));
1324        const int j = k / ROWS, i = k % ROWS;
1325        if (int(threadIdx.x) == s26ts::tsum_lane<P>(k) && k < V && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = sum;
1326        return;
1327    }
1328#pragma unroll
1329    for (int j = 0; j < NCOLS; ++j) {
1330#pragma unroll
1331        for (int i = 0; i < ROWS; ++i) {
1332#pragma unroll
1333            for (int l = 0; l < NW - 1; ++l) tmp[j][i] += partial[l][j][i][threadIdx.x];
1334            tmp[j][i] = warp_sum(tmp[j][i]);
1335            if (threadIdx.x == i && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = tmp[j][i];
1336        }
1337    }
1338}
1339
1340// MODEL-UPDATE: the dense Q8_0 projections of Unsloth's files (all of attention, SSM and the shared expert are Q8_0
1341// there) take one row per block where that was measured faster - the same per-row sums and reduction as two rows per
1342// block (each row its own partials), so every output is the same bits.  q8_gemv_bench, 2-4 columns:
1343//   gfx1201 (R9700): n_in <= 4096 with n_out >= 4096 (qkv 2560->10240 73-79% -> 83-84% of the 644 GB/s, gate 2560->6144
1344//     51-68% -> 76-78%, q 2560->12288 74-80% -> 85-86%); 6144->2560 is slower there (79% -> 55-59%) and keeps two rows.
1345//   sm_86 (RTX A4000): every n_out >= 2048 (+1-4% at 2-4 columns, 6144->2560 at 6 columns 70% -> 76%).
1346// Other cards keep two rows until measured (STRATA_NO_MMVQ_ROWS2=1 forces one row everywhere; =0 keeps two everywhere).
1347int dev_class() {   // 1 = gfx12, 2 = sm_86, 0 = the rest; per device
1348    static int cls[16];   // 0 unknown, else class + 1
1349    int dev = 0;
1350    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return 0;
1351    if (cls[dev] == 0) {
1352        int c = 0;
1353#if defined(__HIPCC__)
1354        cudaDeviceProp p;
1355        if (cudaGetDeviceProperties(&p, dev) == cudaSuccess && strata::kernels::gfx_arch_is_gfx12(p.gcnArchName)) c = 1;
1356#else
1357        int major = 0, minor = 0;
1358        if (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
1359            cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess && major == 8 && minor == 6)
1360            c = 2;
1361#endif
1362        (void) cudaGetLastError();
1363        cls[dev] = c + 1;
1364    }
1365    return cls[dev] - 1;
1366}
1367template<typename F>
1368bool q8_0_rows1(int n_in, int n_out) {
1369    if constexpr (!std::is_same_v<F, SmallTraits<Q80Block, 8>>) {
1370        (void) n_in; (void) n_out;
1371        return false;
1372    } else {
1373        static const int env = [] {
1374            const char* v = std::getenv("STRATA_NO_MMVQ_ROWS2");
1375            return v == nullptr || v[0] == '\0' ? -1 : v[0] != '0';
1376        }();
1377        if (env == 0) return false;
1378        const int c = dev_class();
1379        return (c == 1 && n_in <= 4096 && n_out >= 4096) || (c == 2 && n_out >= 2048);
1380    }
1381}
1382
1383// ---- B6 STRATA_B6_MMVQ_ROWS (lab, opt-in): the exact multi-column layout with each column's activation fragment
1384// loaded ONCE per weight block and reused across ROWS rows of the block (the default kernel reloads it for every row
1385// it applies it to, and the K-quant scales once per column).  A thread keeps the same blocks (kbx = tid / T, stride
1386// BPI with WARPS warps), each (row, column) sum adds the same per-block values in the same order, and the cross-warp
1387// and warp reductions are the default kernel's: every output is bitwise the default exact layout's, so bitwise a
1388// single-column call.  Only the formats with a B6X below; the others keep the default kernel.
1389template<typename F> struct B6X { static constexpr bool ok = false; };
1390template<> struct B6X<Q6KTraits> {
1391    static constexpr bool ok = true;
1392    struct X { int u[2]; float d8[2]; };
1393    struct W { int vl, vh, sc[2]; float d; };
1394    __device__ static X xload(const Q81Block* x, int iqs) {
1395        X r;
1396        const int off = 4 * (iqs / 16) + (iqs % 16) / 8;   // Q6KTraits::load's bq8_offset
1397#pragma unroll
1398        for (int i = 0; i < 2; ++i) {
1399            r.u[i] = reinterpret_cast<const int*>(x[off + 2 * i].qs)[iqs % 8];
1400            r.d8[i] = __low2float(x[off + 2 * i].ds);
1401        }
1402        return r;
1403    }
1404    __device__ static W wload(const Q6KBlock* __restrict__ w, int iqs) {
1405        const Q6KTraits::W t = Q6KTraits::load(w, iqs);
1406        W r;
1407        r.vl = t.vl;
1408        r.vh = t.vh;
1409        r.sc[0] = t.scales[0];
1410        r.sc[1] = t.scales[4];
1411        r.d = t.d;
1412        return r;
1413    }
1414    __device__ static float dot(const W& w, const X& x) {   // q6_q8_dot_impl, the scales already in registers
1415        float sumf = 0.0f;
1416#pragma unroll
1417        for (int i = 0; i < 2; ++i) {
1418            const int vil = (w.vl >> (4 * i)) & 0x0f0f0f0f;
1419            const int vih = ((w.vh >> (4 * i)) << 4) & 0x30303030;
1420            const int vi = __vsubss4(vil | vih, 0x20202020);
1421            sumf += x.d8[i] * (STRATA_DP4A(vi, x.u[i], 0) * w.sc[i]);
1422        }
1423        return w.d * sumf;
1424    }
1425};
1426template<typename T, int KIND> struct B6XK {   // Q4_K (KIND 4) and Q5_K (KIND 5): the same activation fragment
1427    static constexpr bool ok = true;
1428    struct X { int u[4]; float d8[2]; };
1429    using W = typename T::W;
1430    __device__ static X xload(const Q81Block* bq8, int iqs) {
1431        X r;
1432        const int off = 2 * ((iqs / 2) / 4);   // the traits' bq8_offset
1433#pragma unroll
1434        for (int i = 0; i < 2; ++i) {
1435            const Q81Block* bq8i = bq8 + off + i;
1436            r.d8[i] = __low2float(bq8i->ds);
1437            const int* q8 = reinterpret_cast<const int*>(bq8i->qs) + ((iqs / 2) % 4);
1438            r.u[2 * i] = q8[0];
1439            r.u[2 * i + 1] = q8[4];
1440        }
1441        return r;
1442    }
1443    __device__ static W wload(const typename T::Block* __restrict__ w, int iqs) { return T::load(w, iqs); }
1444    __device__ static float dot(const W& w, const X& x) {
1445        const uint8_t* sc = reinterpret_cast<const uint8_t*>(w.aux);
1446        if constexpr (KIND == 4) return q4_q8_dot_impl(w.v, x.u, sc, sc + 2, w.dm, x.d8);
1447        else return q5_q8_dot_impl(w.vl, w.vh, x.u, sc, sc + 2, w.dm, x.d8);
1448    }
1449};
1450template<> struct B6X<Q4KTraits> : B6XK<Q4KTraits, 4> {};
1451template<> struct B6X<Q5KTraits> : B6XK<Q5KTraits, 5> {};
1452template<> struct B6X<IQ4XSTraits> {
1453    static constexpr bool ok = true;
1454    struct X { int u0[4], u1[4]; float dx; };
1455    using W = IQ4XSTraits::W;
1456    __device__ static X xload(const Q81Block* x, int iqs) {
1457        X r;
1458#pragma unroll
1459        for (int j = 0; j < 4; ++j) {
1460            r.u0[j] = reinterpret_cast<const int*>(x[iqs / 4].qs)[j];
1461            r.u1[j] = reinterpret_cast<const int*>(x[iqs / 4].qs)[j + 4];
1462        }
1463        r.dx = __low2float(x[iqs / 4].ds);
1464        return r;
1465    }
1466    __device__ static W wload(const IQ4XSBlock* __restrict__ w, int iqs) { return IQ4XSTraits::load(w, iqs); }
1467    __device__ static float dot(const W& w, const X& x) {   // IQ4XSTraits::apply
1468        int sumi = 0;
1469#pragma unroll
1470        for (int j = 0; j < 4; ++j) {
1471            sumi = STRATA_DP4A(w.v[j].x, x.u0[j], sumi);
1472            sumi = STRATA_DP4A(w.v[j].y, x.u1[j], sumi);
1473        }
1474        sumi *= w.ls - 32;
1475        const float d = w.dw * x.dx;
1476        return d * sumi;
1477    }
1478};
1479
1480template<typename F, int NCOLS, int ROWS>
1481__launch_bounds__(WARPS * WARP, 1)
1482__global__ void b6_mmvq_rows_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
1483                                    float* __restrict__ y, int n_in, int n_out) {
1484    using XB = B6X<F>;
1485    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
1486    const int row0 = ROWS * int(blockIdx.x);
1487    const int blocks_per_row = n_in / F::DIV;
1488    const int x_stride = n_in / Q8K;
1489    const int kqs = F::kqs(tid);
1490    float tmp[NCOLS][ROWS] = {};
1491    for (int kbx = tid / F::T; kbx < blocks_per_row; kbx += F::BPI) {
1492        const int kby = kbx * F::KBY;
1493        typename XB::X xv[NCOLS];
1494#pragma unroll
1495        for (int j = 0; j < NCOLS; ++j) xv[j] = XB::xload(x + std::size_t(j) * x_stride + kby, kqs);
1496#pragma unroll
1497        for (int i = 0; i < ROWS; ++i) {
1498            if (row0 + i < n_out) {
1499                const typename XB::W wv = XB::wload(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs);
1500#pragma unroll
1501                for (int j = 0; j < NCOLS; ++j) tmp[j][i] += XB::dot(wv, xv[j]);
1502            }
1503        }
1504    }
1505    __shared__ float partial[WARPS - 1][NCOLS][ROWS][WARP];
1506    if (threadIdx.y > 0) {
1507#pragma unroll
1508        for (int j = 0; j < NCOLS; ++j)
1509#pragma unroll
1510            for (int i = 0; i < ROWS; ++i) partial[threadIdx.y - 1][j][i][threadIdx.x] = tmp[j][i];
1511    }
1512    __syncthreads();
1513    if (threadIdx.y > 0) return;
1514#pragma unroll
1515    for (int j = 0; j < NCOLS; ++j) {
1516#pragma unroll
1517        for (int i = 0; i < ROWS; ++i) {
1518#pragma unroll
1519            for (int l = 0; l < WARPS - 1; ++l) tmp[j][i] += partial[l][j][i][threadIdx.x];
1520            tmp[j][i] = warp_sum(tmp[j][i]);
1521            if (threadIdx.x == i && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = tmp[j][i];
1522        }
1523    }
1524}
1525
1526// the B6 launch for a format that has a B6X: true when it ran.  g_b6_rows: 1 = 2 rows per block (the fastest on both
1527// cards in b6_mmvq_bench), else 2 / 4 / 8 rows.
1528template<typename F, int NCOLS>
1529bool b6_launch(const typename F::Block* w, const Q81Block* x, float* y, int n_in, int n_out, cudaStream_t s) {
1530    if constexpr (!B6X<F>::ok) {
1531        return false;
1532    } else {
1533        if (b6_rows_mode() <= 0 || !g_multi_exact || s26_tsum_on() || n_in / F::DIV < 1) return false;
1534        const int rows = b6_rows_mode() == 1 ? 2 : b6_rows_mode();
1535        const dim3 threads(WARP, WARPS);
1536        if (rows == 2)
1537            b6_mmvq_rows_kernel<F, NCOLS, 2><<<unsigned((n_out + 1) / 2), threads, 0, s>>>(w, x, y, n_in, n_out);
1538        else if (rows == 8)
1539            b6_mmvq_rows_kernel<F, NCOLS, 8><<<unsigned((n_out + 7) / 8), threads, 0, s>>>(w, x, y, n_in, n_out);
1540        else
1541            b6_mmvq_rows_kernel<F, NCOLS, 4><<<unsigned((n_out + 3) / 4), threads, 0, s>>>(w, x, y, n_in, n_out);
1542        return true;
1543    }
1544}
1545
1546template<typename F, int NCOLS>
1547void launch_multi_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) {
1548    const auto* w = static_cast<const typename F::Block*>(weights);
1549    const auto* x = static_cast<const Q81Block*>(x_q8_1);
1550    if (b6_launch<F, NCOLS>(w, x, y, n_in, n_out, s)) return;   // STRATA_B6_MMVQ_ROWS
1551    if (!g_multi_exact) {
1552        constexpr int NW = NCOLS <= 4 ? 4 : 2;
1553        const unsigned blocks = unsigned((std::size_t(n_out) + 1) / 2);
1554        launch_pdl(native_mmvq_multi_kernel<F, NCOLS, NW, 2, false, false>, dim3(blocks), dim3(WARP, NW), 0, s, w, x, y, n_in, n_out,
1555                   (const typename F::Block*) nullptr, (float*) nullptr);
1556        return;
1557    }
1558    const dim3 threads(WARP, WARPS);
1559    // the PAIR arguments, unused here (launch_pdl passes every parameter)
1560    const typename F::Block* const no_w2 = nullptr;
1561    float* const no_y2 = nullptr;
1562    // #783 PR-h (stuchapin909): two rows per block for every K, not only small K - each row keeps its own partial sums and
1563    // reduction, so a row's result does not depend on its neighbour; STRATA_NO_MMVQ_ROWS2=1 keeps one row for large K
1564    static const bool rows1 = [] {
1565        const char* v = std::getenv("STRATA_NO_MMVQ_ROWS2");
1566        return v != nullptr && v[0] != '\0' && v[0] != '0';
1567    }();
1568    if ((rows1 || q8_0_rows1<F>(n_in, n_out)) && n_in / F::DIV >= F::BPI) {
1569        if (s26_tsum_on()) launch_pdl(native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, true, false>, dim3(unsigned(n_out)), threads, 0, s, w, x, y, n_in, n_out, no_w2, no_y2);
1570        else launch_pdl(native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, false, false>, dim3(unsigned(n_out)), threads, 0, s, w, x, y, n_in, n_out, no_w2, no_y2);
1571        return;
1572    }
1573    constexpr int ROWS = 2;
1574    const unsigned blocks = unsigned((std::size_t(n_out) + ROWS - 1) / ROWS);
1575    if (s26_tsum_on()) launch_pdl(native_mmvq_multi_kernel<F, NCOLS, WARPS, ROWS, true, false>, dim3(blocks), threads, 0, s, w, x, y, n_in, n_out, no_w2, no_y2);
1576    else launch_pdl(native_mmvq_multi_kernel<F, NCOLS, WARPS, ROWS, false, false>, dim3(blocks), threads, 0, s, w, x, y, n_in, n_out, no_w2, no_y2);
1577}
1578
1579template<typename F>
1580void launch_multi(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols,
1581                  void* stream) {
1582    const auto s = static_cast<cudaStream_t>(stream);
1583    switch (ncols) {
1584        case 2: launch_multi_n<F, 2>(weights, x_q8_1, y, n_in, n_out, s); break;
1585        case 3: launch_multi_n<F, 3>(weights, x_q8_1, y, n_in, n_out, s); break;
1586        case 4: launch_multi_n<F, 4>(weights, x_q8_1, y, n_in, n_out, s); break;
1587        case 5: launch_multi_n<F, 5>(weights, x_q8_1, y, n_in, n_out, s); break;
1588        case 6: launch_multi_n<F, 6>(weights, x_q8_1, y, n_in, n_out, s); break;
1589        case 7: launch_multi_n<F, 7>(weights, x_q8_1, y, n_in, n_out, s); break;
1590        case 8: launch_multi_n<F, 8>(weights, x_q8_1, y, n_in, n_out, s); break;
1591#if STRATA_VERIFY_MAX_T > 8
1592        case 9: launch_multi_n<F, 9>(weights, x_q8_1, y, n_in, n_out, s); break;
1593        case 10: launch_multi_n<F, 10>(weights, x_q8_1, y, n_in, n_out, s); break;
1594        case 11: launch_multi_n<F, 11>(weights, x_q8_1, y, n_in, n_out, s); break;
1595        case 12: launch_multi_n<F, 12>(weights, x_q8_1, y, n_in, n_out, s); break;
1596#if STRATA_VERIFY_MAX_T > 12
1597        case 13: launch_multi_n<F, 13>(weights, x_q8_1, y, n_in, n_out, s); break;
1598        case 14: launch_multi_n<F, 14>(weights, x_q8_1, y, n_in, n_out, s); break;
1599        case 15: launch_multi_n<F, 15>(weights, x_q8_1, y, n_in, n_out, s); break;
1600        case 16: launch_multi_n<F, 16>(weights, x_q8_1, y, n_in, n_out, s); break;
1601#endif
1602#endif
1603        default: throw std::invalid_argument("native MMVQ multi-column launch requires 2 <= ncols <= MAX_NCOLS");
1604    }
1605}
1606
1607#if !defined(__HIPCC__)   // CUDA only: the HIP paths keep native_mmvq's kernels
1608// ============================ ncols = 2..4 from interleaved activations (fork F4, Eddoursul) ============================
1609//
1610// `native_quantize_q8_1_il` also writes the columns interleaved (native_mmvq.hpp), so one load reads the same int of
1611// every column. A warp takes R rows and walks their blocks in the chunks of the exact layout above - its lane l's chunk
1612// m is what thread 32 (m % 4) + l does in iteration m / 4 - with a sum per virtual warp, added in warp order before the
1613// xor tree; each weight block is decoded once (the traits' `load`) and every column takes the single-column dot's own
1614// expression (the same *_q8_dot_impl calls), so each value is bitwise the multi-column kernel's. K-quants read the
1615// block-major copy; IQ4_XS, whose lanes read the same int of consecutive blocks, the position-major one.
1616struct IlIQ4XS {
1617    using F = IQ4XSTraits;
1618    static constexpr bool PM = true;
1619    template <int NC, class X>
1620    __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) {
1621        const int b = kby + iqs / 4;
1622        int u0[4][NC], u1[4][NC];
1623#pragma unroll
1624        for (int j = 0; j < 4; ++j) {
1625            x.u(b, j, u0[j]);
1626            x.u(b, j + 4, u1[j]);
1627        }
1628        float d8[NC];
1629        x.scales(b, d8);
1630#pragma unroll
1631        for (int c = 0; c < NC; ++c) {
1632            int sumi = 0;
1633#pragma unroll
1634            for (int j = 0; j < 4; ++j) {
1635                sumi = STRATA_DP4A(r.v[j].x, u0[j][c], sumi);
1636                sumi = STRATA_DP4A(r.v[j].y, u1[j][c], sumi);
1637            }
1638            sumi *= r.ls - 32;
1639            const float d = r.dw * d8[c];
1640            out[c] = d * sumi;
1641        }
1642    }
1643    // P1 (native_mmvq_il_pf_kernel): the block's bytes as loaded, the table lookup and the scale decode deferred to
1644    // applyr so the loads of a whole group issue before any of them is consumed; the same integers and floats as apply
1645    static constexpr bool HAS_PF = true;
1646    struct RP { const uint8_t *qs, *sl, *blk; };   // a row's blocks for this lane: its qs ints, its scales_l byte, the block
1647    __device__ static RP rowptrs(const F::Block* __restrict__ row, int iqs) {
1648        const auto* b = reinterpret_cast<const uint8_t*>(row);
1649        return {b + 8 + 4 * iqs, b + 4 + iqs / 8, b};
1650    }
1651    struct WR { int q[4]; int sl, sh, d; };
1652    // the pointers of block kbx (RP::at), and the loads of block kbx + dv from them (dv a compile-time offset, so the
1653    // group's loads share one pointer set and differ by an immediate)
1654    __device__ static RP at(const RP& rp, int kbx) {
1655        constexpr int S = int(sizeof(F::Block));
1656        return {static_cast<const uint8_t*>(madw(rp.qs, kbx, S)), static_cast<const uint8_t*>(madw(rp.sl, kbx, S)),
1657                static_cast<const uint8_t*>(madw(rp.blk, kbx, S))};
1658    }
1659    __device__ static WR loadr(const RP& rp, int dv) {
1660        constexpr int S = int(sizeof(F::Block));
1661        const auto* qs = reinterpret_cast<const int*>(rp.qs + dv * S);
1662        WR r;
1663#pragma unroll
1664        for (int j = 0; j < 4; ++j) r.q[j] = ldg_nc_s32(qs + j);
1665        r.sl = ldg_nc_u8(rp.sl + dv * S);
1666        r.sh = ldg_nc_u16(rp.blk + dv * S + 2);
1667        r.d = ldg_nc_u16(rp.blk + dv * S);
1668        return r;
1669    }
1670    // the activations: position-major (every int of the 8 at a stride of nb), so the kernel's block pointers are not used
1671    __device__ static int xb(int) { return 0; }
1672    __device__ static int xp(int) { return 0; }
1673    template <int NC, bool FAST, class X>
1674    __device__ static void applyr(const WR& rr, const X& x, const int*, const float*, int kby, int iqs, float (&out)[NC]) {
1675        F::W r;
1676#pragma unroll
1677        for (int j = 0; j < 4; ++j) r.v[j] = iq4_table_lookup(rr.q[j]);
1678        r.ls = ((rr.sl >> (iqs & 0x04)) & 0x0f) | (((rr.sh >> (iqs / 2)) & 0x03) << 4);
1679        r.dw = __half2float(__ushort_as_half((unsigned short) rr.d));
1680        if constexpr (!FAST) {
1681            apply<NC>(r, x, kby, iqs, out);
1682        } else {
1683            // P2: sumi (|sumi| <= 32 * 127 * 127 = 516K < 2^22) through i2f_small, then times (float)(ls - 32): the product
1684            // |sumi * (ls - 32)| < 2^24 is exact in fp32, so it is the float of the int apply() converts; the same d * sumi
1685            const int b = kby + iqs / 4;
1686            int u0[4][NC], u1[4][NC];
1687#pragma unroll
1688            for (int j = 0; j < 4; ++j) {
1689                x.u(b, j, u0[j]);
1690                x.u(b, j + 4, u1[j]);
1691            }
1692            float d8[NC];
1693            x.scales(b, d8);
1694            const float fls = float(r.ls - 32);
1695#pragma unroll
1696            for (int c = 0; c < NC; ++c) {
1697                int sumi = 0;
1698#pragma unroll
1699                for (int j = 0; j < 4; ++j) {
1700                    sumi = STRATA_DP4A(r.v[j].x, u0[j][c], sumi);
1701                    sumi = STRATA_DP4A(r.v[j].y, u1[j][c], sumi);
1702                }
1703                const float fsumi = i2f_small(sumi + kI2fMagic) * fls;
1704                const float d = r.dw * d8[c];
1705                out[c] = d * fsumi;
1706            }
1707        }
1708    }
1709};
1710struct IlQ4K {
1711    using F = Q4KTraits;
1712    static constexpr bool PM = false;
1713    static constexpr bool HAS_PF = true;   // P1: F::W holds every byte of the block already (no pointer into it)
1714    struct RP { const uint8_t *qs, *sc, *blk; int iqs; };   // this lane's ql ints, its scale words, the block (dm)
1715    __device__ static RP rowptrs(const F::Block* __restrict__ row, int iqs) {
1716        const auto* b = reinterpret_cast<const uint8_t*>(row);
1717        const int bq8_offset = 2 * ((iqs / 2) / 4), jm = (bq8_offset / 2) & 1;
1718        return {b + 16 + 16 * bq8_offset + 4 * ((iqs / 2) % 4), b + 4 + 2 * jm, b, iqs};
1719    }
1720    using WR = F::W;
1721    __device__ static RP at(const RP& rp, int kbx) {
1722        constexpr int S = int(sizeof(F::Block));
1723        return {static_cast<const uint8_t*>(madw(rp.qs, kbx, S)), static_cast<const uint8_t*>(madw(rp.sc, kbx, S)),
1724                static_cast<const uint8_t*>(madw(rp.blk, kbx, S)), rp.iqs};
1725    }
1726    __device__ static WR loadr(const RP& rp, int dv) {   // F::load's bytes and aux arithmetic, block dv past rp's
1727        constexpr int S = int(sizeof(F::Block));
1728        const auto* ql = reinterpret_cast<const int*>(rp.qs + dv * S);
1729        const auto* sc = rp.sc + dv * S;
1730        WR r;
1731        r.bq8_offset = 2 * ((rp.iqs / 2) / 4);
1732        r.v[0] = ldg_nc_s32(ql);
1733        r.v[1] = ldg_nc_s32(ql + 4);
1734        const uint32_t s0 = ldg_nc_u16(sc), s2 = ldg_nc_u16(sc + 4), s4 = ldg_nc_u16(sc + 8);
1735        const int dm = ldg_nc_s32(rp.blk + dv * S);
1736        const int j = r.bq8_offset / 2;
1737        const uint32_t hi = uint32_t(-int32_t(j >= 2));
1738        r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
1739        r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
1740        { half2 h; std::memcpy(&h, &dm, 4); r.dm = h; }
1741        return r;
1742    }
1743    __device__ static int xb(int iqs) { return 2 * ((iqs / 2) / 4); }   // the lane's q8_1 block and int within a 256-chunk
1744    __device__ static int xp(int iqs) { return (iqs / 2) % 4; }
1745    template <int NC, bool FAST, class X>
1746    __device__ static void applyr(const WR& r, const X& x, const int* qb, const float* db, int kby, int iqs, float (&out)[NC]) {
1747        if constexpr (!FAST) {
1748            apply<NC>(r, x, kby, iqs, out);
1749        } else {   // P2: q4_q8_dot_impl with (dot1 * sc), (dot2 * m) through i2f_small (|dot1 * sc| <= 15240 * 63, |dot2 * m| <= 1016 * 63)
1750            int u[4][NC];
1751            float d8[2][NC];
1752#pragma unroll
1753            for (int i = 0; i < 2; ++i) {
1754                x.qat(qb + i * X::QB, u[2 * i]);
1755                x.qat(qb + i * X::QB + x.qp(4), u[2 * i + 1]);
1756                x.dat(db + i * X::DB, d8[i]);
1757            }
1758            const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux);
1759            const uint8_t* m = sc + 2;
1760            const float2 dm4f = __half22float2(r.dm);
1761#pragma unroll
1762            for (int c = 0; c < NC; ++c) {
1763                float sumf_d = 0.0f;
1764                float sumf_m = 0.0f;
1765#pragma unroll
1766                for (int i = 0; i < 2; ++i) {
1767                    const int v0i = (r.v[0] >> (4 * i)) & 0x0f0f0f0f;
1768                    const int v1i = (r.v[1] >> (4 * i)) & 0x0f0f0f0f;
1769                    const int dot1 = STRATA_DP4A(v1i, u[2 * i + 1][c], STRATA_DP4A(v0i, u[2 * i][c], 0));
1770                    const int dot2 = STRATA_DP4A(0x01010101, u[2 * i + 1][c], STRATA_DP4A(0x01010101, u[2 * i][c], 0));
1771                    sumf_d += d8[i][c] * i2f_small(dot1 * sc[i] + kI2fMagic);
1772                    sumf_m += d8[i][c] * i2f_small(dot2 * m[i] + kI2fMagic);
1773                }
1774                out[c] = dm4f.x * sumf_d - dm4f.y * sumf_m;
1775            }
1776        }
1777    }
1778    template <int NC, class X>
1779    __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) {
1780        int u[4][NC];
1781        float d8[2][NC];
1782#pragma unroll
1783        for (int i = 0; i < 2; ++i) {
1784            const int b = kby + r.bq8_offset + i;
1785            x.u(b, (iqs / 2) % 4, u[2 * i]);
1786            x.u(b, (iqs / 2) % 4 + 4, u[2 * i + 1]);
1787            x.scales(b, d8[i]);
1788        }
1789        const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux);
1790#pragma unroll
1791        for (int c = 0; c < NC; ++c) {
1792            const int uc[4] = {u[0][c], u[1][c], u[2][c], u[3][c]};
1793            const float dc[2] = {d8[0][c], d8[1][c]};
1794            out[c] = q4_q8_dot_impl(r.v, uc, sc, sc + 2, r.dm, dc);
1795        }
1796    }
1797};
1798struct IlQ5K {
1799    using F = Q5KTraits;
1800    static constexpr bool PM = false;
1801    static constexpr bool HAS_PF = true;   // P1: as IlQ4K
1802    struct RP { const uint8_t *qs, *qh, *sc, *blk; int iqs; };
1803    __device__ static RP rowptrs(const F::Block* __restrict__ row, int iqs) {
1804        const auto* b = reinterpret_cast<const uint8_t*>(row);
1805        const int bq8_offset = 2 * ((iqs / 2) / 4), jm = (bq8_offset / 2) & 1;
1806        return {b + 48 + 16 * bq8_offset + 4 * ((iqs / 2) % 4), b + 16 + 4 * ((iqs / 2) % 4), b + 4 + 2 * jm, b, iqs};
1807    }
1808    using WR = F::W;
1809    __device__ static RP at(const RP& rp, int kbx) {
1810        constexpr int S = int(sizeof(F::Block));
1811        return {static_cast<const uint8_t*>(madw(rp.qs, kbx, S)), static_cast<const uint8_t*>(madw(rp.qh, kbx, S)),
1812                static_cast<const uint8_t*>(madw(rp.sc, kbx, S)), static_cast<const uint8_t*>(madw(rp.blk, kbx, S)), rp.iqs};
1813    }
1814    __device__ static WR loadr(const RP& rp, int dv) {   // F::load's bytes and aux arithmetic, block dv past rp's
1815        constexpr int S = int(sizeof(F::Block));
1816        const auto* ql = reinterpret_cast<const int*>(rp.qs + dv * S);
1817        const auto* qh = reinterpret_cast<const int*>(rp.qh + dv * S);
1818        const auto* sc = rp.sc + dv * S;
1819        WR r;
1820        r.bq8_offset = 2 * ((rp.iqs / 2) / 4);
1821        r.vl[0] = ldg_nc_s32(ql);
1822        r.vl[1] = ldg_nc_s32(ql + 4);
1823        r.vh[0] = ldg_nc_s32(qh) >> r.bq8_offset;
1824        r.vh[1] = ldg_nc_s32(qh + 4) >> r.bq8_offset;
1825        const uint32_t s0 = ldg_nc_u16(sc), s2 = ldg_nc_u16(sc + 4), s4 = ldg_nc_u16(sc + 8);
1826        const int dm = ldg_nc_s32(rp.blk + dv * S);
1827        const int j = r.bq8_offset / 2;
1828        const uint32_t hi = uint32_t(-int32_t(j >= 2));
1829        r.aux[0] = uint16_t(((s0 & 0x3f3f) & ~hi) | ((((s4 >> 0) & 0x0f0f) | ((s0 & 0xc0c0) >> 2)) & hi));
1830        r.aux[1] = uint16_t(((s2 & 0x3f3f) & ~hi) | ((((s4 >> 4) & 0x0f0f) | ((s2 & 0xc0c0) >> 2)) & hi));
1831        { half2 h; std::memcpy(&h, &dm, 4); r.dm = h; }
1832        return r;
1833    }
1834    __device__ static int xb(int iqs) { return 2 * ((iqs / 2) / 4); }
1835    __device__ static int xp(int iqs) { return (iqs / 2) % 4; }
1836    template <int NC, bool FAST, class X>
1837    __device__ static void applyr(const WR& r, const X& x, const int* qb, const float* db, int kby, int iqs, float (&out)[NC]) {
1838        if constexpr (!FAST) {
1839            apply<NC>(r, x, kby, iqs, out);
1840        } else {   // P2: q5_q8_dot_impl with (dot1 * sc), (dot2 * m) through i2f_small (|dot1 * sc| <= 31496 * 63 < 2^22)
1841            int u[4][NC];
1842            float d8[2][NC];
1843#pragma unroll
1844            for (int i = 0; i < 2; ++i) {
1845                x.qat(qb + i * X::QB, u[2 * i]);
1846                x.qat(qb + i * X::QB + x.qp(4), u[2 * i + 1]);
1847                x.dat(db + i * X::DB, d8[i]);
1848            }
1849            const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux);
1850            const uint8_t* m = sc + 2;
1851            const float2 dm5f = __half22float2(r.dm);
1852#pragma unroll
1853            for (int c = 0; c < NC; ++c) {
1854                float sumf_d = 0.0f;
1855                float sumf_m = 0.0f;
1856#pragma unroll
1857                for (int i = 0; i < 2; ++i) {
1858                    const int vl0i = (r.vl[0] >> (4 * i)) & 0x0f0f0f0f;
1859                    const int vl1i = (r.vl[1] >> (4 * i)) & 0x0f0f0f0f;
1860                    const int vh0i = ((r.vh[0] >> i) << 4) & 0x10101010;
1861                    const int vh1i = ((r.vh[1] >> i) << 4) & 0x10101010;
1862                    const int v0i = vl0i | vh0i;
1863                    const int v1i = vl1i | vh1i;
1864                    const int dot1 = STRATA_DP4A(v0i, u[2 * i][c], STRATA_DP4A(v1i, u[2 * i + 1][c], 0));
1865                    const int dot2 = STRATA_DP4A(0x01010101, u[2 * i][c], STRATA_DP4A(0x01010101, u[2 * i + 1][c], 0));
1866                    sumf_d += d8[i][c] * i2f_small(dot1 * sc[i] + kI2fMagic);
1867                    sumf_m += d8[i][c] * i2f_small(dot2 * m[i] + kI2fMagic);
1868                }
1869                out[c] = dm5f.x * sumf_d - dm5f.y * sumf_m;
1870            }
1871        }
1872    }
1873    template <int NC, class X>
1874    __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) {
1875        int u[4][NC];
1876        float d8[2][NC];
1877#pragma unroll
1878        for (int i = 0; i < 2; ++i) {
1879            const int b = kby + r.bq8_offset + i;
1880            x.u(b, (iqs / 2) % 4, u[2 * i]);
1881            x.u(b, (iqs / 2) % 4 + 4, u[2 * i + 1]);
1882            x.scales(b, d8[i]);
1883        }
1884        const uint8_t* sc = reinterpret_cast<const uint8_t*>(r.aux);
1885#pragma unroll
1886        for (int c = 0; c < NC; ++c) {
1887            const int uc[4] = {u[0][c], u[1][c], u[2][c], u[3][c]};
1888            const float dc[2] = {d8[0][c], d8[1][c]};
1889            out[c] = q5_q8_dot_impl(r.vl, r.vh, uc, sc, sc + 2, r.dm, dc);
1890        }
1891    }
1892};
1893// Q3_K (143-dense): the Q2_0 pack's dense projections are mostly Q3_K, which only had the exact layout's kernel. The
1894// dot is q3_q8_dot_impl, the multi-column kernel's own call, on the same four blocks' ints and scales.
1895struct IlQ3K {
1896    using F = Q3KTraits;
1897    static constexpr bool PM = false;
1898    static constexpr bool HAS_PF = false;   // the Q2_0 pack's type: keeps native_mmvq_il_kernel (F::W points into the block)
1899    template <int NC, class X>
1900    __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) {
1901        int u[4][NC];
1902        float d8[4][NC];
1903#pragma unroll
1904        for (int i = 0; i < 4; ++i) {
1905            const int b = kby + r.bq8_offset + i;
1906            x.u(b, iqs % 8, u[i]);
1907            x.scales(b, d8[i]);
1908        }
1909        // q3_q8_dot_impl's arithmetic with the column-independent part done once: the four scales, and the four sets of
1910        // signed values (vil - vih, vih = 4 where the high bit is set, is vil | 0xFC in that byte: vil is 0..3, so nothing
1911        // saturates and it is __vsubss4's result)
1912        int vi[4], sc[4];
1913#pragma unroll
1914        for (int i = 0; i < 4; ++i) {
1915            const int isc = r.scale_offset + 2 * i;
1916            const int isc_low = isc % 8;
1917            const int sc_shift_low = 4 * (isc / 8);
1918            const int sc_low = (r.scales[isc_low] >> sc_shift_low) & 0xf;
1919            const int isc_high = isc % 4;
1920            const int sc_shift_high = 2 * (isc / 4);
1921            const int sc_high = ((r.scales[8 + isc_high] >> sc_shift_high) & 3) << 4;
1922            sc[i] = (sc_low | sc_high) - 32;
1923            vi[i] = ((r.vl >> (2 * i)) & 0x03030303) | (((r.vh >> i) & 0x01010101) * 252);
1924        }
1925#pragma unroll
1926        for (int c = 0; c < NC; ++c) {
1927            float sumf = 0.0f;
1928#pragma unroll
1929            for (int i = 0; i < 4; ++i) sumf += d8[i][c] * (STRATA_DP4A(vi[i], u[i][c], 0) * sc[i]);
1930            out[c] = r.d * sumf;
1931        }
1932    }
1933};
1934struct IlQ6K {
1935    using F = Q6KTraits;
1936    static constexpr bool PM = false;
1937    template <int NC, class X>
1938    __device__ static void apply(const F::W& r, const X& x, int kby, int iqs, float (&out)[NC]) {
1939        int u[2][NC];
1940        float d8[2][NC];
1941#pragma unroll
1942        for (int i = 0; i < 2; ++i) {
1943            x.u(kby + r.bq8_offset + 2 * i, iqs % 8, u[i]);
1944            x.scales(kby + r.bq8_offset + 2 * i, d8[i]);
1945        }
1946#pragma unroll
1947        for (int c = 0; c < NC; ++c) {
1948            const int uc[2] = {u[0][c], u[1][c]};
1949            const float dc[2] = {d8[0][c], d8[1][c]};
1950            out[c] = q6_q8_dot_impl(r.vl, r.vh, uc, r.scales, r.d, dc);
1951        }
1952    }
1953    // P1: the two scale bytes loaded with the rest (F::W keeps a pointer into the block, which would put their loads
1954    // in the compute phase); q6_q8_dot_sc is q6_q8_dot_impl's expression
1955    static constexpr bool HAS_PF = true;
1956    // a row's four lane-adjusted byte pointers (ql, qh, scales, d): a block's loads are then one IMAD.WIDE each from kbx
1957    struct RP { const uint8_t *ql, *qh, *sc, *d; };
1958    __device__ static RP rowptrs(const F::Block* __restrict__ row, int iqs) {
1959        const auto* b = reinterpret_cast<const uint8_t*>(row);
1960        const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4;
1961        return {b + 4 * iqs, b + 128 + 4 * (8 * (iqs / 16) + iqs % 8), b + 192 + scale_offset, b + 208};   // load_int_b2's int iqs
1962    }
1963    struct WR { int vl, vh, sc0, sc1, d; };
1964    __device__ static RP at(const RP& rp, int kbx) {
1965        constexpr int S = int(sizeof(F::Block));
1966        return {static_cast<const uint8_t*>(madw(rp.ql, kbx, S)), static_cast<const uint8_t*>(madw(rp.qh, kbx, S)),
1967                static_cast<const uint8_t*>(madw(rp.sc, kbx, S)), static_cast<const uint8_t*>(madw(rp.d, kbx, S))};
1968    }
1969    __device__ static WR loadr(const RP& rp, int dv) {   // block dv past rp's: immediates off its four pointers
1970        constexpr int S = int(sizeof(F::Block));
1971        WR r;
1972        r.vl = ldg_nc_b2(rp.ql + dv * S, 0);
1973        r.vh = ldg_nc_b2(rp.qh + dv * S, 0);
1974        r.sc0 = ldg_nc_s8(rp.sc + dv * S);
1975        r.sc1 = ldg_nc_s8(rp.sc + dv * S + 4);
1976        r.d = ldg_nc_u16(rp.d + dv * S);
1977        return r;
1978    }
1979    __device__ static int xb(int iqs) { return 4 * (iqs / 16) + (iqs % 16) / 8; }
1980    __device__ static int xp(int iqs) { return iqs % 8; }
1981    template <int NC, bool FAST, class X>
1982    __device__ static void applyr(const WR& r, const X& x, const int* qb, const float* db, int kby, int iqs, float (&out)[NC]) {
1983        const int vh = r.vh >> (2 * ((iqs % 16) / 8));
1984        int u[2][NC];
1985        float d8[2][NC];
1986#pragma unroll
1987        for (int i = 0; i < 2; ++i) {
1988            x.qat(qb + 2 * i * X::QB, u[i]);
1989            x.dat(db + 2 * i * X::DB, d8[i]);
1990        }
1991        const float d = __half2float(__ushort_as_half((unsigned short) r.d));
1992#pragma unroll
1993        for (int c = 0; c < NC; ++c) {
1994            const int uc[2] = {u[0][c], u[1][c]};
1995            const float dc[2] = {d8[0][c], d8[1][c]};
1996            out[c] = FAST ? q6_q8_dot_fast(r.vl, vh, uc, r.sc0, r.sc1, d, dc) : q6_q8_dot_sc(r.vl, vh, uc, r.sc0, r.sc1, d, dc);
1997        }
1998    }
1999};
2000
2001// P1: native_mmvq_il_kernel with every weight load of a group (the 4 virtual warps x R rows) issued
2002// before any of the group's dots - the four `if (kbx < bpr)` sections of the kernel below each sit behind their own
2003// branch, so a warp had one 2-row x 1-block group in flight (ncu: 432 GB/s on the qkv Q6_K matrix).  The addresses are
2004// clamped to the row's last block (a tail re-reads it; its dot is skipped), and with DB the next group's loads are
2005// issued before this group's dots (two register sets, ping-pong, no copies).  The per-lane accumulation order is the
2006// kernel below's: acc[v] += block(4m + v) in ascending m, ((acc0 + acc1) + acc2) + acc3, warp_sum - the same bits.
2007// STRATA_MMVQ_IL_PF=1: hoisted group loads (4 blocks a SM); =3: + P2's exact integer forms (the traits' applyr<FAST>);
2008// =4: as 3 at 5 blocks a SM; =2 / =5: as 3 / 4 with the ring (DB 2: a section's registers reloaded with the next group's
2009// blocks right after its dots); unset / 0: the kernel below.
2010template <typename I, int NC, int R, int DB, int MINB, bool FAST>
2011__launch_bounds__(4 * WARP, MINB)
2012__global__ void native_mmvq_il_pf_kernel(const typename I::F::Block* __restrict__ w, const int* __restrict__ xq,
2013                                         const float* __restrict__ xd, float* __restrict__ y, int n_in, int n_out) {
2014    using F = typename I::F;
2015    using WR = typename I::WR;
2016    constexpr int SUB = WARP / F::T;   // weight blocks a chunk covers
2017    const int lane = int(threadIdx.x) & (WARP - 1);
2018    const auto x = q8_1_cols<NC, I::PM>(xq, xd, n_in / Q8K);
2019    using X = std::remove_const_t<decltype(x)>;
2020    const int bpr = n_in / F::DIV;
2021    const int kqs = F::kqs(lane);
2022    const int sub = lane / F::T;
2023    const int nm = (bpr + SUB - 1) / SUB;
2024    for (int grp = int(blockIdx.x) * 4 + (int(threadIdx.x) >> 5); grp * R < n_out; grp += int(gridDim.x) * 4) {
2025        const int row0 = grp * R;
2026        typename I::RP wr[R];
2027#pragma unroll
2028        for (int i = 0; i < R; ++i) wr[i] = I::rowptrs(w + std::size_t(min(row0 + i, n_out - 1)) * bpr, kqs);   // a partial last group recomputes its last row
2029        float acc[4][R][NC];
2030#pragma unroll
2031        for (int v = 0; v < 4; ++v)
2032#pragma unroll
2033            for (int i = 0; i < R; ++i)
2034#pragma unroll
2035                for (int c = 0; c < NC; ++c) acc[v][i][c] = 0.0f;
2036        // the groups whose four chunks are whole blocks for every lane run with no branch at all (ptxas sinks a load
2037        // whose only use sits behind a branch into it, which is what put the scale loads back into the dot sections);
2038        // the tail group clamps its loads and predicates its dots
2039        const int m_full = bpr / SUB;
2040        // a full group's 4 x R blocks: one pointer set per row at the group's first block, the other three at immediates
2041        // (v * SUB blocks on); a clamped (tail) group addresses each block on its own
2042        auto load_group = [&](int m0, bool clamp, WR (&wv)[4][R]) {
2043            if (!clamp) {
2044#pragma unroll
2045                for (int i = 0; i < R; ++i) {
2046                    const typename I::RP p0 = I::at(wr[i], SUB * m0 + sub);
2047#pragma unroll
2048                    for (int v = 0; v < 4; ++v) wv[v][i] = I::loadr(p0, v * SUB);
2049                }
2050            } else {
2051#pragma unroll
2052                for (int v = 0; v < 4; ++v) {
2053                    const int kbx = min(SUB * (m0 + v) + sub, bpr - 1);
2054#pragma unroll
2055                    for (int i = 0; i < R; ++i) wv[v][i] = I::loadr(I::at(wr[i], kbx), 0);
2056                }
2057            }
2058        };
2059        // the lane's activation ints and scales of the group's first chunk; a section's are an immediate on
2060        const int* xq0 = x.qbase(I::xb(kqs) + sub * F::KBY, I::xp(kqs));
2061        const float* xd0 = x.dbase(I::xb(kqs) + sub * F::KBY);
2062        auto dot_group = [&](int m0, bool pred, const WR (&wv)[4][R]) {
2063            const int* qg = static_cast<const int*>(madw(xq0, SUB * m0 * F::KBY, X::QB * 4));
2064            const float* dg = static_cast<const float*>(madw(xd0, SUB * m0 * F::KBY, X::DB * 4));
2065#pragma unroll
2066            for (int v = 0; v < 4; ++v) {
2067                const int kbx = SUB * (m0 + v) + sub;
2068                if (!pred || kbx < bpr) {
2069#pragma unroll
2070                    for (int i = 0; i < R; ++i) {
2071                        float o[NC];
2072                        I::template applyr<NC, FAST>(wv[v][i], x, qg + v * SUB * F::KBY * X::QB, dg + v * SUB * F::KBY * X::DB,
2073                                                     kbx * F::KBY, kqs, o);
2074#pragma unroll
2075                        for (int c = 0; c < NC; ++c) acc[v][i][c] += o[c];
2076                    }
2077                }
2078            }
2079        };
2080        int m0 = 0;
2081        if constexpr (DB == 0) {
2082            for (; m0 + 4 <= m_full; m0 += 4) {
2083                WR wv[4][R];
2084                load_group(m0, false, wv);
2085                dot_group(m0, false, wv);
2086            }
2087        } else if constexpr (DB == 2) {
2088            // a ring: after a section's dots its registers take the next group's blocks of that section, so the warp
2089            // always has about a group's worth of loads in flight at the register cost of one group (the loads sit
2090            // behind a uniform branch whose consumers are in the next iteration, so nothing can sink)
2091            WR wv[4][R];
2092            if (m0 + 4 <= m_full) load_group(0, false, wv);
2093            for (; m0 + 4 <= m_full; m0 += 4) {
2094                const bool more = m0 + 8 <= m_full;
2095                typename I::RP pn[R];
2096                if (more) {
2097#pragma unroll
2098                    for (int i = 0; i < R; ++i) pn[i] = I::at(wr[i], SUB * (m0 + 4) + sub);
2099                }
2100                const int* qg = static_cast<const int*>(madw(xq0, SUB * m0 * F::KBY, X::QB * 4));
2101                const float* dg = static_cast<const float*>(madw(xd0, SUB * m0 * F::KBY, X::DB * 4));
2102#pragma unroll
2103                for (int v = 0; v < 4; ++v) {
2104                    const int kbx = SUB * (m0 + v) + sub;
2105#pragma unroll
2106                    for (int i = 0; i < R; ++i) {
2107                        float o[NC];
2108                        I::template applyr<NC, FAST>(wv[v][i], x, qg + v * SUB * F::KBY * X::QB, dg + v * SUB * F::KBY * X::DB,
2109                                                     kbx * F::KBY, kqs, o);
2110#pragma unroll
2111                        for (int c = 0; c < NC; ++c) acc[v][i][c] += o[c];
2112                    }
2113                    if (more) {
2114#pragma unroll
2115                        for (int i = 0; i < R; ++i) wv[v][i] = I::loadr(pn[i], v * SUB);
2116                    }
2117                }
2118            }
2119        } else {   // two register sets: a group's loads issue before the previous group's dots; no branch inside the loop
2120            WR wa[4][R], wb[4][R];
2121            if (m0 + 4 <= m_full) load_group(0, false, wa);
2122            for (; m0 + 12 <= m_full; m0 += 8) {
2123                load_group(m0 + 4, false, wb);
2124                dot_group(m0, false, wa);
2125                load_group(m0 + 8, false, wa);
2126                dot_group(m0 + 4, false, wb);
2127            }
2128            if (m0 + 8 <= m_full) {
2129                load_group(m0 + 4, false, wb);
2130                dot_group(m0, false, wa);
2131                dot_group(m0 + 4, false, wb);
2132                m0 += 8;
2133            } else if (m0 + 4 <= m_full) {
2134                dot_group(m0, false, wa);
2135                m0 += 4;
2136            }
2137        }
2138        if (m0 < nm) {
2139            WR wv[4][R];
2140            load_group(m0, true, wv);
2141            dot_group(m0, true, wv);
2142        }
2143#pragma unroll
2144        for (int i = 0; i < R; ++i)
2145#pragma unroll
2146            for (int c = 0; c < NC; ++c) {
2147                float s = acc[0][i][c];
2148                s += acc[1][i][c];
2149                s += acc[2][i][c];
2150                s += acc[3][i][c];
2151                s = warp_sum(s);
2152                if (lane == 0 && row0 + i < n_out) y[std::size_t(c) * n_out + row0 + i] = s;
2153            }
2154    }
2155}
2156
2157// NOUT < NC (BW-NEXT, STRATA_IL_PAD): the kernel of NC columns computes a column that is not wanted and stores only the first NOUT; each column's value is
2158// its own sum, so the stored ones are bitwise those of the NOUT-column kernel.  5 columns of IQ4_XS run as 6 (the 5-column instantiation is 15-40% slower).
2159template <typename I, int NC, int R, int NOUT = NC>
2160__launch_bounds__(4 * WARP)
2161__global__ void native_mmvq_il_kernel(const typename I::F::Block* __restrict__ w, const int* __restrict__ xq,
2162                                      const float* __restrict__ xd, float* __restrict__ y, int n_in, int n_out) {
2163    using F = typename I::F;
2164    constexpr int SUB = WARP / F::T;   // weight blocks a chunk covers
2165    const int lane = int(threadIdx.x) & (WARP - 1);
2166    const auto x = q8_1_cols<NC, I::PM>(xq, xd, n_in / Q8K);
2167    const int bpr = n_in / F::DIV;
2168    const int kqs = F::kqs(lane);
2169    const int nm = (bpr + SUB - 1) / SUB;
2170    // A grid-stride loop over the row groups, though the grid gives each warp one: without it ptxas gives several
2171    // instances fewer registers (the fork measured Q6_K's at 3 columns 10-50% slower).
2172    for (int grp = int(blockIdx.x) * 4 + (int(threadIdx.x) >> 5); grp * R < n_out; grp += int(gridDim.x) * 4) {
2173        const int row0 = grp * R;
2174        float acc[4][R][NC];
2175#pragma unroll
2176        for (int v = 0; v < 4; ++v)
2177#pragma unroll
2178            for (int i = 0; i < R; ++i)
2179#pragma unroll
2180                for (int c = 0; c < NC; ++c) acc[v][i][c] = 0.0f;
2181        for (int m0 = 0; m0 < nm; m0 += 4) {
2182#pragma unroll
2183            for (int v = 0; v < 4; ++v) {
2184                const int kbx = SUB * (m0 + v) + lane / F::T;
2185                if (kbx < bpr) {
2186#pragma unroll
2187                    for (int i = 0; i < R; ++i) {
2188                        const int row = min(row0 + i, n_out - 1);   // a partial last group recomputes its last row
2189                        const typename F::W wv = F::load(w + std::size_t(row) * bpr + kbx, kqs);
2190                        float o[NC];
2191                        I::template apply<NC>(wv, x, kbx * F::KBY, kqs, o);
2192#pragma unroll
2193                        for (int c = 0; c < NC; ++c) acc[v][i][c] += o[c];
2194                    }
2195                }
2196            }
2197        }
2198#pragma unroll
2199        for (int i = 0; i < R; ++i)
2200#pragma unroll
2201            for (int c = 0; c < NC; ++c) {
2202                float s = acc[0][i][c];
2203                s += acc[1][i][c];
2204                s += acc[2][i][c];
2205                s += acc[3][i][c];
2206                s = warp_sum(s);
2207                if (c < NOUT && lane == 0 && row0 + i < n_out) y[std::size_t(c) * n_out + row0 + i] = s;
2208            }
2209    }
2210}
2211
2212int g_il_pf = -1;   // native_mmvq_il_pf (tests, benchmarks): the variant for every launch; -1: STRATA_MMVQ_IL_PF
2213int il_pf_env() {
2214    static const int env = [] { const char* v = std::getenv("STRATA_MMVQ_IL_PF"); return v ? std::atoi(v) : 0; }();
2215    return env;
2216}
2217int il_pf_table(int type, int ncols, int n_out);   // the sm_80 table below: pf << 4 | rows, 0 = today's kernel and table
2218// the variant of one launch (g_il_pf, else STRATA_MMVQ_IL_PF: 0 / unset today's kernel, 1 the measured table, 2-6 that
2219// variant for every type and shape), and with the table its rows a warp (0: the rows table's)
2220int il_pf_for(int type, int ncols, int n_out, int* rows) {
2221    *rows = 0;
2222    if (g_il_pf >= 0) return g_il_pf;
2223    const int env = il_pf_env();
2224    if (env != 1) return env;
2225    const int t = il_pf_table(type, ncols, n_out);
2226    *rows = t & 15;
2227    return t >> 4;
2228}
2229// one (type, columns, rows) launch: today's kernel, or the variant il_pf_for names for a type that has them
2230template <typename I, int NC, int R, int NOUT = NC>
2231void launch_il_one(unsigned blocks, const typename I::F::Block* w, const int* xq, const float* xd, float* y, int n_in, int n_out,
2232                   cudaStream_t s, int pf) {
2233    if constexpr (I::HAS_PF && NOUT == NC) {
2234        switch (pf) {
2235        case 6: native_mmvq_il_pf_kernel<I, NC, R, 0, 4, false><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return;
2236        case 2: native_mmvq_il_pf_kernel<I, NC, R, 2, 4, true><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return;
2237        case 3: native_mmvq_il_pf_kernel<I, NC, R, 0, 4, true><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return;
2238        case 4: native_mmvq_il_pf_kernel<I, NC, R, 0, 5, true><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return;
2239        case 5: native_mmvq_il_pf_kernel<I, NC, R, 2, 5, true><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out); return;
2240        default: break;
2241        }
2242    }
2243    native_mmvq_il_kernel<I, NC, R, NOUT><<<blocks, 4 * WARP, 0, s>>>(w, xq, xd, y, n_in, n_out);
2244}
2245
2246// STRATA_IL_PAD (bit 0: IQ4_XS 5 columns as 6; default on, 0 off): bitwise, see native_mmvq_il_kernel
2247int il_pad() {
2248    static const int v = [] { const char* e = std::getenv("STRATA_IL_PAD"); return e != nullptr ? std::atoi(e) : 1; }();
2249    return v;
2250}
2251
2252template <typename I, int R>
2253void launch_il(const void* weights, const void* x_il, float* y, int n_in, int n_out, int ncols, cudaStream_t s, int pf) {
2254    const auto* w = static_cast<const typename I::F::Block*>(weights);
2255    const unsigned blocks = unsigned(((n_out + R - 1) / R + 3) / 4);
2256    if (ncols == 1) {   // 143-dense: one column reads the plain q8_1 blocks (x_il is then the caller's x_q8_1)
2257        launch_il_one<I, 1, R>(blocks, w, static_cast<const int*>(x_il), nullptr, y, n_in, n_out, s, pf);
2258        return;
2259    }
2260    const Q81IlParts parts = q8_1_il_parts(x_il, n_in, ncols);
2261    const int* xq = I::PM ? parts.pm : parts.bm;
2262    const float* xd = parts.d;
2263    switch (ncols) {
2264#define STRATA_IL_CASE(N) case N: launch_il_one<I, N, R>(blocks, w, xq, xd, y, n_in, n_out, s, pf); break;
2265        STRATA_IL_CASE(2) STRATA_IL_CASE(3) STRATA_IL_CASE(4)
2266#undef STRATA_IL_CASE
2267        // 147-verify: 5..8 columns (the cp = 8 copy) at 1 or 2 rows a warp; launch_il_rows maps 4 rows to 2 there
2268#define STRATA_IL_CASE(N) case N: if constexpr (R <= 2) launch_il_one<I, N, R>(blocks, w, xq, xd, y, n_in, n_out, s, pf); break;
2269        STRATA_IL_CASE(6) STRATA_IL_CASE(7) STRATA_IL_CASE(8)
2270#undef STRATA_IL_CASE
2271    case 5:
2272        if constexpr (R <= 2) {
2273            if constexpr (std::is_same_v<I, IlIQ4XS>) {
2274                if ((il_pad() & 1) != 0) { launch_il_one<I, 6, R, 5>(blocks, w, xq, xd, y, n_in, n_out, s, 0); break; }
2275            }
2276            launch_il_one<I, 5, R>(blocks, w, xq, xd, y, n_in, n_out, s, pf);
2277        }
2278        break;
2279        default: throw std::invalid_argument("native_mmvq_il requires 1 <= ncols <= 8");
2280    }
2281}
2282
2283template <typename I>
2284void launch_il_rows(int r, const void* weights, const void* x_il, float* y, int n_in, int n_out, int ncols, cudaStream_t s) {
2285    int pf_rows = 0;
2286    const int pf = il_pf_for(I::F::TYPE, ncols, n_out, &pf_rows);
2287    if (pf_rows != 0) r = pf_rows;   // the pf table measured its rows with its kernel
2288    if (ncols > 4 && r == 4) r = 2;   // 5..8 columns: 1 or 2 rows a warp
2289    switch (r) {
2290    case 1: launch_il<I, 1>(weights, x_il, y, n_in, n_out, ncols, s, pf); break;
2291    case 4: launch_il<I, 4>(weights, x_il, y, n_in, n_out, ncols, s, pf); break;
2292    default: launch_il<I, 2>(weights, x_il, y, n_in, n_out, ncols, s, pf); break;
2293    }
2294}
2295
2296// The interleaved copy (native_mmvq.hpp) of columns already quantized into plain q8_1 blocks, whoever wrote them (the
2297// quantizer, a fused norm): the same bytes, one int of a block a thread.
2298__global__ void native_q8_1_interleave_kernel(const Q81Block* __restrict__ y, int* __restrict__ bm, int* __restrict__ pm,
2299                                              float* __restrict__ dl, int nb, int n_total, int cp) {
2300    const int i = int(blockIdx.x) * 256 + int(threadIdx.x);
2301    if (i >= n_total) return;
2302    const int c = i / (nb * 8), r = i - c * nb * 8, b = r / 8, p = r % 8;
2303    const Q81Block& blk = y[std::size_t(c) * nb + b];
2304    const int q = reinterpret_cast<const int*>(blk.qs)[p];
2305    bm[(std::size_t(b) * 8 + p) * cp + c] = q;
2306    pm[(std::size_t(p) * nb + b) * cp + c] = q;
2307    if (p == 0) dl[std::size_t(b) * cp + c] = __low2float(blk.ds);
2308}
2309
2310// native_quantize_q8_1_kernel and native_q8_1_interleave_kernel in one launch: the same q8_1 blocks, and the
2311// interleaved copy's ints and scales (an int is four codes, gathered from lanes 4p..4p+3 with two shuffles).
2312__global__ void native_quantize_q8_1_il_kernel(const float* __restrict__ x, Q81Block* __restrict__ y,
2313                                               int* __restrict__ bm, int* __restrict__ pm, float* __restrict__ dl,
2314                                               int n_in, int n_total, int cp) {
2315    const int i = int(blockIdx.x) * QUANT_THREADS + int(threadIdx.x);
2316    if (i >= n_total) return;   // n_total is a multiple of 32: only whole warps return
2317    const float xi = x[i];
2318    const float amax = warp_max(fabsf(xi));
2319    const float sum = warp_sum(xi);
2320    const float d = q8_1_finite(amax / 127.0f);
2321    const int8_t q = q8_1_quant(xi, d, amax);
2322    y[i / Q8K].qs[i % Q8K] = q;
2323    const auto ds = q8_1_ds(d, sum);
2324    if (i % Q8K == 0) y[i / Q8K].ds = ds;
2325    const int lane = int(threadIdx.x) & 31;
2326    unsigned v = unsigned(uint8_t(q)) << (8 * (lane & 3));
2327    v |= __shfl_xor_sync(0xffffffffu, v, 1);
2328    v |= __shfl_xor_sync(0xffffffffu, v, 2);
2329    const int nb = n_in / Q8K, c = i / n_in, b = (i - c * n_in) / Q8K, pp = lane >> 2;
2330    if ((lane & 3) == 0) {
2331        bm[(std::size_t(b) * 8 + pp) * cp + c] = int(v);
2332        pm[(std::size_t(pp) * nb + b) * cp + c] = int(v);
2333    }
2334    if (lane == 0) dl[std::size_t(b) * cp + c] = __low2float(ds);
2335}
2336
2337#endif  // !__HIPCC__
2338
2339void validate_shape(int n_in, int ncols, int block_elems = Q8K) {
2340    if (n_in <= 0 || n_in % block_elems != 0) {
2341        throw std::invalid_argument("native MMVQ requires n_in > 0 and divisible by its block element count");
2342    }
2343    if (ncols < 1 || ncols > MAX_NCOLS) throw std::invalid_argument("native MMVQ requires 1 <= ncols <= MAX_NCOLS");
2344}
2345void validate_pointer(const void* p) {
2346    if (!p || reinterpret_cast<std::uintptr_t>(p) % 4 != 0) {
2347        throw std::invalid_argument("native MMVQ requires non-null 4-byte aligned device pointers");
2348    }
2349}
2350void validate_stream(void* stream) {
2351    if (!stream) throw std::invalid_argument("native MMVQ requires an explicit non-null CUDA stream");
2352}
2353void launch_check() {
2354    const auto error = cudaGetLastError();
2355    if (error != cudaSuccess) {
2356        throw std::runtime_error(std::string("native MMVQ launch: ") + cudaGetErrorString(error));
2357    }
2358}
2359
2360
2361#if defined(STRATA_HIP_GFX906)
2362// ---- AMD (wave64) layout: one wavefront per R rows, four wavefronts per block, the row's blocks strided over the
2363// 64 lanes exactly as the CUDA kernels stride them over a block (kbx = lane / T, stride 64 / T), and a 64-lane
2364// butterfly instead of the LDS partials and __syncthreads of the one-block-per-row layout: on gfx906 a block per
2365// 2 KB row spent most of its time being launched and joined.  The SAME kernel serves every column count 1..8, so a
2366// column's sums do not depend on how many columns (verify tokens) ride along.  STRATA_MMVQ_WAVE=0: the CUDA layout.
2367bool g_wave_off = std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0";
2368template<typename F, int NCOLS, int R>
2369__launch_bounds__(256)
2370__global__ void native_mmvq_wave_kernel(const typename F::Block* __restrict__ w, const Q81Block* __restrict__ x,
2371                                        float* __restrict__ y, int n_in, int n_out) {
2372    constexpr int BPIW = 64 / F::T;
2373    static_assert(64 % F::T == 0, "a block's threads must tile the wavefront");
2374    const int lane = int(threadIdx.x) & 63;
2375    const int row0 = (int(blockIdx.x) * 4 + (int(threadIdx.x) >> 6)) * R;
2376    if (row0 >= n_out) return;
2377    const int blocks_per_row = n_in / F::DIV;
2378    const int x_stride = n_in / Q8K;
2379    const int kqs = F::kqs(lane);
2380    float tmp[NCOLS][R] = {};
2381    for (int kbx = lane / F::T; kbx < blocks_per_row; kbx += BPIW) {
2382        const int kby = kbx * F::KBY;
2383#pragma unroll
2384        for (int i = 0; i < R; ++i) {
2385            if (row0 + i < n_out) {
2386                const typename F::W wv = F::load(w + std::size_t(row0 + i) * blocks_per_row + kbx, kqs);
2387#pragma unroll
2388                for (int j = 0; j < NCOLS; ++j) tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);
2389            }
2390        }
2391    }
2392#pragma unroll
2393    for (int j = 0; j < NCOLS; ++j)
2394#pragma unroll
2395        for (int i = 0; i < R; ++i) {
2396            float v = tmp[j][i];
2397#pragma unroll
2398            for (int off = 32; off > 0; off >>= 1) v += __shfl_xor(v, off, 64);
2399            if (lane == 0 && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = v;
2400        }
2401}
2402template<typename F, int NCOLS>
2403void wave_launch_n(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, cudaStream_t s) {
2404    const auto* w = static_cast<const typename F::Block*>(weights);
2405    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2406    constexpr int R = 1;
2407    const unsigned blocks = unsigned((std::size_t(n_out) + 4 * R - 1) / (4 * R));
2408    native_mmvq_wave_kernel<F, NCOLS, R><<<blocks, 256, 0, s>>>(w, x, y, n_in, n_out);
2409}
2410template<typename F>
2411void wave_launch(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
2412    const auto s = static_cast<cudaStream_t>(stream);
2413    switch (ncols) {
2414        case 1: wave_launch_n<F, 1>(weights, x_q8_1, y, n_in, n_out, s); break;
2415        case 2: wave_launch_n<F, 2>(weights, x_q8_1, y, n_in, n_out, s); break;
2416        case 3: wave_launch_n<F, 3>(weights, x_q8_1, y, n_in, n_out, s); break;
2417        case 4: wave_launch_n<F, 4>(weights, x_q8_1, y, n_in, n_out, s); break;
2418        case 5: wave_launch_n<F, 5>(weights, x_q8_1, y, n_in, n_out, s); break;
2419        case 6: wave_launch_n<F, 6>(weights, x_q8_1, y, n_in, n_out, s); break;
2420        case 7: wave_launch_n<F, 7>(weights, x_q8_1, y, n_in, n_out, s); break;
2421        case 8: wave_launch_n<F, 8>(weights, x_q8_1, y, n_in, n_out, s); break;
2422#if STRATA_VERIFY_MAX_T > 8
2423        case 9: wave_launch_n<F, 9>(weights, x_q8_1, y, n_in, n_out, s); break;
2424        case 10: wave_launch_n<F, 10>(weights, x_q8_1, y, n_in, n_out, s); break;
2425        case 11: wave_launch_n<F, 11>(weights, x_q8_1, y, n_in, n_out, s); break;
2426        case 12: wave_launch_n<F, 12>(weights, x_q8_1, y, n_in, n_out, s); break;
2427#if STRATA_VERIFY_MAX_T > 12
2428        case 13: wave_launch_n<F, 13>(weights, x_q8_1, y, n_in, n_out, s); break;
2429        case 14: wave_launch_n<F, 14>(weights, x_q8_1, y, n_in, n_out, s); break;
2430        case 15: wave_launch_n<F, 15>(weights, x_q8_1, y, n_in, n_out, s); break;
2431        case 16: wave_launch_n<F, 16>(weights, x_q8_1, y, n_in, n_out, s); break;
2432#endif
2433#endif
2434        default: throw std::invalid_argument("native MMVQ (wave) requires 1 <= ncols <= MAX_NCOLS");
2435    }
2436}
2437#define STRATA_WAVE_MMVQ(...) \
2438    if (!g_wave_off) { wave_launch<__VA_ARGS__>(weights, x_q8_1, y, n_in, n_out, ncols, stream); launch_check(); return; }
2439#else
2440#define STRATA_WAVE_MMVQ(...)
2441#endif
2442
2443template<typename Weight, int Qi>
2444void small_mmvq(const void* weights, const void* x_q8_1, float* y,
2445                int n_in, int n_out, int ncols, void* stream) {
2446    validate_shape(n_in, ncols, 32);
2447    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
2448    validate_pointer(weights);
2449    validate_pointer(x_q8_1);
2450    validate_pointer(y);
2451    validate_stream(stream);
2452    STRATA_WAVE_MMVQ(SmallTraits<Weight, Qi>)
2453    if (ncols > 1) {
2454        launch_multi<SmallTraits<Weight, Qi>>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
2455        launch_check();
2456        return;
2457    }
2458    const auto* w = static_cast<const Weight*>(weights);
2459    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2460    const auto s = static_cast<cudaStream_t>(stream);
2461    const dim3 threads(WARP, WARPS);
2462    if (n_in / 32 < 2 * WARPS * WARP / Qi) {
2463        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
2464        native_small_mmvq_kernel<Weight, Qi, true><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);
2465    } else {
2466        native_small_mmvq_kernel<Weight, Qi, false><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);
2467    }
2468    launch_check();
2469}
2470
2471template<typename Weight, int Qi>
2472void small_f32(const void* weights, const float* x, void* scratch_q8_1,
2473               float* y, int n_in, int n_out, int ncols, void* stream) {
2474    validate_shape(n_in, ncols, 32);
2475    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
2476    validate_pointer(weights);
2477    validate_pointer(x);
2478    validate_pointer(scratch_q8_1);
2479    validate_pointer(y);
2480    validate_stream(stream);
2481    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
2482    small_mmvq<Weight, Qi>(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
2483}
2484
2485// STRATA_Q8_SM60=1 (opt-in, written for Pascal GP100): every Q8_0 dense matrix and the head get the packed planes
2486// below and run q8sm60::kernel on them (q8_sm60.cuh) instead of the exact kernels.
2487bool q8_sm60_on() {
2488#if defined(__HIPCC__)
2489    return false;   // a CUDA kernel for one NVIDIA chip: HIP builds never compile it
2490#else
2491    static const bool on = [] {
2492        const char* v = std::getenv("STRATA_Q8_SM60");
2493        const bool yes = v && v[0] == '1' && v[1] == '\0';
2494        if (yes) std::fprintf(stderr, "strata q8 sm60: Q8_0 decode GEMVs on the Pascal kernel (STRATA_Q8_SM60=1)\n");
2495        return yes;
2496    }();
2497    return on;
2498#endif
2499}
2500#if !defined(__HIPCC__)
2501#include "q8_sm60.cuh"
2502#endif
2503
2504// ============================ STRATA_Q8_PACKED=1: the packed Q8_0 decode layout (opt-in) ============================
2505//
2506// A lossless load-time repack of a Q8_0 matrix: the SAME int8 values in a qs plane (row-major, n_in bytes per row)
2507// followed by the SAME fp16 scales in a d plane (row-major, n_in / 32 per row) - no requantization, same bytes.
2508// The GGUF's 34-byte blocks leave every int 2-byte aligned (load_int_b2 = two 16-bit loads); the planes give each
2509// thread one aligned 8-byte run, read with streaming (non-temporal) loads. Every thread owns exactly the bytes of
2510// the ncols = 1 / multi-column EXACT layout (block kbx = tid / 4 + 32 i, ints 2 (tid % 4) and +1), accumulates them
2511// in the same order with the same expression, and the cross-warp sum and XOR tree are the same: every output is
2512// BITWISE equal to native_small_mmvq_kernel / native_mmvq_multi_kernel<SmallTraits<Q80Block, 8>, NC, 4, 1>.
2513// Eligible: 1024 <= n_in <= 4096 and n_out >= 2048, run as 640 persistent workgroups (a grid-stride over rows, two
2514// partial buffers). Measured on gfx1151 (S26, 8 real UD-IQ4_XS layers per shape, paired, 1-5 columns): 2560 ->
2515// 6144/10240/12288 +10-12% per call (engine trace: -10.7% on those calls). 6144 -> 2560 (one workgroup per row)
2516// was +2-4% standalone but -3% in the engine, and rows < 2048 lose: neither is packed.
2517#if defined(__HIPCC__)
2518#define STRATA_Q8P_LOAD(p) __builtin_nontemporal_load(p)
2519#else
2520#define STRATA_Q8P_LOAD(p) __ldcs(p)
2521#endif
2522constexpr int Q8P_PERSIST_GRID = 640;
2523constexpr int Q8P_PERSIST_MAX_IN = 4096;
2524
2525template<int NCOLS, bool TS = false>
2526__launch_bounds__(WARPS * WARP, 1)
2527__global__ void native_q8_0_packed_kernel(const int8_t* __restrict__ qs, const half* __restrict__ dpl,
2528                                          const Q81Block* __restrict__ x, float* __restrict__ y,
2529                                          int n_in, int n_out, int row_step) {
2530    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
2531    const int nb = n_in / 32;
2532    const int kqs = 2 * (tid % 4);
2533    __shared__ float partial[2][WARPS - 1][NCOLS][WARP];
2534    int buf = 0;
2535    for (int row = int(blockIdx.x); row < n_out; row += row_step, buf ^= 1) {
2536        float tmp[NCOLS] = {};
2537        for (int kbx = tid / 4; kbx < nb; kbx += 2 * WARPS * WARP / 8) {
2538            const std::size_t block = std::size_t(row) * nb + kbx;
2539            const int* p = reinterpret_cast<const int*>(qs + block * 32) + kqs;
2540            const int v0 = STRATA_Q8P_LOAD(p);
2541            const int v1 = STRATA_Q8P_LOAD(p + 1);
2542            const float d0 = dpl[block];
2543#pragma unroll
2544            for (int j = 0; j < NCOLS; ++j) {
2545                const Q81Block* xb = x + std::size_t(j) * nb + kbx;
2546                const int* u = reinterpret_cast<const int*>(xb->qs);
2547                int sumi = 0;
2548                sumi = STRATA_DP4A(v0, u[kqs], sumi);
2549                sumi = STRATA_DP4A(v1, u[kqs + 1], sumi);
2550                const float d1 = __low2float(xb->ds);
2551                tmp[j] += d0 * d1 * float(sumi);
2552            }
2553        }
2554        if (threadIdx.y > 0) {
2555#pragma unroll
2556            for (int j = 0; j < NCOLS; ++j) partial[buf][threadIdx.y - 1][j][threadIdx.x] = tmp[j];
2557        }
2558        __syncthreads();
2559        if (TS && threadIdx.y == 0) {   // S26 STRATA_TSUM=1: one transposed butterfly, bitwise the same sums
2560            constexpr int P = s26ts::pow2_ceil(NCOLS);
2561            float v[P];
2562#pragma unroll
2563            for (int j = 0; j < NCOLS; ++j) {
2564#pragma unroll
2565                for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x];
2566                v[j] = tmp[j];
2567            }
2568#pragma unroll
2569            for (int j = NCOLS; j < P; ++j) v[j] = 0.0f;
2570            const float sum = s26ts::tsum<P>(v, int(threadIdx.x));
2571            const int j = s26ts::tsum_token<P>(int(threadIdx.x));
2572            if (int(threadIdx.x) == s26ts::tsum_lane<P>(j) && j < NCOLS) y[std::size_t(j) * n_out + row] = sum;
2573        } else if (threadIdx.y == 0) {
2574#pragma unroll
2575            for (int j = 0; j < NCOLS; ++j) {
2576#pragma unroll
2577                for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x];
2578                tmp[j] = warp_sum(tmp[j]);
2579                if (threadIdx.x == 0) y[std::size_t(j) * n_out + row] = tmp[j];
2580            }
2581        }
2582    }
2583}
2584
2585struct Q8Packed { const int8_t* qs; const half* d; int n_in, n_out; };
2586std::unordered_map<const void*, Q8Packed>& q8_packed_registry() {
2587    static std::unordered_map<const void*, Q8Packed> registry;
2588    return registry;
2589}
2590
2591template<int NCOLS>
2592void q8_packed_launch(const Q8Packed& w, const Q81Block* x, float* y, cudaStream_t s) {
2593    const bool persist = w.n_in <= Q8P_PERSIST_MAX_IN;
2594    const int grid = persist ? (std::min)(w.n_out, Q8P_PERSIST_GRID) : w.n_out;
2595    if (s26_tsum_on())
2596        native_q8_0_packed_kernel<NCOLS, true><<<unsigned(grid), dim3(WARP, WARPS), 0, s>>>(w.qs, w.d, x, y, w.n_in, w.n_out,
2597                                                                                          persist ? grid : w.n_out);
2598    else
2599        native_q8_0_packed_kernel<NCOLS><<<unsigned(grid), dim3(WARP, WARPS), 0, s>>>(w.qs, w.d, x, y, w.n_in, w.n_out,
2600                                                                                    persist ? grid : w.n_out);
2601}
2602
2603bool q8_packed_shape(int n_in, int n_out) {   // the shapes native_q8_0_packed_kernel was measured on
2604    return n_in > 0 && n_in % 32 == 0 && n_in / 32 >= 2 * WARPS * WARP / 8 && n_in <= Q8P_PERSIST_MAX_IN &&
2605           n_out >= 2048;
2606}
2607
2608bool q8_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
2609    auto& registry = q8_packed_registry();
2610#if !defined(__HIPCC__)
2611    if (q8_sm60_on() && !registry.empty()) {
2612        const auto found = registry.find(weights);
2613        if (found != registry.end() && found->second.n_in == n_in && found->second.n_out == n_out) {
2614            validate_pointer(x_q8_1);
2615            validate_pointer(y);
2616            validate_stream(stream);
2617            // (the kernel takes at most q8sm60::MAX_COLS columns; a 9..16-row window is run in passes, each column bitwise
2618            // the one-column result, as native_mmvq does for more than MAX_NCOLS)
2619            bool all = true;
2620            for (int j = 0; all && j < ncols; j += q8sm60::MAX_COLS) {
2621                const int nj = ncols - j < q8sm60::MAX_COLS ? ncols - j : q8sm60::MAX_COLS;
2622                all = q8sm60::launch(found->second.qs, found->second.d,
2623                                     static_cast<const Q81Block*>(x_q8_1) + std::size_t(j) * std::size_t(n_in / Q8K),
2624                                     y + std::size_t(j) * std::size_t(n_out), n_in, n_out, nj, static_cast<cudaStream_t>(stream));
2625            }
2626            if (all) {
2627                launch_check();
2628                return true;
2629            }
2630            // a shape the Pascal kernel declines: the exact packed kernel only where it was measured, else the GGUF layout
2631            if (!q8_packed_shape(n_in, n_out)) return false;
2632        }
2633    }
2634#endif
2635    if (registry.empty() || (ncols > 1 && !g_multi_exact)) return false;   // packed = the EXACT layout only
2636    const auto found = registry.find(weights);
2637    if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false;
2638    validate_shape(n_in, ncols, 32);
2639    validate_pointer(x_q8_1);
2640    validate_pointer(y);
2641    validate_stream(stream);
2642    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2643    const auto s = static_cast<cudaStream_t>(stream);
2644    switch (ncols) {
2645        case 1: q8_packed_launch<1>(found->second, x, y, s); break;
2646        case 2: q8_packed_launch<2>(found->second, x, y, s); break;
2647        case 3: q8_packed_launch<3>(found->second, x, y, s); break;
2648        case 4: q8_packed_launch<4>(found->second, x, y, s); break;
2649        case 5: q8_packed_launch<5>(found->second, x, y, s); break;
2650        case 6: q8_packed_launch<6>(found->second, x, y, s); break;
2651        case 7: q8_packed_launch<7>(found->second, x, y, s); break;
2652        case 8: q8_packed_launch<8>(found->second, x, y, s); break;
2653#if STRATA_VERIFY_MAX_T > 8
2654        case 9: q8_packed_launch<9>(found->second, x, y, s); break;
2655        case 10: q8_packed_launch<10>(found->second, x, y, s); break;
2656        case 11: q8_packed_launch<11>(found->second, x, y, s); break;
2657        case 12: q8_packed_launch<12>(found->second, x, y, s); break;
2658#if STRATA_VERIFY_MAX_T > 12
2659        case 13: q8_packed_launch<13>(found->second, x, y, s); break;
2660        case 14: q8_packed_launch<14>(found->second, x, y, s); break;
2661        case 15: q8_packed_launch<15>(found->second, x, y, s); break;
2662        case 16: q8_packed_launch<16>(found->second, x, y, s); break;
2663#endif
2664#endif
2665        default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= MAX_NCOLS");
2666    }
2667    launch_check();
2668    return true;
2669}
2670
2671
2672// ============================ STRATA_Q6_PACKED=1: the packed Q6_K head layout (opt-in) ============================
2673//
2674// The output heads (the main head, 248320 rows, and the MTP draft head's row subset) are Q6_K matrices of 2560-wide
2675// rows: 10 blocks of 210 bytes each, so every int load is 2-byte aligned and a row is 2100 bytes. The packed copy
2676// holds the SAME bytes as four planes - ql (128 B per block), qh (64 B), scales (16 B), d (2 B) - so a thread's
2677// two words are aligned dword loads (non-temporal). Thread ownership (block tid / 32 + 4 i, word tid % 32), the
2678// q6_q8_dot_impl expression, the per-thread order and the reduction are those of native_q6_k_mmvq_kernel<false> /
2679// native_mmvq_multi_kernel<Q6KTraits, NC, 4, 1>: every output is bitwise equal. Persistent workgroups.
2680int g_q6p_grid_override = 0;   // the self-test's grid sweep (STRATA_Q6P_SELFTEST=2)
2681int q6p_grid() {
2682    if (g_q6p_grid_override > 0) return g_q6p_grid_override;
2683    static const int grid = [] {
2684        const char* v = std::getenv("STRATA_Q6P_GRID");
2685        const int g = v ? std::atoi(v) : 0;
2686        return g > 0 ? g : 640;
2687    }();
2688    return grid;
2689}
2690
2691template<int NCOLS, bool TS = false>
2692__launch_bounds__(WARPS * WARP, 1)
2693__global__ void native_q6_k_packed_kernel(const int* __restrict__ ql, const int* __restrict__ qh,
2694                                          const int8_t* __restrict__ sc, const half* __restrict__ dpl,
2695                                          const Q81Block* __restrict__ x, float* __restrict__ y,
2696                                          int n_in, int n_out, int row_step) {
2697    const int tid = WARP * int(threadIdx.y) + int(threadIdx.x);
2698    const int nb = n_in / 256;
2699    const int x_stride = n_in / Q8K;
2700    const int iqs = tid % 32;
2701    const int bq8_offset = 4 * (iqs / 16) + (iqs % 16) / 8;
2702    const int scale_offset = 8 * (iqs / 16) + (iqs % 16) / 4;
2703    const int vh_shift = 2 * ((iqs % 16) / 8);
2704    const int qh_word = 8 * (iqs / 16) + iqs % 8;
2705    __shared__ float partial[2][WARPS - 1][NCOLS][WARP];
2706    int buf = 0;
2707    for (int row = int(blockIdx.x); row < n_out; row += row_step, buf ^= 1) {
2708        float tmp[NCOLS] = {};
2709        for (int kbx = tid / 32; kbx < nb; kbx += WARPS * WARP / 32) {
2710            const std::size_t block = std::size_t(row) * nb + kbx;
2711            const int vl = STRATA_Q8P_LOAD(ql + block * 32 + iqs);
2712            const int vh = STRATA_Q8P_LOAD(qh + block * 16 + qh_word) >> vh_shift;
2713            const int8_t* scales = sc + block * 16 + scale_offset;
2714            const float d = dpl[block];
2715            const int kby = kbx * 8;
2716#pragma unroll
2717            for (int j = 0; j < NCOLS; ++j) {
2718                const Q81Block* xb = x + std::size_t(j) * x_stride + kby;
2719                int u[2];
2720                float d8[2];
2721#pragma unroll
2722                for (int i = 0; i < 2; ++i) {
2723                    u[i] = reinterpret_cast<const int*>(xb[bq8_offset + 2 * i].qs)[iqs % 8];
2724                    d8[i] = __low2float(xb[bq8_offset + 2 * i].ds);
2725                }
2726                tmp[j] += q6_q8_dot_impl(vl, vh, u, scales, d, d8);
2727            }
2728        }
2729        if (threadIdx.y > 0) {
2730#pragma unroll
2731            for (int j = 0; j < NCOLS; ++j) partial[buf][threadIdx.y - 1][j][threadIdx.x] = tmp[j];
2732        }
2733        __syncthreads();
2734        if (TS && threadIdx.y == 0) {   // S26 STRATA_TSUM=1: one transposed butterfly, bitwise the same sums
2735            constexpr int P = s26ts::pow2_ceil(NCOLS);
2736            float v[P];
2737#pragma unroll
2738            for (int j = 0; j < NCOLS; ++j) {
2739#pragma unroll
2740                for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x];
2741                v[j] = tmp[j];
2742            }
2743#pragma unroll
2744            for (int j = NCOLS; j < P; ++j) v[j] = 0.0f;
2745            const float sum = s26ts::tsum<P>(v, int(threadIdx.x));
2746            const int j = s26ts::tsum_token<P>(int(threadIdx.x));
2747            if (int(threadIdx.x) == s26ts::tsum_lane<P>(j) && j < NCOLS) y[std::size_t(j) * n_out + row] = sum;
2748        } else if (threadIdx.y == 0) {
2749#pragma unroll
2750            for (int j = 0; j < NCOLS; ++j) {
2751#pragma unroll
2752                for (int l = 0; l < WARPS - 1; ++l) tmp[j] += partial[buf][l][j][threadIdx.x];
2753                tmp[j] = warp_sum(tmp[j]);
2754                if (threadIdx.x == 0) y[std::size_t(j) * n_out + row] = tmp[j];
2755            }
2756        }
2757    }
2758}
2759
2760bool g_q6_bypass = false;   // the load-time self-test times the GGUF-layout kernels with the copy registered
2761
2762// the packed planes of one Q6_K matrix (owned: allocated by native_q6_k_pack, freed by native_q6_k_unpack)
2763struct Q6Packed { void* base; const int* ql; const int* qh; const int8_t* sc; const half* d; int n_in, n_out; };
2764std::unordered_map<const void*, Q6Packed>& q6_packed_registry() {
2765    static std::unordered_map<const void*, Q6Packed> registry;
2766    return registry;
2767}
2768
2769template<int NCOLS>
2770void q6_packed_launch(const Q6Packed& w, const Q81Block* x, float* y, cudaStream_t s) {
2771    const int grid = (std::min)(w.n_out, q6p_grid());
2772    if (s26_tsum_on())
2773        native_q6_k_packed_kernel<NCOLS, true><<<unsigned(grid), dim3(WARP, WARPS), 0, s>>>(w.ql, w.qh, w.sc, w.d, x, y, w.n_in,
2774                                                                                          w.n_out, grid);
2775    else
2776        native_q6_k_packed_kernel<NCOLS><<<unsigned(grid), dim3(WARP, WARPS), 0, s>>>(w.ql, w.qh, w.sc, w.d, x, y, w.n_in,
2777                                                                                    w.n_out, grid);
2778}
2779
2780bool q6_packed_mmvq(const void* weights, const void* x_q8_1, float* y, int n_in, int n_out, int ncols, void* stream) {
2781    auto& registry = q6_packed_registry();
2782    if (registry.empty() || g_q6_bypass || (ncols > 1 && !g_multi_exact)) return false;
2783    const auto found = registry.find(weights);
2784    if (found == registry.end() || found->second.n_in != n_in || found->second.n_out != n_out) return false;
2785    validate_shape(n_in, ncols, 256);
2786    validate_pointer(x_q8_1);
2787    validate_pointer(y);
2788    validate_stream(stream);
2789    const auto* x = static_cast<const Q81Block*>(x_q8_1);
2790    const auto s = static_cast<cudaStream_t>(stream);
2791    switch (ncols) {
2792        case 1: q6_packed_launch<1>(found->second, x, y, s); break;
2793        case 2: q6_packed_launch<2>(found->second, x, y, s); break;
2794        case 3: q6_packed_launch<3>(found->second, x, y, s); break;
2795        case 4: q6_packed_launch<4>(found->second, x, y, s); break;
2796        case 5: q6_packed_launch<5>(found->second, x, y, s); break;
2797        case 6: q6_packed_launch<6>(found->second, x, y, s); break;
2798        case 7: q6_packed_launch<7>(found->second, x, y, s); break;
2799        case 8: q6_packed_launch<8>(found->second, x, y, s); break;
2800#if STRATA_VERIFY_MAX_T > 8
2801        case 9: q6_packed_launch<9>(found->second, x, y, s); break;
2802        case 10: q6_packed_launch<10>(found->second, x, y, s); break;
2803        case 11: q6_packed_launch<11>(found->second, x, y, s); break;
2804        case 12: q6_packed_launch<12>(found->second, x, y, s); break;
2805#if STRATA_VERIFY_MAX_T > 12
2806        case 13: q6_packed_launch<13>(found->second, x, y, s); break;
2807        case 14: q6_packed_launch<14>(found->second, x, y, s); break;
2808        case 15: q6_packed_launch<15>(found->second, x, y, s); break;
2809        case 16: q6_packed_launch<16>(found->second, x, y, s); break;
2810#endif
2811#endif
2812        default: throw std::invalid_argument("native MMVQ requires 1 <= ncols <= MAX_NCOLS");
2813    }
2814    launch_check();
2815    return true;
2816}
2817} // namespace
2818
2819bool native_q8_0_packed_enabled() {
2820    static const bool enabled = [] {
2821        const char* v = std::getenv("STRATA_Q8_PACKED");
2822        return v && v[0] == '1' && v[1] == '\0';
2823    }();
2824    return enabled || q8_sm60_on();
2825}
2826
2827bool native_q8_0_packed_eligible(int n_in, int n_out) {
2828    if (q8_sm60_on()) return n_in >= 128 && n_in % 32 == 0 && n_out > 0;   // the Pascal kernel takes any of them
2829    return q8_packed_shape(n_in, n_out);
2830}
2831
2832namespace {
2833// packed copies made here (the head), freed by release; null: packed in place (release only unregisters it)
2834std::unordered_map<const void*, void*>& q8_sm60_owned() {
2835    static std::unordered_map<const void*, void*> owned;
2836    return owned;
2837}
2838bool q8_sm60_pack_impl(const void* weights, int n_in, int n_out, const char* what, bool quiet);
2839} // namespace
2840
2841bool native_q8_0_sm60_pack(const void* weights, int n_in, int n_out, const char* what) {
2842    return q8_sm60_pack_impl(weights, n_in, n_out, what, false);
2843}
2844bool native_q8_0_sm60_pack_quiet(const void* weights, int n_in, int n_out, const char* what) {
2845    return q8_sm60_pack_impl(weights, n_in, n_out, what, true);
2846}
2847
2848namespace {
2849bool q8_sm60_pack_impl(const void* weights, int n_in, int n_out, const char* what, bool quiet) {
2850#if defined(__HIPCC__)
2851    (void) weights; (void) n_in; (void) n_out; (void) what; (void) quiet;
2852    return false;
2853#else
2854    if (!q8_sm60_on() || !weights || !native_q8_0_packed_eligible(n_in, n_out)) return false;
2855    if (q8_packed_registry().count(weights)) return true;
2856    const std::size_t count = std::size_t(n_in / 32) * std::size_t(n_out);
2857    const std::size_t bytes = count * 34;
2858    void* packed = nullptr;
2859    if (cudaMalloc(&packed, bytes) != cudaSuccess) {
2860        cudaGetLastError();
2861        std::fprintf(stderr, "strata q8 sm60: no VRAM for the packed %s (%.0f MiB); it keeps the GGUF layout\n", what,
2862                     double(bytes) / 1048576.0);
2863        return false;
2864    }
2865    auto* qs = static_cast<int8_t*>(packed);
2866    auto* d = reinterpret_cast<half*>(qs + std::size_t(n_in) * n_out);
2867    q8sm60::pack_kernel<<<unsigned((count + 255) / 256), 256>>>(static_cast<const Q80Block*>(weights), qs, d, count);
2868    if (cudaDeviceSynchronize() != cudaSuccess) {
2869        cudaGetLastError();
2870        cudaFree(packed);
2871        std::fprintf(stderr, "strata q8 sm60: packing the %s failed; it keeps the GGUF layout\n", what);
2872        return false;
2873    }
2874    q8_packed_registry()[weights] = Q8Packed{qs, d, n_in, n_out};
2875    q8_sm60_owned()[weights] = packed;
2876    if (!quiet)
2877        std::fprintf(stderr, "strata q8 sm60: packed %s (%d x %d, %.0f MiB more VRAM)\n", what, n_out, n_in,
2878                     double(bytes) / 1048576.0);
2879    return true;
2880#endif
2881}
2882} // namespace
2883
2884void native_q8_0_sm60_release(const void* weights) {
2885    auto& owned = q8_sm60_owned();
2886    const auto it = owned.find(weights);
2887    if (it == owned.end()) return;
2888    q8_packed_registry().erase(weights);
2889    if (it->second) cudaFree(it->second);
2890    owned.erase(it);
2891}
2892
2893void native_q8_0_pack_host(const void* gguf_blocks, void* out, int n_in, int n_out) {
2894    const auto* blocks = static_cast<const Q80Block*>(gguf_blocks);
2895    auto* qs = static_cast<int8_t*>(out);
2896    auto* d = reinterpret_cast<half*>(qs + std::size_t(n_in) * n_out);
2897    const std::size_t count = std::size_t(n_in / 32) * n_out;
2898    for (std::size_t b = 0; b < count; ++b) {
2899        std::memcpy(qs + b * 32, blocks[b].qs, 32);
2900        std::memcpy(d + b, &blocks[b].d, sizeof(half));
2901    }
2902}
2903
2904void native_q8_0_packed_register(const void* gguf_weights, const void* packed, int n_in, int n_out) {
2905    validate_pointer(gguf_weights);
2906    validate_pointer(packed);
2907    if (!native_q8_0_packed_eligible(n_in, n_out)) throw std::invalid_argument("Q8_0 packed: ineligible shape");
2908    const auto* qs = static_cast<const int8_t*>(packed);
2909    q8_packed_registry()[gguf_weights] =
2910        Q8Packed{qs, reinterpret_cast<const half*>(qs + std::size_t(n_in) * n_out), n_in, n_out};
2911}
2912
2913void native_q8_0_packed_unregister(const void* gguf_weights) { q8_packed_registry().erase(gguf_weights); }
2914
2915bool native_q8_0_sm60_pack_in_place(void* weights, int n_in, int n_out, const char* what) {
2916#if defined(__HIPCC__)
2917    (void) weights; (void) n_in; (void) n_out; (void) what;
2918    return false;
2919#else
2920    if (!q8_sm60_on() || !weights || !native_q8_0_packed_eligible(n_in, n_out)) return false;
2921    if (q8_packed_registry().count(weights)) return true;
2922    // The GGUF blocks are gone afterwards, so only where q8_packed_mmvq can never fall back to the GGUF-layout kernels
2923    // (every column count fits the kernel's shared-memory planes) and its 16-byte weight loads stay aligned
2924    if (q8sm60::smem_bytes(q8sm60::MAX_COLS, n_in) > q8sm60::MAX_SMEM || reinterpret_cast<std::uintptr_t>(weights) % 16 != 0)
2925        return native_q8_0_sm60_pack(weights, n_in, n_out, what);
2926    const std::size_t bytes = std::size_t(n_in / 32) * std::size_t(n_out) * 34;   // both layouts: 34 bytes per 32
2927    std::vector<uint8_t> blocks(bytes), planes(bytes);
2928    if (cudaMemcpy(blocks.data(), weights, bytes, cudaMemcpyDeviceToHost) != cudaSuccess) {
2929        cudaGetLastError();
2930        std::fprintf(stderr, "strata q8 sm60: reading the %s failed; it keeps the GGUF layout\n", what);
2931        return false;
2932    }
2933    native_q8_0_pack_host(blocks.data(), planes.data(), n_in, n_out);
2934    if (cudaMemcpy(weights, planes.data(), bytes, cudaMemcpyHostToDevice) != cudaSuccess) {
2935        cudaGetLastError();
2936        // a partial write leaves neither layout: put the blocks back
2937        const bool restored = cudaMemcpy(weights, blocks.data(), bytes, cudaMemcpyHostToDevice) == cudaSuccess;
2938        cudaGetLastError();
2939        std::fprintf(stderr, "strata q8 sm60: writing the packed %s failed; %s\n", what,
2940                     restored ? "it keeps the GGUF layout" : "its GGUF blocks could not be restored either");
2941        return false;
2942    }
2943    native_q8_0_packed_register(weights, weights, n_in, n_out);
2944    q8_sm60_owned()[weights] = nullptr;
2945    return true;   // the caller says what it packed
2946#endif
2947}
2948
2949bool native_q6_k_packed_enabled() {
2950    static const bool enabled = [] {
2951        const char* v = std::getenv("STRATA_Q6_PACKED");
2952        return v && v[0] == '1' && v[1] == '\0';
2953    }();
2954    return enabled;
2955}
2956
2957bool native_q6_k_pack(const void* weights, int n_in, int n_out, const char* what) {
2958    if (!weights || n_in <= 0 || n_in % 256 || n_in / 256 < WARPS * WARP / 32 || n_out < 2048) return false;
2959    if (q6_packed_registry().count(weights)) return true;
2960    const std::size_t nb = std::size_t(n_in / 256) * std::size_t(n_out);
2961    const std::size_t bytes = nb * sizeof(Q6KBlock);
2962    std::vector<Q6KBlock> host(nb);
2963    if (cudaMemcpy(host.data(), weights, bytes, cudaMemcpyDeviceToHost) != cudaSuccess) { cudaGetLastError(); return false; }
2964    // planes: ql | qh | scales | d, each 256-byte aligned
2965    const std::size_t o_qh = (nb * 128 + 255) & ~std::size_t(255);
2966    const std::size_t o_sc = (o_qh + nb * 64 + 255) & ~std::size_t(255);
2967    const std::size_t o_d = (o_sc + nb * 16 + 255) & ~std::size_t(255);
2968    const std::size_t total = o_d + nb * 2;
2969    std::vector<uint8_t> packed(total, 0);
2970    for (std::size_t b = 0; b < nb; ++b) {
2971        std::memcpy(packed.data() + b * 128, host[b].ql, 128);
2972        std::memcpy(packed.data() + o_qh + b * 64, host[b].qh, 64);
2973        std::memcpy(packed.data() + o_sc + b * 16, host[b].scales, 16);
2974        std::memcpy(packed.data() + o_d + b * 2, &host[b].d, 2);
2975    }
2976    void* dev = nullptr;
2977    if (cudaMalloc(&dev, total) != cudaSuccess) { cudaGetLastError(); return false; }
2978    if (cudaMemcpy(dev, packed.data(), total, cudaMemcpyHostToDevice) != cudaSuccess) {
2979        cudaFree(dev); cudaGetLastError(); return false;
2980    }
2981    auto* base = static_cast<uint8_t*>(dev);
2982    q6_packed_registry()[weights] = Q6Packed{dev, reinterpret_cast<const int*>(base),
2983                                             reinterpret_cast<const int*>(base + o_qh),
2984                                             reinterpret_cast<const int8_t*>(base + o_sc),
2985                                             reinterpret_cast<const half*>(base + o_d), n_in, n_out};
2986    std::fprintf(stderr, "strata: STRATA_Q6_PACKED=1 packed the %s (%d x %d, +%.1f MiB)\n", what, n_out, n_in,
2987                 total / 1048576.0);
2988    // STRATA_Q6P_SELFTEST=1: bitwise check against the GGUF-layout kernels (1..4 columns) and paired timings
2989    if (const char* v = std::getenv("STRATA_Q6P_SELFTEST"); v && (v[0] == '1' || v[0] == '2')) {
2990        cudaStream_t s = nullptr;
2991        cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking);
2992        const int nq = n_in / Q8K;
2993        std::vector<Q81Block> hx(std::size_t(4) * nq);
2994        uint32_t r = 12345u;
2995        for (auto& blk : hx) {
2996            for (auto& q : blk.qs) { r = r * 1664525u + 1013904223u; q = int8_t(int((r >> 24) & 255u) - 128); }
2997            r = r * 1664525u + 1013904223u;
2998            blk.ds = __floats2half2_rn(0.001f + float(r >> 8) * 1e-9f, 0.0f);
2999        }
3000        void *dx = nullptr, *ya = nullptr, *yb = nullptr;
3001        cudaMalloc(&dx, hx.size() * sizeof(Q81Block));
3002        cudaMalloc(&ya, std::size_t(4) * n_out * 4);
3003        cudaMalloc(&yb, std::size_t(4) * n_out * 4);
3004        cudaMemcpy(dx, hx.data(), hx.size() * sizeof(Q81Block), cudaMemcpyHostToDevice);
3005        std::vector<float> a(std::size_t(4) * n_out), c(std::size_t(4) * n_out);
3006        bool same = true;
3007        for (int nc = 1; nc <= 4; ++nc) {
3008            g_q6_bypass = true;
3009            native_q6_k_mmvq(weights, dx, (float*) ya, n_in, n_out, nc, s);
3010            g_q6_bypass = false;
3011            native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s);
3012            cudaStreamSynchronize(s);
3013            cudaMemcpy(a.data(), ya, std::size_t(nc) * n_out * 4, cudaMemcpyDeviceToHost);
3014            cudaMemcpy(c.data(), yb, std::size_t(nc) * n_out * 4, cudaMemcpyDeviceToHost);
3015            same = same && std::memcmp(a.data(), c.data(), std::size_t(nc) * n_out * 4) == 0;
3016        }
3017        cudaEvent_t e0, e1;
3018        cudaEventCreate(&e0); cudaEventCreate(&e1);
3019        for (int nc : {1, 2, 4}) {
3020            std::vector<float> tb, tc;
3021            for (int k = 0; k < 11; ++k) {
3022                for (int pass = 0; pass < 2; ++pass) {
3023                    const bool cand = (pass == 0) == (k % 2 == 1);
3024                    g_q6_bypass = !cand;
3025                    cudaEventRecord(e0, s);
3026                    for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) (cand ? yb : ya), n_in, n_out, nc, s);
3027                    cudaEventRecord(e1, s);
3028                    cudaEventSynchronize(e1);
3029                    float ms = 0; cudaEventElapsedTime(&ms, e0, e1);
3030                    (cand ? tc : tb).push_back(ms * 1000.0f / 5);
3031                }
3032            }
3033            g_q6_bypass = false;
3034            std::sort(tb.begin(), tb.end()); std::sort(tc.begin(), tc.end());
3035            std::fprintf(stderr, "strata: Q6_K packed self-test %s ncols %d: GGUF %.1f us (%.1f-%.1f), packed %.1f us "
3036                         "(%.1f-%.1f), 11 paired samples\n", what, nc, tb[5], tb[0], tb[10], tc[5], tc[0], tc[10]);
3037        }
3038        std::fprintf(stderr, "strata: Q6_K packed self-test %s: outputs %s (1-4 columns)\n", what,
3039                     same ? "BITWISE EQUAL" : "DIFFER");
3040        if (v[0] == '2') {   // grid sweep of the packed kernel
3041            for (int grid : {160, 320, 640, 1280, 2560, 5120, 20480}) {
3042                g_q6p_grid_override = grid;
3043                for (int nc : {1, 2, 4}) {
3044                    std::vector<float> tc;
3045                    for (int k = 0; k < 7; ++k) {
3046                        cudaEventRecord(e0, s);
3047                        for (int it = 0; it < 5; ++it) native_q6_k_mmvq(weights, dx, (float*) yb, n_in, n_out, nc, s);
3048                        cudaEventRecord(e1, s);
3049                        cudaEventSynchronize(e1);
3050                        float ms = 0; cudaEventElapsedTime(&ms, e0, e1);
3051                        tc.push_back(ms * 1000.0f / 5);
3052                    }
3053                    std::sort(tc.begin(), tc.end());
3054                    std::fprintf(stderr, "strata: Q6_K packed grid sweep %s grid %d ncols %d: %.1f us (%.1f-%.1f)\n",
3055                                 what, grid, nc, tc[3], tc[0], tc[6]);
3056                }
3057            }
3058            g_q6p_grid_override = 0;
3059        }
3060        cudaEventDestroy(e0); cudaEventDestroy(e1);
3061        cudaFree(dx); cudaFree(ya); cudaFree(yb);
3062        cudaStreamDestroy(s);
3063        if (!same) { native_q6_k_unpack(weights); return false; }
3064    }
3065    return true;
3066}
3067
3068void native_q6_k_unpack(const void* weights) {
3069    auto& registry = q6_packed_registry();
3070    const auto found = registry.find(weights);
3071    if (found == registry.end()) return;
3072    cudaFree(found->second.base);
3073    registry.erase(found);
3074}
3075
3076void native_mmvq_set_multi_exact(bool exact) { g_multi_exact = exact; }
3077bool native_mmvq_multi_exact() { return g_multi_exact; }
3078void native_mmvq_set_b6_rows(int mode) { g_b6_rows = mode; }
3079int native_mmvq_b6_rows() { return b6_rows_mode(); }
3080
3081std::size_t native_q8_1_bytes(int n_in, int ncols) {
3082    validate_shape(n_in, ncols);
3083    return std::size_t(ncols) * std::size_t(n_in / Q8K) * sizeof(Q81Block);
3084}
3085
3086void native_quantize_q8_1(const float* x, void* x_q8_1, int n_in, int ncols, void* stream) {
3087    validate_shape(n_in, ncols);
3088    validate_pointer(x);
3089    validate_pointer(x_q8_1);
3090    validate_stream(stream);
3091    // Columns are contiguous and n_in is a multiple of 32, so ncols columns quantize as one vector of
3092    // ncols * n_in elements: every 32-element block stays inside one column.
3093    const int n_total = n_in * ncols;
3094    const unsigned blocks = unsigned((std::size_t(n_total) + QUANT_THREADS - 1) / QUANT_THREADS);
3095    launch_pdl(native_quantize_q8_1_kernel, dim3(blocks), dim3(QUANT_THREADS), 0, static_cast<cudaStream_t>(stream), x,
3096               static_cast<Q81Block*>(x_q8_1), n_total);
3097    launch_check();
3098}
3099
3100void native_swiglu_quantize_q8_1(const float* gate, const float* up, void* x_q8_1,
3101                                 int n_in, int ncols, void* stream) {
3102    validate_shape(n_in, ncols);
3103    validate_pointer(gate);
3104    validate_pointer(up);
3105    validate_pointer(x_q8_1);
3106    validate_stream(stream);
3107    const int n_total = n_in * ncols;
3108    const unsigned blocks = unsigned((std::size_t(n_total) + QUANT_THREADS - 1) / QUANT_THREADS);
3109    native_swiglu_quantize_q8_1_kernel<<<blocks, QUANT_THREADS, 0,
3110                                         static_cast<cudaStream_t>(stream)>>>(
3111        gate, up, static_cast<Q81Block*>(x_q8_1), n_total);
3112    launch_check();
3113}
3114
3115void native_q5_k_mmvq(const void* weights, const void* x_q8_1, float* y,
3116                      int n_in, int n_out, int ncols, void* stream) {
3117    validate_shape(n_in, ncols, QK);
3118    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3119    validate_pointer(weights);
3120    validate_pointer(x_q8_1);
3121    validate_pointer(y);
3122    validate_stream(stream);
3123    STRATA_WAVE_MMVQ(Q5KTraits)
3124    if (ncols > 1) {
3125        launch_multi<Q5KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3126        launch_check();
3127        return;
3128    }
3129    const auto* w = static_cast<const Q5KBlock*>(weights);
3130    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3131    const auto s = static_cast<cudaStream_t>(stream);
3132    const dim3 threads(WARP, WARPS);
3133    if (n_in / QK < VDR * WARPS * WARP / QI) {
3134        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3135        native_q5_k_mmvq_kernel<true><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);
3136    } else {
3137        native_q5_k_mmvq_kernel<false><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);
3138    }
3139    launch_check();
3140}
3141
3142void native_q5_k_f32(const void* weights, const float* x, void* scratch_q8_1,
3143                     float* y, int n_in, int n_out, int ncols, void* stream) {
3144    // Validate all outputs before enqueueing the first operation.
3145    validate_shape(n_in, ncols, QK);
3146    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3147    validate_pointer(weights);
3148    validate_pointer(x);
3149    validate_pointer(scratch_q8_1);
3150    validate_pointer(y);
3151    validate_stream(stream);
3152    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3153    native_q5_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3154}
3155
3156namespace {
3157// Turing: Q2_0 one to four columns with one warp per RPW rows.  The exact layout gives each row four warps, a chunk of
3158// a 64-weight block per thread and a cross-warp reduction; at the engine's 2560 inputs (40 blocks a row) 48 of the 128
3159// threads have no chunk and the reduction is most of the time (QSA attn_q 2560x12288 at 3 columns: 80 us, 110 GB/s on
3160// an RTX 2080 Ti).  Here lane l runs the chunks of the exact kernel's threads l, 32+l, 64+l and 96+l in their loop
3161// order, adds the four sums as warp 0 adds the other warps' partials, then the same warp_sum: every output is bit for
3162// bit native_q2_0_mmvq_kernel's (one column) and launch_multi's exact layout (two to four).  80 -> 31 us at three
3163// columns, 37 -> 25 us at one.  STRATA_Q2_WARP=0 keeps the old kernels; =1 takes this one on any CUDA card.
3164constexpr int kQ20WarpRows = 4;
3165template <int NCOLS>
3166__global__ void __launch_bounds__(WARPS * WARP) q2_0_warp_rows_kernel(const Q20Block* __restrict__ w,
3167                                                                      const Q81Block* __restrict__ x,
3168                                                                      float* __restrict__ y, int n_in, int n_out) {
3169    using F = Q20Traits;
3170    constexpr int RPW = kQ20WarpRows;
3171    static_assert(F::T == 2 && F::BPI == WARPS * WARP / 2, "the lanes play the exact layout's threads");
3172    const int lane = int(threadIdx.x) & (WARP - 1);
3173    const int row0 = (int(blockIdx.x) * WARPS + int(threadIdx.x) / WARP) * RPW;
3174    if (row0 >= n_out) return;
3175    const int bpr = n_in / F::DIV, x_stride = n_in / Q8K;
3176    float acc[NCOLS][RPW];
3177#pragma unroll
3178    for (int v = 0; v < WARPS; ++v) {   // the exact kernel's thread WARP * v + lane
3179        const int tid = WARP * v + lane;
3180        const int kqs = F::kqs(tid);
3181        float tmp[NCOLS][RPW] = {};
3182        for (int kbx = tid / F::T; kbx < bpr; kbx += F::BPI) {
3183            const int kby = kbx * F::KBY;
3184#pragma unroll
3185            for (int i = 0; i < RPW; ++i) {
3186                if (row0 + i < n_out) {
3187                    const F::W wv = F::load(w + std::size_t(row0 + i) * bpr + kbx, kqs);
3188#pragma unroll
3189                    for (int j = 0; j < NCOLS; ++j) tmp[j][i] += F::apply(wv, x + std::size_t(j) * x_stride + kby, kqs);
3190                }
3191            }
3192        }
3193#pragma unroll
3194        for (int j = 0; j < NCOLS; ++j)
3195#pragma unroll
3196            for (int i = 0; i < RPW; ++i) acc[j][i] = v == 0 ? tmp[j][i] : acc[j][i] + tmp[j][i];
3197    }
3198#pragma unroll
3199    for (int j = 0; j < NCOLS; ++j)
3200#pragma unroll
3201        for (int i = 0; i < RPW; ++i) {
3202            const float sum = warp_sum(acc[j][i]);
3203            if (lane == i && row0 + i < n_out) y[std::size_t(j) * n_out + row0 + i] = sum;
3204        }
3205}
3206bool q2_0_warp_rows_on() {
3207    static int on[16] = {};   // by device ordinal: 0 unknown, 1 yes, -1 no
3208    static const int env = [] { const char* v = std::getenv("STRATA_Q2_WARP"); return v ? (v[0] == '0' ? 0 : 1) : -1; }();
3209    if (env >= 0) return env == 1;
3210    int dev = 0;
3211    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return false;
3212    if (on[dev] == 0) {
3213        int maj = 0, mnr = 0;
3214        const bool ok = cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
3215                        cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) == cudaSuccess;
3216        if (!ok) cudaGetLastError();
3217        on[dev] = ok && strata::sm75_default(maj, mnr) ? 1 : -1;   // Turing only, with STRATA_SM75_PERF=1
3218    }
3219    return on[dev] > 0;
3220}
3221}  // namespace
3222
3223void native_q2_0_mmvq(const void* weights, const void* x_q8_1, float* y,
3224                      int n_in, int n_out, int ncols, void* stream) {
3225    validate_shape(n_in, ncols, 64);
3226    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3227    validate_pointer(weights);
3228    validate_pointer(x_q8_1);
3229    validate_pointer(y);
3230    validate_stream(stream);
3231    STRATA_WAVE_MMVQ(Q20Traits)
3232#if !defined(__HIPCC__)
3233    // one column always (bitwise the single-column kernel); two to four only where the exact layout is the one in use
3234    if (ncols <= 4 && (ncols == 1 || g_multi_exact) && q2_0_warp_rows_on()) {
3235        const auto* w = static_cast<const Q20Block*>(weights);
3236        const auto* x = static_cast<const Q81Block*>(x_q8_1);
3237        const auto s = static_cast<cudaStream_t>(stream);
3238        const int warps = (n_out + kQ20WarpRows - 1) / kQ20WarpRows;
3239        const unsigned blocks = unsigned((warps + WARPS - 1) / WARPS);
3240        switch (ncols) {
3241            case 1: q2_0_warp_rows_kernel<1><<<blocks, WARPS * WARP, 0, s>>>(w, x, y, n_in, n_out); break;
3242            case 2: q2_0_warp_rows_kernel<2><<<blocks, WARPS * WARP, 0, s>>>(w, x, y, n_in, n_out); break;
3243            case 3: q2_0_warp_rows_kernel<3><<<blocks, WARPS * WARP, 0, s>>>(w, x, y, n_in, n_out); break;
3244            default: q2_0_warp_rows_kernel<4><<<blocks, WARPS * WARP, 0, s>>>(w, x, y, n_in, n_out); break;
3245        }
3246        launch_check();
3247        return;
3248    }
3249#endif
3250    if (ncols > 1) {
3251        launch_multi<Q20Traits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3252        launch_check();
3253        return;
3254    }
3255    const auto* w = static_cast<const Q20Block*>(weights);
3256    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3257    const auto s = static_cast<cudaStream_t>(stream);
3258    const dim3 threads(WARP, WARPS);
3259    if (n_in / 64 < WARPS * WARP / 2) {
3260        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3261        native_q2_0_mmvq_kernel<true><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);
3262    } else {
3263        native_q2_0_mmvq_kernel<false><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);
3264    }
3265    launch_check();
3266}
3267
3268void native_q2_0_f32(const void* weights, const float* x, void* scratch_q8_1,
3269                     float* y, int n_in, int n_out, int ncols, void* stream) {
3270    validate_shape(n_in, ncols, 64);
3271    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3272    validate_pointer(weights);
3273    validate_pointer(x);
3274    validate_pointer(scratch_q8_1);
3275    validate_pointer(y);
3276    validate_stream(stream);
3277    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3278    native_q2_0_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3279}
3280
3281void native_q3_k_mmvq(const void* weights, const void* x_q8_1, float* y,
3282                      int n_in, int n_out, int ncols, void* stream) {
3283    validate_shape(n_in, ncols, 256);
3284    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3285    validate_pointer(weights);
3286    validate_pointer(x_q8_1);
3287    validate_pointer(y);
3288    validate_stream(stream);
3289    STRATA_WAVE_MMVQ(Q3KTraits)
3290    if (ncols > 1) {
3291        launch_multi<Q3KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3292        launch_check();
3293        return;
3294    }
3295    const auto* w = static_cast<const Q3KBlock*>(weights);
3296    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3297    const auto s = static_cast<cudaStream_t>(stream);
3298    const dim3 threads(WARP, WARPS);
3299    if (n_in / 256 < WARPS * WARP / 16) {
3300        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3301        native_q3_k_mmvq_kernel<true><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);
3302    } else {
3303        native_q3_k_mmvq_kernel<false><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);
3304    }
3305    launch_check();
3306}
3307
3308void native_q3_k_f32(const void* weights, const float* x, void* scratch_q8_1,
3309                     float* y, int n_in, int n_out, int ncols, void* stream) {
3310    validate_shape(n_in, ncols, 256);
3311    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3312    validate_pointer(weights);
3313    validate_pointer(x);
3314    validate_pointer(scratch_q8_1);
3315    validate_pointer(y);
3316    validate_stream(stream);
3317    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3318    native_q3_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3319}
3320
3321void native_iq4_xs_mmvq(const void* weights, const void* x_q8_1, float* y,
3322                       int n_in, int n_out, int ncols, void* stream) {
3323    validate_shape(n_in, ncols, 256);
3324    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3325    validate_pointer(weights);
3326    validate_pointer(x_q8_1);
3327    validate_pointer(y);
3328    validate_stream(stream);
3329    STRATA_WAVE_MMVQ(IQ4XSTraits)
3330    if (ncols > 1) {
3331        launch_multi<IQ4XSTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3332        launch_check();
3333        return;
3334    }
3335    const auto* w = static_cast<const IQ4XSBlock*>(weights);
3336    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3337    const auto s = static_cast<cudaStream_t>(stream);
3338    const dim3 threads(WARP, WARPS);
3339    if (n_in / 256 < 4 * WARPS * WARP / 32) {
3340        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3341        native_iq4_xs_mmvq_kernel<true><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);
3342    } else {
3343        native_iq4_xs_mmvq_kernel<false><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);
3344    }
3345    launch_check();
3346}
3347
3348void native_iq4_xs_f32(const void* weights, const float* x, void* scratch_q8_1,
3349                      float* y, int n_in, int n_out, int ncols, void* stream) {
3350    validate_shape(n_in, ncols, 256);
3351    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3352    validate_pointer(weights);
3353    validate_pointer(x);
3354    validate_pointer(scratch_q8_1);
3355    validate_pointer(y);
3356    validate_stream(stream);
3357    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3358    native_iq4_xs_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3359}
3360
3361void native_q4_k_mmvq(const void* weights, const void* x_q8_1, float* y,
3362                      int n_in, int n_out, int ncols, void* stream) {
3363    validate_shape(n_in, ncols, 256);
3364    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3365    validate_pointer(weights);
3366    validate_pointer(x_q8_1);
3367    validate_pointer(y);
3368    validate_stream(stream);
3369    STRATA_WAVE_MMVQ(Q4KTraits)
3370    if (ncols > 1) {
3371        launch_multi<Q4KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3372        launch_check();
3373        return;
3374    }
3375    const auto* w = static_cast<const Q4KBlock*>(weights);
3376    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3377    const auto s = static_cast<cudaStream_t>(stream);
3378    const dim3 threads(WARP, WARPS);
3379    if (n_in / 256 < WARPS * WARP / 16) {
3380        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3381        native_q4_k_mmvq_kernel<true><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);
3382    } else {
3383        native_q4_k_mmvq_kernel<false><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);
3384    }
3385    launch_check();
3386}
3387
3388void native_q4_k_f32(const void* weights, const float* x, void* scratch_q8_1,
3389                     float* y, int n_in, int n_out, int ncols, void* stream) {
3390    validate_shape(n_in, ncols, 256);
3391    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3392    validate_pointer(weights);
3393    validate_pointer(x);
3394    validate_pointer(scratch_q8_1);
3395    validate_pointer(y);
3396    validate_stream(stream);
3397    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3398    native_q4_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3399}
3400
3401void native_q6_k_mmvq(const void* weights, const void* x_q8_1, float* y,
3402                      int n_in, int n_out, int ncols, void* stream) {
3403    if (q6_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return;   // STRATA_Q6_PACKED=1 heads
3404    validate_shape(n_in, ncols, 256);
3405    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3406    validate_pointer(weights);
3407    validate_pointer(x_q8_1);
3408    validate_pointer(y);
3409    validate_stream(stream);
3410    STRATA_WAVE_MMVQ(Q6KTraits)
3411    if (ncols > 1) {
3412        launch_multi<Q6KTraits>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3413        launch_check();
3414        return;
3415    }
3416    const auto* w = static_cast<const Q6KBlock*>(weights);
3417    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3418    const auto s = static_cast<cudaStream_t>(stream);
3419    const dim3 threads(WARP, WARPS);
3420    if (n_in / 256 < WARPS * WARP / 32) {
3421        const unsigned blocks = unsigned((std::size_t(n_out) + WARPS - 1) / WARPS);
3422        native_q6_k_mmvq_kernel<true><<<blocks, threads, 0, s>>>(w, x, y, n_in, n_out);
3423    } else {
3424        native_q6_k_mmvq_kernel<false><<<unsigned(n_out), threads, 0, s>>>(w, x, y, n_in, n_out);
3425    }
3426    launch_check();
3427}
3428
3429void native_q6_k_f32(const void* weights, const float* x, void* scratch_q8_1,
3430                     float* y, int n_in, int n_out, int ncols, void* stream) {
3431    validate_shape(n_in, ncols, 256);
3432    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3433    validate_pointer(weights);
3434    validate_pointer(x);
3435    validate_pointer(scratch_q8_1);
3436    validate_pointer(y);
3437    validate_stream(stream);
3438    native_quantize_q8_1(x, scratch_q8_1, n_in, ncols, stream);
3439    native_q6_k_mmvq(weights, scratch_q8_1, y, n_in, n_out, ncols, stream);
3440}
3441
3442void native_q4_0_mmvq(const void* weights, const void* x_q8_1, float* y,
3443                       int n_in, int n_out, int ncols, void* stream) {
3444    small_mmvq<Q40Block, 4>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3445}
3446
3447void native_q4_0_f32(const void* weights, const float* x, void* scratch_q8_1,
3448                      float* y, int n_in, int n_out, int ncols, void* stream) {
3449    small_f32<Q40Block, 4>(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream);
3450}
3451
3452void native_q5_0_mmvq(const void* weights, const void* x_q8_1, float* y,
3453                       int n_in, int n_out, int ncols, void* stream) {
3454    small_mmvq<Q50Block, 4>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3455}
3456
3457void native_q5_0_f32(const void* weights, const float* x, void* scratch_q8_1,
3458                      float* y, int n_in, int n_out, int ncols, void* stream) {
3459    small_f32<Q50Block, 4>(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream);
3460}
3461
3462template<int NCOLS>
3463void q8_0_pair_launch(const Q80Block* w1, const Q80Block* w2, const Q81Block* x, float* y1, float* y2, int n_in, int n_out,
3464                      cudaStream_t s) {
3465    using F = SmallTraits<Q80Block, 8>;
3466    const dim3 threads(WARP, WARPS);
3467    if (s26_tsum_on())
3468        native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, true, true><<<unsigned(2 * n_out), threads, 0, s>>>(w1, x, y1, n_in, n_out, w2, y2);
3469    else
3470        native_mmvq_multi_kernel<F, NCOLS, WARPS, 1, false, true><<<unsigned(2 * n_out), threads, 0, s>>>(w1, x, y1, n_in, n_out, w2, y2);
3471}
3472
3473bool native_mmvq_pair(int ggml_type, const void* w1, const void* w2, const void* x_q8_1, float* y1, float* y2,
3474                      int n_in, int n_out, int ncols, void* stream) {
3475    using F = SmallTraits<Q80Block, 8>;
3476    // only where both calls would run native_mmvq_multi_kernel<F, ncols, WARPS, 1> (exact layout, not packed)
3477    if (ggml_type != 8 || !g_multi_exact || ncols < 2 || ncols > 8 || n_out <= 0 || n_in <= 0 || n_in % 32 != 0 ||
3478        n_in / F::DIV < F::BPI || !w1 || !w2 || !x_q8_1 || !y1 || !y2 || !stream)
3479        return false;
3480    const auto& reg = q8_packed_registry();
3481    if (reg.count(w1) || reg.count(w2)) return false;
3482    const auto* a = static_cast<const Q80Block*>(w1);
3483    const auto* b = static_cast<const Q80Block*>(w2);
3484    const auto* x = static_cast<const Q81Block*>(x_q8_1);
3485    const auto s = static_cast<cudaStream_t>(stream);
3486    switch (ncols) {
3487        case 2: q8_0_pair_launch<2>(a, b, x, y1, y2, n_in, n_out, s); break;
3488        case 3: q8_0_pair_launch<3>(a, b, x, y1, y2, n_in, n_out, s); break;
3489        case 4: q8_0_pair_launch<4>(a, b, x, y1, y2, n_in, n_out, s); break;
3490        case 5: q8_0_pair_launch<5>(a, b, x, y1, y2, n_in, n_out, s); break;
3491        case 6: q8_0_pair_launch<6>(a, b, x, y1, y2, n_in, n_out, s); break;
3492        case 7: q8_0_pair_launch<7>(a, b, x, y1, y2, n_in, n_out, s); break;
3493        default: q8_0_pair_launch<8>(a, b, x, y1, y2, n_in, n_out, s); break;
3494    }
3495    launch_check();
3496    return true;
3497}
3498
3499void native_q8_0_mmvq(const void* weights, const void* x_q8_1, float* y,
3500                       int n_in, int n_out, int ncols, void* stream) {
3501    if (q8_packed_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream)) return;   // STRATA_Q8_PACKED=1 tensors
3502    small_mmvq<Q80Block, 8>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3503}
3504
3505void native_q8_0_f32(const void* weights, const float* x, void* scratch_q8_1,
3506                      float* y, int n_in, int n_out, int ncols, void* stream) {
3507    small_f32<Q80Block, 8>(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream);
3508}
3509
3510void native_iq4_nl_mmvq(const void* weights, const void* x_q8_1, float* y,
3511                       int n_in, int n_out, int ncols, void* stream) {
3512    small_mmvq<IQ4NLBlock, 4>(weights, x_q8_1, y, n_in, n_out, ncols, stream);
3513}
3514
3515void native_iq4_nl_f32(const void* weights, const float* x, void* scratch_q8_1,
3516                      float* y, int n_in, int n_out, int ncols, void* stream) {
3517    small_f32<IQ4NLBlock, 4>(weights, x, scratch_q8_1, y, n_in, n_out, ncols, stream);
3518}
3519
3520bool native_mmvq_supported(int ggml_type) noexcept {
3521    return ggml_type == 2 || ggml_type == 6 || ggml_type == 7 || ggml_type == 8 || ggml_type == 11 ||
3522           ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 20 ||
3523           ggml_type == 23 || ggml_type == 42 || ggml_type == 16 || ggml_type == 17 || ggml_type == 18 ||
3524           ggml_type == 21 || ggml_type == 22 || ggml_type == 29;
3525}
3526
3527std::size_t native_mmvq_weight_bytes(int ggml_type, int n_in, int n_out) {
3528    int block_elems, block_bytes;
3529    switch (ggml_type) {
3530    case 2: block_elems = 32; block_bytes = 18; break;
3531    case 6: block_elems = 32; block_bytes = 22; break;
3532    case 7: block_elems = 32; block_bytes = 24; break;
3533    case 8: block_elems = 32; block_bytes = 34; break;
3534    case 20: block_elems = 32; block_bytes = 18; break;
3535    case 11: block_elems = 256; block_bytes = 110; break;
3536    case 12: block_elems = 256; block_bytes = 144; break;
3537    case 13: block_elems = 256; block_bytes = 176; break;
3538    case 14: block_elems = 256; block_bytes = 210; break;
3539    case 23: block_elems = 256; block_bytes = 136; break;
3540    case 42: block_elems = 64; block_bytes = 18; break;
3541    case 16: case 17: case 18: case 21: case 22: case 29:
3542        block_elems = 256; block_bytes = (int) iq_row_bytes(ggml_type, 256); break;
3543    default: throw std::invalid_argument("unsupported native MMVQ GGML type");
3544    }
3545    validate_shape(n_in, 1, block_elems);
3546    if (n_out <= 0) throw std::invalid_argument("native MMVQ requires n_out > 0");
3547    const std::size_t row_bytes = std::size_t(n_in / block_elems) * block_bytes;
3548    if (row_bytes > std::numeric_limits<std::size_t>::max() / std::size_t(n_out)) {
3549        throw std::length_error("native MMVQ weight byte count overflows size_t");
3550    }
3551    return row_bytes * std::size_t(n_out);
3552}
3553
3554void native_mmvq(int ggml_type, const void* weights, const void* x_q8_1, float* y,
3555                 int n_in, int n_out, int ncols, void* stream) {
3556    // more columns than one launch takes: ceil(ncols / MAX_NCOLS) passes over the same weights.  Every column of a
3557    // multi-column pass is bitwise the single-column result (bench/micro/native_mmvq_multi.cpp), so the split changes no
3558    // arithmetic.  Column j starts at activation block j * (n_in / Q8K) and writes y + j * n_out.  (Never reached by a
3559    // window of up to 16 rows in a wide build, nor of up to 8 in a narrow one: a guard for a caller that asks for more.)
3560    if (ncols > MAX_NCOLS) {
3561        const std::size_t col_blocks = std::size_t(n_in / Q8K);
3562        for (int j = 0; j < ncols; j += MAX_NCOLS) {
3563            const int nj = (ncols - j < MAX_NCOLS) ? (ncols - j) : MAX_NCOLS;
3564            native_mmvq(ggml_type, weights, static_cast<const Q81Block*>(x_q8_1) + std::size_t(j) * col_blocks,
3565                        y + std::size_t(j) * std::size_t(n_out), n_in, n_out, nj, stream);
3566        }
3567        return;
3568    }
3569    strata::dispatch::kernel(strata::dispatch::kDense, 0, ggml_type, n_in, n_out, ncols);   // BW-MEASURE: the multi-column MMVQ kernels
3570    switch (ggml_type) {
3571    case 2: native_q4_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3572    case 6: native_q5_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3573    case 7: iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3574    case 8: native_q8_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3575    case 20: native_iq4_nl_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3576    case 11: native_q3_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3577    case 12: native_q4_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3578    case 13: native_q5_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3579    case 14: native_q6_k_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3580    case 23: native_iq4_xs_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3581    case 42: native_q2_0_mmvq(weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3582    case 16: case 17: case 18: case 21: case 22: case 29:
3583        iq_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream); break;
3584    default: throw std::invalid_argument("unsupported native MMVQ GGML type");
3585    }
3586}
3587
3588#if !defined(__HIPCC__)
3589std::size_t native_q8_1_il_bytes(int n_in, int ncols) {
3590    validate_shape(n_in, ncols);
3591    return std::size_t(n_in / Q8K) * std::size_t(native_q8_1_il_cp(ncols)) * (16 * sizeof(int) + sizeof(float));
3592}
3593
3594void native_quantize_q8_1_il(const float* x, void* x_q8_1, void* x_il, int n_in, int ncols, void* stream) {
3595    validate_shape(n_in, ncols);
3596    if (ncols < 2 || ncols > 4) throw std::invalid_argument("native_quantize_q8_1_il requires 2 <= ncols <= 4");
3597    validate_pointer(x);
3598    validate_pointer(x_q8_1);
3599    validate_pointer(x_il);
3600    validate_stream(stream);
3601    const int cp = native_q8_1_il_cp(ncols);
3602    const Q81IlParts parts = q8_1_il_parts(x_il, n_in, ncols);
3603    const int n_total = n_in * ncols;
3604    native_quantize_q8_1_il_kernel<<<unsigned((n_total + QUANT_THREADS - 1) / QUANT_THREADS), QUANT_THREADS, 0,
3605                                     static_cast<cudaStream_t>(stream)>>>(
3606        x, static_cast<Q81Block*>(x_q8_1), const_cast<int*>(parts.bm), const_cast<int*>(parts.pm),
3607        const_cast<float*>(parts.d), n_in, n_total, cp);
3608    launch_check();
3609}
3610
3611void native_q8_1_interleave(const void* x_q8_1, void* x_il, int n_in, int ncols, void* stream) {
3612    validate_shape(n_in, ncols);
3613    if (ncols < 2 || ncols > 8) throw std::invalid_argument("native_q8_1_interleave requires 2 <= ncols <= 8");
3614    validate_pointer(x_q8_1);
3615    validate_pointer(x_il);
3616    validate_stream(stream);
3617    const int nb = n_in / Q8K, cp = native_q8_1_il_cp(ncols);
3618    const Q81IlParts parts = q8_1_il_parts(x_il, n_in, ncols);
3619    const int n_total = nb * 8 * ncols;
3620    native_q8_1_interleave_kernel<<<unsigned((n_total + 255) / 256), 256, 0, static_cast<cudaStream_t>(stream)>>>(
3621        static_cast<const Q81Block*>(x_q8_1), const_cast<int*>(parts.bm), const_cast<int*>(parts.pm),
3622        const_cast<float*>(parts.d), nb, n_total, cp);
3623    launch_check();
3624}
3625
3626namespace {
3627// Rows a warp at 2-4 columns ([ncols - 2]) by the matrix's row count, in classes: below 2048 (the keys' 512), 4096 (the
3628// output projections' 2560), 8192 (the gate projection's 6144), 12288 (qkv's 10240), and more (the queries' 12288, the
3629// head's 248K); 0: native_mmvq's kernels. The fork tuned its table on an RTX 3090. This one is read off
3630// mmvq_il_parity --bench on an RTX 3060 (sm_86) and an RTX 5070 (sm_120) together: per cell the rows count (1/2/4) whose
3631// worse card still takes at least 3% off native_mmvq's time, else 0; classes without a measured shape take their
3632// neighbour's value. Every choice is bitwise the same output, so the table is only speed.
3633struct IlRows { int type; uint8_t r[3][5]; };
3634constexpr IlRows kIlRowsShared[] = {   // sm_86 + sm_120, and the fallback for every other sm_80+ card
3635    {23, {{0, 0, 0, 0, 0}, {0, 0, 2, 4, 4}, {0, 1, 1, 1, 1}}},   // IQ4_XS
3636    {12, {{0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}},   // Q4_K
3637    {13, {{0, 0, 1, 1, 1}, {0, 4, 1, 1, 1}, {0, 1, 1, 1, 2}}},   // Q5_K
3638    {14, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 2}, {0, 0, 1, 1, 1}}},   // Q6_K
3639};
3640// Per-architecture tables (P10).  A card whose compute capability (major * 10 + minor) is listed here uses its own table;
3641// every other sm_80+ card uses kIlRowsShared.  sm_89 (Ada) has an opt-in table (kIlRows_89, below; STRATA_MMVQ_IL_89=1).  To add one, run
3642// `mmvq_il_parity --bench --emit-table` on the card (docs/MMVQ_IL_TABLE.md), paste the printed block as a
3643// `constexpr IlRows kIlRows_<cc>[]` and add {<cc>, kIlRows_<cc>, sizeof(kIlRows_<cc>) / sizeof(IlRows)} below.  Each choice
3644// is bitwise the same output, so a table is only speed.  Without a rebuild: STRATA_MMVQ_IL_ROWS (see il_env_rows).
3645// Volta (sm_70): read off mmvq_il_parity --bench on a V100-SXM2-32GB (two runs, mean), the same rule - per cell the
3646// rows count whose every measured shape takes at least 3% off native_mmvq's time (e.g. the Q5_K head at 3 columns
3647// 1094 -> 821 us, Q6_K 12288 rows 68.9 -> 47.9 us), else 0; unmeasured classes take a neighbour's value (PR 1401)
3648constexpr IlRows kIlRows_70[] = {
3649    {23, {{0, 2, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 4, 2, 2, 2}}},   // IQ4_XS
3650    {12, {{0, 2, 2, 4, 4}, {0, 2, 2, 2, 2}, {0, 2, 2, 2, 2}}},   // Q4_K
3651    {13, {{0, 2, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 1, 2, 2, 2}}},   // Q5_K
3652    {14, {{0, 1, 1, 1, 1}, {0, 2, 2, 2, 2}, {0, 2, 2, 4, 2}}},   // Q6_K
3653};
3654// Pascal (sm_60), read off mmvq_il_parity --bench --emit-table on a Tesla P100-PCIE-16GB (three runs, identical
3655// tables), the same 3% rule.  Pascal has no dp4a (strata_dp4a: four vmad), so the kernels are compute-bound and more rows a
3656// warp (weights and activations reused across rows) win 15-35% on the large shapes.  Bitwise equal to native_mmvq.
3657constexpr IlRows kIlRows_60[] = {
3658    {23, {{0, 4, 4, 4, 4}, {2, 4, 2, 4, 4}, {1, 1, 1, 1, 1}}},   // IQ4_XS
3659    {12, {{0, 4, 4, 4, 4}, {0, 2, 2, 2, 2}, {0, 0, 0, 4, 4}}},   // Q4_K
3660    {13, {{0, 2, 2, 2, 2}, {0, 4, 2, 2, 4}, {0, 2, 2, 2, 2}}},   // Q5_K
3661    {14, {{0, 2, 2, 2, 4}, {0, 0, 0, 4, 4}, {0, 0, 0, 4, 4}}},   // Q6_K
3662};
3663// Pascal with dp4a (sm_61), read off mmvq_il_parity --bench --emit-table on a Tesla P40 (three runs: a cell is non-zero
3664// only where every run picked a rows count that takes at least 3% off native_mmvq's time; where the runs disagreed on
3665// the count, the one that won twice).  E.g. IQ4_XS 2560x10240 at 2 columns 112 -> 65 us, Q6_K 12288x2560 at 4
3666// columns 189 -> 127 us, the Q5_K head at 3 columns 2545 -> 1766 us.  Bitwise equal to native_mmvq.
3667constexpr IlRows kIlRows_61[] = {
3668    {23, {{2, 4, 4, 4, 4}, {4, 4, 4, 4, 4}, {2, 2, 2, 2, 2}}},   // IQ4_XS
3669    {12, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}},   // Q4_K
3670    {13, {{2, 0, 4, 4, 4}, {2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}}},   // Q5_K
3671    {14, {{0, 0, 2, 2, 2}, {0, 4, 4, 4, 4}, {2, 4, 2, 2, 2}}},   // Q6_K
3672    {11, {{2, 2, 2, 2, 2}, {2, 2, 2, 2, 2}, {1, 1, 1, 1, 1}}},   // Q3_K
3673};
3674// RTX 30-series (sm_86), 143-dense: read off mmvq_il_parity --bench --emit-table on an RTX A4000 with the engine's real
3675// shapes (the output projections have 6144 inputs, not 4096), per cell the rows count whose worst measured shape is under
3676// 0.97 of native_mmvq's time. The four older rows are the shared table's; Q3_K (the Q2_0 pack's main dense type) is new.
3677constexpr IlRows kIlRows_86[] = {
3678    {23, {{0, 0, 0, 0, 0}, {0, 0, 2, 4, 4}, {0, 1, 1, 1, 1}}},   // IQ4_XS
3679    {12, {{0, 0, 1, 1, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}},   // Q4_K
3680    {13, {{0, 0, 1, 1, 1}, {0, 4, 1, 1, 1}, {0, 1, 1, 1, 2}}},   // Q5_K
3681    {14, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 2}, {0, 0, 1, 1, 1}}},   // Q6_K
3682    {11, {{1, 2, 2, 2, 2}, {1, 1, 1, 2, 2}, {1, 1, 1, 1, 1}}},   // Q3_K (two runs; 2560x10240 at 4 columns 120 -> 70 us)
3683};
3684// RTX PRO 5000 Blackwell (sm_120), 147-verify: read off mmvq_il_parity --bench --emit-table with the engine's shapes, the
3685// same 3% rule; it takes the interleaved kernels in more cells than the shared table (e.g. the Q5_K head at 2 columns
3686// 507 -> 367 us, IQ4_XS 2560x10240 at 3 columns 20.7 -> 14.9 us).  Bitwise equal to native_mmvq.
3687constexpr IlRows kIlRows_120[] = {
3688    {23, {{0, 1, 2, 2, 2}, {0, 4, 4, 4, 4}, {0, 2, 2, 4, 2}}},   // IQ4_XS
3689    {12, {{0, 0, 2, 1, 1}, {0, 2, 4, 2, 2}, {0, 2, 2, 2, 2}}},   // Q4_K
3690    {13, {{0, 1, 2, 1, 1}, {0, 1, 4, 2, 4}, {0, 1, 2, 1, 2}}},   // Q5_K
3691    {14, {{0, 0, 2, 1, 1}, {0, 0, 4, 2, 4}, {0, 2, 2, 2, 2}}},   // Q6_K
3692    {11, {{0, 1, 2, 2, 2}, {0, 2, 4, 2, 2}, {0, 2, 2, 2, 2}}},   // Q3_K
3693};
3694// Ada (sm_89): the cells where two cards agree.  mmvq_il_parity --bench --emit-table was run on an RTX 4070 (46 SMs,
3695// #3453) and on an RTX 4080 (48 SMs, same issue); a cell is kept only where both runs give the same rows count, else 0
3696// (the plain kernel), so a card that disagrees never gets a split it did not measure.  The 5-8 column table of that
3697// issue is not taken: the 4080 reproduced the 2-4 column table byte for byte in four runs, and the 5-8 column table
3698// changed in 10-14 of 20 entries between runs.  Bitwise equal to native_mmvq, so the table is only speed.
3699// mmvq_il_parity's check_tables rebuilds the table from the two source runs and compares.
3700constexpr IlRows kIlRows_89[] = {
3701    {23, {{0, 0, 0, 0, 0}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}},   // IQ4_XS
3702    {12, {{0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}, {0, 0, 1, 1, 1}}},   // Q4_K
3703    {13, {{0, 0, 1, 1, 0}, {0, 0, 1, 1, 0}, {0, 0, 1, 0, 0}}},   // Q5_K
3704    {14, {{0, 0, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 1}}},   // Q6_K
3705    {11, {{0, 0, 1, 0, 1}, {0, 1, 1, 1, 1}, {0, 1, 1, 1, 1}}},   // Q3_K
3706};
3707// sm_80: read off mmvq_il_parity --bench --emit-table on a CMP 170HX (GA100, 70 SMs, HBM2e 1.5 TB/s), the same 3% rule;
3708// bitwise equal to native_mmvq (the tool checks every case).
3709constexpr IlRows kIlRows_80[] = {
3710    {23, {{0, 2, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 2, 1, 1, 1}}},   // IQ4_XS
3711    {12, {{0, 0, 4, 4, 4}, {0, 0, 2, 2, 2}, {0, 0, 2, 2, 2}}},   // Q4_K
3712    {13, {{0, 0, 2, 2, 4}, {0, 0, 2, 2, 2}, {0, 0, 2, 2, 2}}},   // Q5_K
3713    {14, {{0, 0, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 2, 4, 2, 2}}},   // Q6_K
3714    {11, {{1, 2, 2, 2, 2}, {1, 1, 2, 2, 2}, {1, 2, 2, 2, 2}}},   // Q3_K
3715};
3716// sm_80 P1/P2: the hoisted-load / exact-integer kernel variant and its rows a warp per cell, pf << 4 | rows
3717// (0x32 = variant 3 at 2 rows a warp; 0 = today's kernel with kIlRows_80), read off mmvq_il_parity --bench --emit-table
3718// --pf 0,3,4 on the CMP 170HX with the same 3% rule against native_mmvq; STRATA_MMVQ_IL_PF=1 takes it.  Every variant is
3719// bitwise native_mmvq (the tool checks every case, T 1-8, rows 1/2/4, each variant).
3720struct IlPf { int type; uint8_t v[3][5]; };
3721struct IlPf58 { int type; uint8_t v[4][5]; };
3722// Only Q6_K: the same variants are bitwise and measured for Q4_K / Q5_K / IQ4_XS too, but there they tie today's kernel
3723// within the run-to-run noise (their emitted cells flip between 0 and a variant), so those types keep kIlRows_80.
3724constexpr IlPf kIlPf_80[] = {
3725    {14, {{0x31, 0x42, 0x32, 0x42, 0x42}, {0x31, 0x41, 0x32, 0x32, 0x41}, {0x31, 0x41, 0x32, 0x32, 0x32}}},   // Q6_K
3726};
3727constexpr IlPf58 kIlPf58_80[] = {   // (rows 4 runs as 2 at 5+ columns, so the emitted 0x34 cells are written 0x32)
3728    {14, {{0x31, 0x42, 0x32, 0x32, 0x32}, {0x31, 0x31, 0x32, 0x32, 0x32}, {0x31, 0x31, 0x02, 0x32, 0x02}, {0x31, 0x31, 0x31, 0x31, 0x31}}},   // Q6_K
3729};
3730// Turing (sm_75): read off mmvq_il_parity --bench --emit-table on an RTX 2080 Ti 22 GB (SM 1650 MHz), the same 3% rule.
3731// The plain multi-column kernels are bound by dp4a throughput on Turing from 2 columns on (IQ4_XS 2560x10240 at 4
3732// columns 81.1 -> 37.4 us, the Q5_K head 1671 -> 1045 us); bitwise equal to native_mmvq.  No one-column table here:
3733// the engine's dedicated single-column kernels (native_q3_k_mmvq) sum in another order, and the gain was 0.5%.
3734constexpr IlRows kIlRows_75[] = {
3735    {23, {{2, 2, 2, 2, 2}, {2, 2, 4, 2, 4}, {2, 2, 2, 2, 2}}},   // IQ4_XS
3736    {12, {{0, 4, 2, 4, 4}, {1, 2, 2, 2, 2}, {1, 2, 2, 2, 2}}},   // Q4_K
3737    {13, {{0, 4, 2, 2, 4}, {1, 4, 2, 2, 2}, {1, 1, 2, 2, 2}}},   // Q5_K
3738    {14, {{0, 0, 1, 2, 1}, {0, 2, 2, 4, 4}, {0, 4, 4, 4, 4}}},   // Q6_K
3739    {11, {{1, 2, 4, 4, 4}, {1, 2, 4, 4, 4}, {1, 2, 2, 2, 2}}},   // Q3_K
3740};
3741// 147-verify: 5-8 columns (a verify window of 5+ rows) by n_out class, per architecture; 0 = native_mmvq's kernels.  Every
3742// choice is bitwise native_mmvq's output (mmvq_il_parity, T 1-8), so a table is only speed.  Measured on an RTX PRO 5000
3743// Blackwell (sm_120) with mmvq_il_parity --bench --emit-table; other cards have no table yet and keep native_mmvq's
3744// kernels at 5+ columns.  STRATA_MMVQ_IL_WIDE=0 turns the 5-8 column path off.
3745struct IlRows58 { int type; uint8_t r[4][5]; };
3746constexpr IlRows58 kIlRows58_120[] = {   // 4 = 2 rows a warp here (launch_il_rows)
3747    {23, {{0, 4, 4, 4, 4}, {0, 4, 2, 4, 2}, {0, 4, 2, 4, 2}, {0, 4, 2, 2, 2}}},   // IQ4_XS
3748    {12, {{0, 2, 4, 4, 4}, {0, 4, 4, 4, 4}, {0, 2, 2, 2, 2}, {0, 4, 2, 4, 4}}},   // Q4_K
3749    {13, {{0, 2, 2, 2, 4}, {0, 4, 2, 4, 2}, {0, 2, 4, 2, 2}, {0, 2, 4, 2, 2}}},   // Q5_K
3750    {14, {{0, 2, 4, 4, 4}, {0, 4, 2, 4, 2}, {0, 2, 4, 2, 2}, {0, 4, 4, 4, 2}}},   // Q6_K
3751    {11, {{0, 2, 4, 2, 4}, {0, 2, 2, 4, 4}, {0, 2, 2, 2, 4}, {0, 4, 2, 2, 2}}},   // Q3_K
3752};
3753constexpr IlRows58 kIlRows58_80[] = {   // CMP 170HX, as kIlRows_80
3754    {23, {{0, 4, 4, 2, 2}, {0, 2, 4, 4, 4}, {0, 2, 4, 1, 1}, {1, 4, 1, 1, 1}}},   // IQ4_XS
3755    {12, {{0, 0, 4, 2, 2}, {0, 2, 4, 2, 2}, {0, 2, 4, 4, 4}, {0, 2, 2, 4, 4}}},   // Q4_K
3756    {13, {{0, 0, 4, 2, 2}, {0, 4, 2, 2, 2}, {0, 4, 4, 2, 4}, {0, 2, 4, 4, 2}}},   // Q5_K
3757    {14, {{0, 0, 4, 2, 4}, {0, 0, 2, 2, 2}, {0, 2, 2, 2, 2}, {0, 0, 4, 2, 4}}},   // Q6_K
3758    {11, {{0, 0, 4, 2, 4}, {0, 0, 4, 1, 4}, {0, 0, 1, 1, 1}, {1, 1, 1, 1, 1}}},   // Q3_K
3759};
3760struct Il58Arch { int cc; const IlRows58* t; size_t n; };
3761constexpr Il58Arch kIl58Arch[] = {
3762    {80, kIlRows58_80, sizeof(kIlRows58_80) / sizeof(IlRows58)},
3763    {120, kIlRows58_120, sizeof(kIlRows58_120) / sizeof(IlRows58)},
3764    {1201, kIlRows58_120, sizeof(kIlRows58_120) / sizeof(IlRows58)},   // a 12.0 card with 80+ SMs (il_cc)
3765};
3766// One column: rows a warp by n_out class, 0 = native_mmvq's single-column kernels (STRATA_MMVQ_IL_T1=0 turns this off).
3767struct Il1Rows { int type; uint8_t r[5]; };
3768constexpr Il1Rows kIl1Rows_86[] = {
3769    {11, {0, 1, 1, 1, 1}},   // Q3_K: 2560x10240 60 -> 43 us, 6144x2560 30 -> 26 us on the A4000
3770};
3771// Ada (sm_89): the RTX 4070 and the RTX 4080 runs gave the same one-column row (only Q3_K takes the interleaved kernel)
3772constexpr Il1Rows kIl1Rows_89[] = {
3773    {11, {0, 0, 1, 1, 1}},   // Q3_K
3774};
3775// Tesla P40 (sm_61), the same three runs: IQ4_XS 2560x10240 102 -> 58 us, the Q5_K head 1754 -> 1507 us
3776constexpr Il1Rows kIl1Rows_61[] = {
3777    {23, {2, 2, 4, 4, 4}},   // IQ4_XS
3778    {13, {0, 0, 0, 2, 2}},   // Q5_K
3779    {11, {0, 0, 2, 2, 2}},   // Q3_K
3780};
3781constexpr Il1Rows kIl1Rows_80[] = {   // CMP 170HX, as kIlRows_80
3782    {23, {0, 0, 1, 4, 1}},   // IQ4_XS
3783    {12, {0, 0, 2, 2, 2}},   // Q4_K
3784    {13, {0, 0, 0, 4, 1}},   // Q5_K
3785    {11, {0, 0, 2, 2, 2}},   // Q3_K
3786};
3787struct Il1Arch { int cc; const Il1Rows* t; size_t n; };
3788constexpr Il1Arch kIl1Arch[] = {
3789    {80, kIl1Rows_80, sizeof(kIl1Rows_80) / sizeof(Il1Rows)},
3790    {61, kIl1Rows_61, sizeof(kIl1Rows_61) / sizeof(Il1Rows)},
3791    {86, kIl1Rows_86, sizeof(kIl1Rows_86) / sizeof(Il1Rows)},
3792    {89, kIl1Rows_89, sizeof(kIl1Rows_89) / sizeof(Il1Rows)},   // Ada: the RTX 4070 and 4080 agree
3793};
3794bool il_env_on(const char* name) {
3795    const char* v = std::getenv(name);
3796    return v == nullptr || v[0] != '0';
3797}
3798bool il_t1_on() { static const bool on = il_env_on("STRATA_MMVQ_IL_T1"); return on; }
3799bool il_q3k_on() { static const bool on = il_env_on("STRATA_MMVQ_IL_Q3K"); return on; }
3800// #3453: sm_89's own tables (kIlRows_89 / kIl1Rows_89) are ON by default on compute capability 8.9 only (owner decision, 0.2.7; no sm_89 card
3801// has run mmvq_il_parity or an end-to-end A/B for us, the reporter tests and reports back).  STRATA_MMVQ_IL_89=0 gives an Ada card what it
3802// answered before (the shared table, no one-column row) and so does STRATA_DEFAULTS=026; STRATA_MMVQ_IL_89=1 wins over that master switch
3803// (sm120_series.hpp mmvq_il_89_resolve).  Cached once; the lookup runs on the host once a launch.
3804bool il_89_opt_in() {
3805    static const bool on = strata::mmvq_il_89_resolve(std::getenv("STRATA_MMVQ_IL_89"), false, 89, strata::qwen_defaults_026());
3806    return on;
3807}
3808struct IlArch { int cc; const IlRows* t; size_t n; };
3809constexpr IlArch kIlArch[] = {
3810    {60, kIlRows_60, sizeof(kIlRows_60) / sizeof(IlRows)},   // Pascal GP100: measured on a Tesla P100
3811    {61, kIlRows_61, sizeof(kIlRows_61) / sizeof(IlRows)},   // Pascal with dp4a: measured on a Tesla P40
3812    {75, kIlRows_75, sizeof(kIlRows_75) / sizeof(IlRows)},   // Turing: measured on an RTX 2080 Ti
3813    {70, kIlRows_70, sizeof(kIlRows_70) / sizeof(IlRows)},   // Volta: PR 1401, measured on a V100-SXM2
3814    {80, kIlRows_80, sizeof(kIlRows_80) / sizeof(IlRows)},   // sm_80: measured on a CMP 170HX
3815    {86, kIlRows_86, sizeof(kIlRows_86) / sizeof(IlRows)},   // 143-dense: RTX A4000 with the real shapes (Q3_K added)
3816    {89, kIlRows_89, sizeof(kIlRows_89) / sizeof(IlRows)},   // Ada: the cells where an RTX 4070 and an RTX 4080 agree
3817    // 147-verify: RTX PRO 5000 Blackwell (110 SMs).  Only 12.0 cards with 80+ SMs (il_cc's 1201) take it: the shared table
3818    // was measured on an RTX 5070 (48 SMs) and stays that card's
3819    {1201, kIlRows_120, sizeof(kIlRows_120) / sizeof(IlRows)},
3820};
3821// STRATA_MMVQ_IL_ROWS="type:ncols:r0,r1,r2,r3,r4;..." overrides single rows of the table for every card (type = ggml
3822// type 23/12/13/14, ncols 2-4, r* = rows a warp 0/1/2/4 for the five n_out classes).  Parsed once.
3823struct IlEnvRow { int type, ncols; uint8_t r[5]; };
3824const std::vector<IlEnvRow>& il_env_rows() {
3825    static const std::vector<IlEnvRow> v = [] {
3826        std::vector<IlEnvRow> out;
3827        const char* e = std::getenv("STRATA_MMVQ_IL_ROWS");
3828        if (!e) return out;
3829        std::string str(e);
3830        size_t pos = 0;
3831        while (pos < str.size()) {
3832            size_t end = str.find(';', pos);
3833            if (end == std::string::npos) end = str.size();
3834            int t = 0, n = 0, r[5] = {0, 0, 0, 0, 0}, used = 0;
3835            if (std::sscanf(str.substr(pos, end - pos).c_str(), "%d:%d:%d,%d,%d,%d,%d%n", &t, &n, &r[0], &r[1], &r[2], &r[3],
3836                            &r[4], &used) >= 7 && n >= 1 && n <= 4) {
3837                IlEnvRow x{t, n, {}};
3838                bool ok = true;
3839                for (int i = 0; i < 5; ++i) { ok = ok && (r[i] == 0 || r[i] == 1 || r[i] == 2 || r[i] == 4); x.r[i] = (uint8_t) r[i]; }
3840                if (ok) out.push_back(x);
3841                else std::fprintf(stderr, "strata: STRATA_MMVQ_IL_ROWS: rows must be 0/1/2/4 - entry ignored\n");
3842            } else {
3843                std::fprintf(stderr, "strata: STRATA_MMVQ_IL_ROWS: cannot read '%s' (type:ncols:r0,r1,r2,r3,r4) - ignored\n",
3844                             str.substr(pos, end - pos).c_str());
3845            }
3846            pos = end + 1;
3847        }
3848        return out;
3849    }();
3850    return v;
3851}
3852}  // namespace
3853// The rows a warp for a card of compute capability `cc` (major * 10 + minor); 0: native_mmvq's kernels.  Pure, so a test
3854// can check every architecture's table without that card.
3855int native_mmvq_il_rows_for(int cc, int type, int ncols, int n_out) {
3856    if (ncols < 1 || ncols > 8) return 0;
3857    const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4;
3858    if (ncols > 4) {   // 147-verify: 5..8 columns, only where a card measured its table
3859        static const bool wide = il_env_on("STRATA_MMVQ_IL_WIDE");
3860        if (!wide) return 0;
3861        if (type == 11 && !il_q3k_on()) return 0;
3862        for (const Il58Arch& a : kIl58Arch)
3863            if (a.cc == cc)
3864                for (size_t i = 0; i < a.n; ++i)
3865                    if (a.t[i].type == type) return a.t[i].r[ncols - 5][cls];
3866        return 0;
3867    }
3868    for (const IlEnvRow& e : il_env_rows())
3869        if (e.type == type && e.ncols == ncols) return e.r[cls];
3870    if (ncols == 1) {   // 143-dense: one column (the plain q8_1 blocks, no interleaved copy); STRATA_MMVQ_IL_T1=0 turns it off
3871        if (!il_t1_on()) return 0;
3872        for (const Il1Arch& a : kIl1Arch)
3873            if (a.cc == cc && (cc != 89 || il_89_opt_in()))
3874                for (size_t i = 0; i < a.n; ++i)
3875                    if (a.t[i].type == type) return a.t[i].r[cls];
3876        return 0;
3877    }
3878    if (type == 11 && !il_q3k_on()) return 0;   // STRATA_MMVQ_IL_Q3K=0: Q3_K keeps native_mmvq's kernels
3879    const IlRows* t = kIlRowsShared;
3880    size_t n = sizeof(kIlRowsShared) / sizeof(IlRows);
3881    static const bool own120 = il_env_on("STRATA_MMVQ_IL_120");   // 147-verify: =0 gives a big 12.0 card the shared table again
3882    for (const IlArch& a : kIlArch)
3883        if (a.cc == cc && a.t != nullptr && (cc != 1201 || own120) && (cc != 89 || il_89_opt_in())) { t = a.t; n = a.n; }
3884    for (size_t i = 0; i < n; ++i)
3885        if (t[i].type == type) return t[i].r[ncols - 2][cls];
3886    return 0;
3887}
3888namespace {
3889int il_cc() {
3890    static int cc[16] = {};   // by device ordinal, 0 unknown
3891    int dev = 0;
3892    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return 0;
3893    if (cc[dev] == 0) {
3894        int maj = 0, mnr = 0;
3895        if (cudaDeviceGetAttribute(&maj, cudaDevAttrComputeCapabilityMajor, dev) != cudaSuccess ||
3896            cudaDeviceGetAttribute(&mnr, cudaDevAttrComputeCapabilityMinor, dev) != cudaSuccess) { cudaGetLastError(); return 0; }
3897        cc[dev] = maj * 10 + mnr;
3898        // 147-verify: a 12.0 card with 80+ SMs (RTX PRO 5000 / 6000, RTX 5080 / 5090) answers 1201, its own table's key;
3899        // a smaller one (RTX 5070: 48 SMs) keeps 120 and the shared table it was measured into
3900        int sms = 0;
3901        if (cc[dev] == 120 && cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev) == cudaSuccess && sms >= 80)
3902            cc[dev] = 1201;
3903        // STRATA_MMVQ_IL_SM80=0: an sm_80 card takes the shared table as before kIlRows_80 (A/B)
3904        if (cc[dev] == 80 && !strata::sm80_default_on(std::getenv("STRATA_MMVQ_IL_SM80"), strata::qwen_defaults_026())) cc[dev] = 81;   // =0 or STRATA_DEFAULTS=026
3905        cudaGetLastError();
3906    }
3907    return cc[dev];
3908}
3909int il_rows(int type, int ncols, int n_out) { return native_mmvq_il_rows_for(il_cc(), type, ncols, n_out); }
3910int il_pf_table(int type, int ncols, int n_out) {
3911    if (il_cc() != 80 || ncols < 2 || ncols > 8) return 0;   // only the CMP 170HX measured one
3912    const int cls = n_out < 2048 ? 0 : n_out < 4096 ? 1 : n_out < 8192 ? 2 : n_out < 12288 ? 3 : 4;
3913    if (ncols <= 4) {
3914        for (const IlPf& t : kIlPf_80)
3915            if (t.type == type) return t.v[ncols - 2][cls];
3916    } else {
3917        for (const IlPf58& t : kIlPf58_80)
3918            if (t.type == type) return t.v[ncols - 5][cls];
3919    }
3920    return 0;
3921}
3922int g_tune_rows = 0;   // native_mmvq_il_tune (tests, benchmarks): rows a warp for every shape (0: the table)
3923}  // namespace
3924void native_mmvq_il_tune(int rows) { g_tune_rows = rows; }
3925void native_mmvq_il_pf(int pf) { g_il_pf = pf; }
3926
3927namespace {
3928// sm_80 and newer (measured on sm_86 and sm_120), Volta (sm_70) and Pascal (sm_60, sm_61), each with its own table
3929// above; Turing keeps native_mmvq's kernels unless STRATA_SM75_PERF=1 (kIlRows_75)
3930// Volta (PR 1401): opt-in with STRATA_SM70_TABLE=1 until the author confirms on a V100 with the final code
3931bool sm70_opt_in() { const char* v = std::getenv("STRATA_SM70_TABLE"); return v != nullptr && std::atoi(v) != 0; }
3932// Pascal (sm_60, GP100): the same interleaved kernels (bitwise equal to native_mmvq's, mmvq_il_parity), its own table
3933// kIlRows_60.  STRATA_SM60_TABLE=0 keeps native_mmvq's kernels on a P100; any other value (or unset) uses the table.
3934// STRATA_SM75_IL=0 / 1 forces the table off / on; unset it follows STRATA_SM75_PERF=1 (Turing only)
3935bool sm75_il_on(int major, int minor) { return strata::sm75_switch("STRATA_SM75_IL", major, minor); }
3936bool sm60_table_on() { const char* v = std::getenv("STRATA_SM60_TABLE"); return v == nullptr || std::atoi(v) != 0; }
3937// Pascal (sm_61: Tesla P40 / P4, GTX 10 series; native dp4a): the same interleaved kernels (bitwise equal to
3938// native_mmvq's, mmvq_il_parity), its own table kIlRows_61.  STRATA_SM61_TABLE=0 keeps native_mmvq's kernels.
3939bool sm61_table_on() { const char* v = std::getenv("STRATA_SM61_TABLE"); return v == nullptr || std::atoi(v) != 0; }
3940bool il_arch_ok() {
3941    static int ok[16] = {};   // 0 unknown, 1 yes, -1 no, by device ordinal
3942    int dev = 0;
3943    if (cudaGetDevice(&dev) != cudaSuccess || dev < 0 || dev >= 16) return false;
3944    if (ok[dev] == 0) {
3945        int major = 0;
3946        int minor = 0;
3947        cudaDeviceGetAttribute(&minor, cudaDevAttrComputeCapabilityMinor, dev);
3948        ok[dev] = (cudaDeviceGetAttribute(&major, cudaDevAttrComputeCapabilityMajor, dev) == cudaSuccess &&
3949                   (major >= 8 || (major == 7 && minor == 0 && sm70_opt_in()) || (major == 7 && minor == 5 && sm75_il_on(major, minor)) ||
3950                    (major == 6 && minor == 0 && sm60_table_on()) || (major == 6 && minor == 1 && sm61_table_on()))) ? 1 : -1;
3951    }
3952    return ok[dev] > 0;
3953}
3954}  // namespace
3955
3956bool native_mmvq_il_supported(int ggml_type, int ncols, int n_out) {
3957    if (ncols < 1 || ncols > 8 || !g_multi_exact || !il_arch_ok()) return false;
3958    return (g_tune_rows ? g_tune_rows : il_rows(ggml_type, ncols, n_out)) != 0 &&
3959           (ggml_type == 23 || ggml_type == 12 || ggml_type == 13 || ggml_type == 14 || ggml_type == 11);
3960}
3961
3962void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, const void* x_il, float* y, int n_in,
3963                    int n_out, int ncols, void* stream) {
3964    if (!native_mmvq_il_supported(ggml_type, ncols, n_out)) {
3965        native_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream);
3966        return;
3967    }
3968    const int r = g_tune_rows ? g_tune_rows : il_rows(ggml_type, ncols, n_out);
3969    strata::dispatch::kernel(strata::dispatch::kDense, 10 + r, ggml_type, n_in, n_out, ncols);   // BW-MEASURE: the interleaved MMVQ, r rows a warp
3970    validate_shape(n_in, ncols, QK);
3971    validate_pointer(weights);
3972    if (ncols == 1) x_il = x_q8_1;   // one column: the plain blocks, no interleaved copy
3973    validate_pointer(x_il);
3974    validate_pointer(y);
3975    validate_stream(stream);
3976    const auto s = static_cast<cudaStream_t>(stream);
3977    switch (ggml_type) {
3978    case 23: launch_il_rows<IlIQ4XS>(r, weights, x_il, y, n_in, n_out, ncols, s); break;
3979    case 12: launch_il_rows<IlQ4K>(r, weights, x_il, y, n_in, n_out, ncols, s); break;
3980    case 13: launch_il_rows<IlQ5K>(r, weights, x_il, y, n_in, n_out, ncols, s); break;
3981    case 14: launch_il_rows<IlQ6K>(r, weights, x_il, y, n_in, n_out, ncols, s); break;
3982    case 11: launch_il_rows<IlQ3K>(r, weights, x_il, y, n_in, n_out, ncols, s); break;
3983    }
3984    launch_check();
3985}
3986
3987#else  // HIP: no interleaved path
3988std::size_t native_q8_1_il_bytes(int n_in, int ncols) { return native_q8_1_bytes(n_in, ncols) * 2; }
3989void native_quantize_q8_1_il(const float*, void*, void*, int, int, void*) {
3990    throw std::invalid_argument("native_quantize_q8_1_il is CUDA only");
3991}
3992void native_q8_1_interleave(const void*, void*, int, int, void*) {
3993    throw std::invalid_argument("native_q8_1_interleave is CUDA only");
3994}
3995bool native_mmvq_il_supported(int, int, int) { return false; }
3996int native_mmvq_il_rows_for(int, int, int, int) { return 0; }
3997void native_mmvq_il(int ggml_type, const void* weights, const void* x_q8_1, const void*, float* y, int n_in, int n_out,
3998                    int ncols, void* stream) {
3999    native_mmvq(ggml_type, weights, x_q8_1, y, n_in, n_out, ncols, stream);
4000}
4001void native_mmvq_il_tune(int) {}
4002void native_mmvq_il_pf(int) {}
4003#endif  // !__HIPCC__
4004
4005} // namespace strata::kernels