okami.mom/strata

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

Niko1221Merge f-0216-cpu into f-0216-allf2eedfe9f

main
48.6 KiB858 linesraw
1// src/kernels/cpu/iq_avx512.cpp - plan v0.3 P6: the i-quant expert rows in 512-bit lanes, several tokens at once.
2//
3// ggml-cpu's x86 dot products for these formats are AVX2 and single-token: every token re-decodes the weights
4// and a sign is applied with five instructions per 32 values.  Here 64 values are decoded once (8 or 16 grid
5// lookups, one 64-bit sign mask, one vector of scales) and every token applies them with a masked subtract, a
6// `maddubs` and a `madd`.  The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references): integer sums
7// per block, times d_x * d_y * the format's constant - only the order of the float additions differs.
8//
9// Formats: IQ2_XXS (16), IQ2_XS (17), IQ3_XXS (18), IQ3_S (21), IQ2_S (22).  IQ1_M stays on ggml-cpu (no shipped
10// model has IQ1_M expert rows: the 'Coder IQ1_M' pack's gate/up are IQ2_S / IQ3_XXS / IQ3_S).
11#include "strata/kernels/cpu/iq_avx512.hpp"
12#include "strata/kernels/cpu/expert_layout.hpp"
13
14#define GGML_COMMON_DECL_CPP
15#define GGML_COMMON_IMPL_CPP
16#include "ggml-common.h"
17
18#include <immintrin.h>
19#if defined(_MSC_VER)
20#include <intrin.h>
21#else
22#include <cpuid.h>
23#endif
24
25#include <cmath>
26#include <cstdlib>
27#include <cstring>
28#include <vector>
29
30namespace strata::kernels::cpu {
31namespace {
32
33inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); }
34inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; }
35inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; }
36inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; }
37
38// E-2: the IQ3 grids by one AVX-512 gather (the same words, the same results) - measured 3-5% SLOWER than the scalar
39// lookups on a Ryzen 5 7600 (Zen 4 gathers are microcoded), so opt-in: STRATA_IQ_GATHER=1
40// 0.2.5: DEFAULT on where gathers are fast (Intel server and HEDT cores with AVX-512: cpu_gather_fast), off on Zen 4 (microcoded);
41// STRATA_IQ_GATHER=1 / 0 force it either way.  The same words are loaded, so the results are bit for bit the scalar decode's.
42const bool gather = [] {
43    const char* v = std::getenv("STRATA_IQ_GATHER");
44    return v != nullptr && v[0] != '\0' ? std::atoi(v) != 0 : cpu_gather_fast();
45}();
46// the grid lookups by one 64-bit gather of eight entries (IQ2_XXS / IQ2_XS / IQ2_S): `idx` = eight 32-bit indices
47inline __m512i gather64(__m256i idx, const void* grid) { return _mm512_i32gather_epi64(idx, grid, 8); }
48// E-2: software prefetch distance in bytes (STRATA_IQ_PREFETCH; 0 = off): -2-3% gate/up time on IQ3_S decode
49// (the rows are read at ~30 GB/s by 6 cores, near what DDR5 with 4 KB pages gives: the pool is memory-bound)
50const int prefetch_ahead = [] {
51    const char* v = std::getenv("STRATA_IQ_PREFETCH");
52    return v ? std::atoi(v) : 2048;
53}();
54
55// lanes 0-7 -> s0, 8-15 -> s1, 16-23 -> s2, 24-31 -> s3 (int16 lanes of a maddubs result: two values each)
56inline __m512i scales4(int s0, int s1, int s2, int s3) {
57    const __m512i idx = _mm512_set_epi16(3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1,
58                                         0, 0, 0, 0, 0, 0, 0, 0);
59    const uint64_t packed = (uint64_t) (uint16_t) s0 | ((uint64_t) (uint16_t) s1 << 16) |
60                            ((uint64_t) (uint16_t) s2 << 32) | ((uint64_t) (uint16_t) s3 << 48);
61    return _mm512_permutexvar_epi16(idx, _mm512_set1_epi64((long long) packed));
62}
63
64// ---- per format: 64 values (chunk j of a 256-value block) -> grid magnitudes, sign mask, scales
65template <int TY> struct Fmt;
66
67template <> struct Fmt<16> {   // IQ2_XXS: d, qs[32] u16
68    static constexpr int bytes = 66;
69    static constexpr float K = 0.125f;
70    static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
71        const uint8_t* q = b + 2 + 16 * j;
72        const uint32_t a0 = u32(q), a1 = u32(q + 4), b0 = u32(q + 8), b1 = u32(q + 12);
73        g = gather ? gather64(_mm256_cvtepu8_epi32(_mm_cvtsi64_si128((long long) ((uint64_t) a0 | ((uint64_t) b0 << 32)))), iq2xxs_grid)
74                   : _mm512_set_epi64((long long) iq2xxs_grid[b0 >> 24], (long long) iq2xxs_grid[(b0 >> 16) & 255],
75                             (long long) iq2xxs_grid[(b0 >> 8) & 255], (long long) iq2xxs_grid[b0 & 255],
76                             (long long) iq2xxs_grid[a0 >> 24], (long long) iq2xxs_grid[(a0 >> 16) & 255],
77                             (long long) iq2xxs_grid[(a0 >> 8) & 255], (long long) iq2xxs_grid[a0 & 255]);
78        const uint64_t s = (uint64_t) ksigns_iq2xs[a1 & 127] | ((uint64_t) ksigns_iq2xs[(a1 >> 7) & 127] << 8) |
79                           ((uint64_t) ksigns_iq2xs[(a1 >> 14) & 127] << 16) | ((uint64_t) ksigns_iq2xs[(a1 >> 21) & 127] << 24) |
80                           ((uint64_t) ksigns_iq2xs[b1 & 127] << 32) | ((uint64_t) ksigns_iq2xs[(b1 >> 7) & 127] << 40) |
81                           ((uint64_t) ksigns_iq2xs[(b1 >> 14) & 127] << 48) | ((uint64_t) ksigns_iq2xs[(b1 >> 21) & 127] << 56);
82        m = _cvtu64_mask64(s);
83        const int sa = 2 * (int) (a1 >> 28) + 1, sb = 2 * (int) (b1 >> 28) + 1;
84        sc = scales4(sa, sa, sb, sb);
85    }
86};
87
88template <> struct Fmt<17> {   // IQ2_XS: d, qs[32] u16 (9-bit grid index + 7-bit sign index), scales[8]
89    static constexpr int bytes = 74;
90    static constexpr float K = 0.125f;
91    static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
92        const uint8_t* q = b + 2 + 16 * j;
93        uint16_t v[8];
94        std::memcpy(v, q, 16);
95        g = gather ? gather64(_mm256_and_si256(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) q)), _mm256_set1_epi32(511)), iq2xs_grid)
96                   : _mm512_set_epi64((long long) iq2xs_grid[v[7] & 511], (long long) iq2xs_grid[v[6] & 511],
97                             (long long) iq2xs_grid[v[5] & 511], (long long) iq2xs_grid[v[4] & 511],
98                             (long long) iq2xs_grid[v[3] & 511], (long long) iq2xs_grid[v[2] & 511],
99                             (long long) iq2xs_grid[v[1] & 511], (long long) iq2xs_grid[v[0] & 511]);
100        uint64_t s = 0;
101        for (int l = 0; l < 8; ++l) s |= (uint64_t) ksigns_iq2xs[v[l] >> 9] << (8 * l);
102        m = _cvtu64_mask64(s);
103        const uint8_t s0 = b[66 + 2 * j], s1 = b[66 + 2 * j + 1];
104        sc = scales4(2 * (s0 & 15) + 1, 2 * (s0 >> 4) + 1, 2 * (s1 & 15) + 1, 2 * (s1 >> 4) + 1);
105    }
106};
107
108template <> struct Fmt<22> {   // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes), qh[8], scales[8]
109    static constexpr int bytes = 82;
110    static constexpr float K = 0.125f;
111    static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
112        const uint8_t* qs = b + 2 + 8 * j;
113        const uint8_t h0 = b[66 + 2 * j], h1 = b[66 + 2 * j + 1];
114        if (gather) {   // the 10-bit indices: the byte plus two high bits from qh (h0 for lanes 0-3, h1 for 4-7), one 64-bit gather
115            const __m256i hi = _mm256_and_si256(_mm256_sllv_epi32(_mm256_setr_epi32(h0, h0, h0, h0, h1, h1, h1, h1),
116                                                                   _mm256_setr_epi32(8, 6, 4, 2, 8, 6, 4, 2)), _mm256_set1_epi32(0x300));
117            g = gather64(_mm256_or_si256(_mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) qs)), hi), iq2s_grid);
118        } else
119        g = _mm512_set_epi64((long long) iq2s_grid[qs[7] | ((h1 << 2) & 0x300)], (long long) iq2s_grid[qs[6] | ((h1 << 4) & 0x300)],
120                             (long long) iq2s_grid[qs[5] | ((h1 << 6) & 0x300)], (long long) iq2s_grid[qs[4] | ((h1 << 8) & 0x300)],
121                             (long long) iq2s_grid[qs[3] | ((h0 << 2) & 0x300)], (long long) iq2s_grid[qs[2] | ((h0 << 4) & 0x300)],
122                             (long long) iq2s_grid[qs[1] | ((h0 << 6) & 0x300)], (long long) iq2s_grid[qs[0] | ((h0 << 8) & 0x300)]);
123        m = _cvtu64_mask64(u64(b + 2 + 32 + 8 * j));
124        const uint8_t s0 = b[74 + 2 * j], s1 = b[74 + 2 * j + 1];
125        sc = scales4(2 * (s0 & 15) + 1, 2 * (s0 >> 4) + 1, 2 * (s1 & 15) + 1, 2 * (s1 >> 4) + 1);
126    }
127};
128
129template <> struct Fmt<18> {   // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-bit sign index + 4-bit scale)
130    static constexpr int bytes = 98;
131    static constexpr float K = 0.25f;
132    static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
133        const uint8_t* q = b + 2 + 16 * j;
134        // E-2: one gather of the 16 grid words (the scalar lookups assembled with set_epi32 cost ~30 uops)
135        g = gather ? _mm512_i32gather_epi32(_mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q)), iq3xxs_grid, 4)
136                   : _mm512_set_epi32((int) iq3xxs_grid[q[15]], (int) iq3xxs_grid[q[14]], (int) iq3xxs_grid[q[13]], (int) iq3xxs_grid[q[12]],
137                             (int) iq3xxs_grid[q[11]], (int) iq3xxs_grid[q[10]], (int) iq3xxs_grid[q[9]], (int) iq3xxs_grid[q[8]],
138                             (int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]],
139                             (int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]);
140        const uint32_t a = u32(b + 2 + 64 + 8 * j), c = u32(b + 2 + 64 + 8 * j + 4);
141        const uint64_t s = (uint64_t) ksigns_iq2xs[a & 127] | ((uint64_t) ksigns_iq2xs[(a >> 7) & 127] << 8) |
142                           ((uint64_t) ksigns_iq2xs[(a >> 14) & 127] << 16) | ((uint64_t) ksigns_iq2xs[(a >> 21) & 127] << 24) |
143                           ((uint64_t) ksigns_iq2xs[c & 127] << 32) | ((uint64_t) ksigns_iq2xs[(c >> 7) & 127] << 40) |
144                           ((uint64_t) ksigns_iq2xs[(c >> 14) & 127] << 48) | ((uint64_t) ksigns_iq2xs[(c >> 21) & 127] << 56);
145        m = _cvtu64_mask64(s);
146        const int sa = 2 * (int) (a >> 28) + 1, sb = 2 * (int) (c >> 28) + 1;
147        sc = scales4(sa, sa, sb, sb);
148    }
149};
150
151template <> struct Fmt<21> {   // IQ3_S: d, qs[64], qh[8], signs[32], scales[4]
152    static constexpr int bytes = 110;
153    static constexpr float K = 1.0f;
154    static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
155        const uint8_t* q = b + 2 + 16 * j;
156        const uint32_t h0 = b[66 + 2 * j], h1 = b[66 + 2 * j + 1];
157        if (gather) {   // E-2: the 9-bit indices (the high bit from qh under a mask), one gather
158            __m512i idx = _mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q));
159            idx = _mm512_mask_add_epi32(idx, (__mmask16) (h0 | (h1 << 8)), idx, _mm512_set1_epi32(256));
160            g = _mm512_i32gather_epi32(idx, iq3s_grid, 4);
161        } else {
162#define G3(k, h, kk) (int) iq3s_grid[q[k] | (((h >> kk) & 1) << 8)]
163        g = _mm512_set_epi32(G3(15, h1, 7), G3(14, h1, 6), G3(13, h1, 5), G3(12, h1, 4),
164                             G3(11, h1, 3), G3(10, h1, 2), G3(9, h1, 1), G3(8, h1, 0),
165                             G3(7, h0, 7), G3(6, h0, 6), G3(5, h0, 5), G3(4, h0, 4),
166                             G3(3, h0, 3), G3(2, h0, 2), G3(1, h0, 1), G3(0, h0, 0));
167#undef G3
168        }
169        m = _cvtu64_mask64(u64(b + 74 + 8 * j));
170        const uint8_t s = b[106 + j];
171        const int sa = 2 * (s & 15) + 1, sb = 2 * (s >> 4) + 1;
172        sc = scales4(sa, sa, sb, sb);
173    }
174};
175
176// IQ4_XS (23): d, scales_h (u16), scales_l[4], qs[128].  Chunk j = the 64 values of two 32-value sub-blocks (2j, 2j+1): the
177// table lookup of the nibbles is one vpshufb in 512-bit lanes (kvalues_iq4nl broadcast to every lane), laid out as ggml's AVX2 dot lays
178// out its two 256-bit halves (low nibbles of 16 bytes, then the high nibbles), so the integer lanes line up with that dot's.
179// The decode of the nibble planes follows the layout of PR #5243 (bsorensen110); only this format's part is taken.
180template <> struct Fmt<23> {
181    static constexpr int bytes = 136;
182    static constexpr float K = 1.0f;
183    static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
184        const __m128i b0 = _mm_loadu_si128((const __m128i*) (b + 8 + 32 * j));
185        const __m128i b1 = _mm_loadu_si128((const __m128i*) (b + 24 + 32 * j));
186        const __m128i m4 = _mm_set1_epi8(0x0f);
187        const __m256i n0 = _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_and_si128(b0, m4)), _mm_and_si128(_mm_srli_epi16(b0, 4), m4), 1);
188        const __m256i n1 = _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_and_si128(b1, m4)), _mm_and_si128(_mm_srli_epi16(b1, 4), m4), 1);
189        const __m512i nib = _mm512_inserti64x4(_mm512_castsi256_si512(n0), n1, 1);
190        const __m512i lut = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*) kvalues_iq4nl));
191        const __m512i q4 = _mm512_shuffle_epi8(lut, nib);
192        g = _mm512_abs_epi8(q4);
193        m = _mm512_movepi8_mask(q4);
194        const uint8_t sl = b[4 + j];
195        const uint16_t sh = (uint16_t) (u16(b + 2) >> (4 * j));
196        const int ls0 = ((sl & 0x0f) | ((sh << 4) & 0x30)) - 32;
197        const int ls1 = ((sl >> 4) | ((sh << 2) & 0x30)) - 32;
198        sc = scales4(ls0, ls0, ls1, ls1);
199    }
200};
201
202template <bool Singleton> struct RowAccumulator;
203template <> struct RowAccumulator<false> { using Type = __m512; };
204template <> struct RowAccumulator<true> { using Type = __m256; };
205
206template <int TY, int NT, bool Singleton = false>
207inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) {
208    // Decode weights once for the group; select the accumulation order at compile time.
209    using Acc = typename RowAccumulator<Singleton>::Type;
210    Acc accf[NT];
211    for (int t = 0; t < NT; ++t) {
212        if constexpr (Singleton) accf[t] = _mm256_setzero_ps();
213        else accf[t] = _mm512_setzero_ps();
214    }
215    const __m512i zero = _mm512_setzero_si512();
216    for (int i = 0; i < nblocks; ++i) {
217        const uint8_t* blk = row + (size_t) i * Fmt<TY>::bytes;
218        // E-2: the weight rows stream from DRAM (4 KB pages when large pages are refused): ask for the bytes a few
219        // blocks ahead (the next row's start included) before the decode needs them
220        if (prefetch_ahead > 0) {
221            const uint8_t* ahead = blk + (size_t) prefetch_ahead;
222            _mm_prefetch((const char*) ahead, _MM_HINT_T0);
223            _mm_prefetch((const char*) ahead + 64, _MM_HINT_T0);
224        }
225        __m512i acci[NT];
226        for (int t = 0; t < NT; ++t) acci[t] = _mm512_setzero_si512();
227        for (int j = 0; j < 4; ++j) {
228            __m512i g, sc;
229            __mmask64 m;
230            Fmt<TY>::decode(blk, j, g, m, sc);
231            for (int t = 0; t < NT; ++t) {
232                const __m512i yv = _mm512_loadu_si512((const void*) (y[t][i].qs + 64 * j));
233                const __m512i ys = _mm512_mask_sub_epi8(yv, m, zero, yv);
234                acci[t] = _mm512_dpwssd_epi32(acci[t], _mm512_maddubs_epi16(g, ys), sc);
235            }
236        }
237        if constexpr (Singleton) {
238            const float dx = h2f(u16(blk));
239            for (int t = 0; t < NT; ++t) {
240                // Preserve ggml AVX2's eight integer lanes BEFORE floating conversion.
241                const __m256i folded = _mm256_add_epi32(_mm512_castsi512_si256(acci[t]),
242                                                       _mm512_extracti64x4_epi64(acci[t], 1));
243                accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d),
244                                         _mm256_cvtepi32_ps(folded), accf[t]);
245            }
246        } else {
247            const float dx = h2f(u16(blk)) * Fmt<TY>::K;
248            for (int t = 0; t < NT; ++t)
249                accf[t] = _mm512_fmadd_ps(_mm512_set1_ps(dx * y[t][i].d), _mm512_cvtepi32_ps(acci[t]), accf[t]);
250        }
251    }
252    if constexpr (Singleton) {
253        for (int t = 0; t < NT; ++t) {
254            __m128 sum = _mm256_extractf128_ps(accf[t], 1);
255            sum = _mm_add_ps(sum, _mm256_castps256_ps128(accf[t]));
256            sum = _mm_add_ps(sum, _mm_movehl_ps(sum, sum));
257            sum = _mm_add_ss(sum, _mm_movehdup_ps(sum));
258            res[t] = Fmt<TY>::K * _mm_cvtss_f32(sum);
259        }
260    } else {
261        for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(accf[t]);
262    }
263}
264
265template <int TY, int NT, bool Singleton = false>
266void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, float* const* ff,
267             int r0, int r1) {
268    const block_q8_K* y[NT];
269    for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
270    const int nb = n / QK_K;
271    float g[NT], u[NT];
272    for (int r = r0; r < r1; ++r) {
273        row_dot<TY, NT, Singleton>(blob + (size_t) r * gu_row, nb, y, g);
274        row_dot<TY, NT, Singleton>(blob + up_off + (size_t) r * gu_row, nb, y, u);
275        for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t];
276    }
277}
278
279template <int TY, int NT>
280void dot_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) {
281    const block_q8_K* y[NT];
282    for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
283    float res[NT];
284    for (int r = r0; r < r1; ++r) {
285        row_dot<TY, NT>(w + (size_t) r * row_bytes, n / QK_K, y, res);
286        for (int t = 0; t < NT; ++t) out[t][r] = res[t];
287    }
288}
289
290template <int TY, bool Singleton = false>
291void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
292                float* const* ff, int r0, int r1) {
293    switch (nt) {
294        case 1: gu_rows<TY, 1, Singleton>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
295        case 2: gu_rows<TY, 2, Singleton>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
296        case 3: gu_rows<TY, 3, Singleton>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
297        case 4: gu_rows<TY, 4, Singleton>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
298        case 5: gu_rows<TY, 5, Singleton>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
299        case 6: gu_rows<TY, 6, Singleton>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
300        case 7: gu_rows<TY, 7, Singleton>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
301        default: gu_rows<TY, 8, Singleton>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
302    }
303}
304
305template <int TY>
306void dot_rows_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0,
307                 int r1) {
308    switch (nt) {
309        case 1: dot_rows<TY, 1>(w, row_bytes, n, act, out, r0, r1); break;
310        case 2: dot_rows<TY, 2>(w, row_bytes, n, act, out, r0, r1); break;
311        case 3: dot_rows<TY, 3>(w, row_bytes, n, act, out, r0, r1); break;
312        case 4: dot_rows<TY, 4>(w, row_bytes, n, act, out, r0, r1); break;
313        default: for (int t0 = 0; t0 < nt; t0 += 4) {
314            const int k = nt - t0 < 4 ? nt - t0 : 4;
315            dot_rows_nt<TY>(k, w, row_bytes, n, act + t0, out + t0, r0, r1);
316        }
317    }
318}
319
320
321// The sign masks of IQ2_XXS / IQ2_XS / IQ3_XXS come from a 7-bit index whose 8th bit is the parity of the other seven (ksigns_iq2xs[i] =
322// i | parity(i) << 7).  The table needs a load and a few shifts and ors a group of eight values; popcount does it for all eight groups
323// of 64 values in one vector: measured on Zen 5, one-token IQ2_XXS rows 33 -> 45-50 GB/s (16 threads, DRAM-sized), cache-resident 16.8 -> 13.4 ns a block.
324// (AVX512_VPOPCNTDQ + VL: Zen 4, Zen 5, Ice Lake and later; iq512x_supported() asks for it.)
325inline __mmask64 sign_mask_from_idx(__m256i si) {
326    const __m256i par = _mm256_slli_epi32(_mm256_and_si256(_mm256_popcnt_epi32(si), _mm256_set1_epi32(1)), 7);
327    return _cvtu64_mask64((uint64_t) _mm_cvtsi128_si64(_mm256_cvtepi32_epi8(_mm256_or_si256(si, par))));
328}
329inline __m256i sign_idx_xxs(uint32_t lo4, uint32_t hi4) {   // four 7-bit fields of each of two words -> eight dwords
330    const __m256i w = _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_set1_epi32((int) lo4)), _mm_set1_epi32((int) hi4), 1);
331    return _mm256_and_si256(_mm256_srlv_epi32(w, _mm256_setr_epi32(0, 7, 14, 21, 0, 7, 14, 21)), _mm256_set1_epi32(127));
332}
333
334template <int TY> struct FmtX : Fmt<TY> {};
335template <> struct FmtX<16> : Fmt<16> {
336    static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
337        const uint8_t* q = b + 2 + 16 * j;
338        const uint32_t a0 = u32(q), a1 = u32(q + 4), b0 = u32(q + 8), b1 = u32(q + 12);
339        g = gather ? gather64(_mm256_cvtepu8_epi32(_mm_cvtsi64_si128((long long) ((uint64_t) a0 | ((uint64_t) b0 << 32)))), iq2xxs_grid)
340                   : _mm512_set_epi64((long long) iq2xxs_grid[b0 >> 24], (long long) iq2xxs_grid[(b0 >> 16) & 255],
341                             (long long) iq2xxs_grid[(b0 >> 8) & 255], (long long) iq2xxs_grid[b0 & 255],
342                             (long long) iq2xxs_grid[a0 >> 24], (long long) iq2xxs_grid[(a0 >> 16) & 255],
343                             (long long) iq2xxs_grid[(a0 >> 8) & 255], (long long) iq2xxs_grid[a0 & 255]);
344        m = sign_mask_from_idx(sign_idx_xxs(a1, b1));
345        const int sa = 2 * (int) (a1 >> 28) + 1, sb = 2 * (int) (b1 >> 28) + 1;
346        sc = scales4(sa, sa, sb, sb);
347    }
348};
349template <> struct FmtX<17> : Fmt<17> {
350    static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
351        const uint8_t* q = b + 2 + 16 * j;
352        uint16_t v[8];
353        std::memcpy(v, q, 16);
354        g = gather ? gather64(_mm256_and_si256(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) q)), _mm256_set1_epi32(511)), iq2xs_grid)
355                   : _mm512_set_epi64((long long) iq2xs_grid[v[7] & 511], (long long) iq2xs_grid[v[6] & 511],
356                             (long long) iq2xs_grid[v[5] & 511], (long long) iq2xs_grid[v[4] & 511],
357                             (long long) iq2xs_grid[v[3] & 511], (long long) iq2xs_grid[v[2] & 511],
358                             (long long) iq2xs_grid[v[1] & 511], (long long) iq2xs_grid[v[0] & 511]);
359        m = sign_mask_from_idx(_mm256_srli_epi32(_mm256_cvtepu16_epi32(_mm_loadu_si128((const __m128i*) q)), 9));
360        const uint8_t s0 = b[66 + 2 * j], s1 = b[66 + 2 * j + 1];
361        sc = scales4(2 * (s0 & 15) + 1, 2 * (s0 >> 4) + 1, 2 * (s1 & 15) + 1, 2 * (s1 >> 4) + 1);
362    }
363};
364template <> struct FmtX<18> : Fmt<18> {
365    static inline void decode(const uint8_t* b, int j, __m512i& g, __mmask64& m, __m512i& sc) {
366        const uint8_t* q = b + 2 + 16 * j;
367        g = gather ? _mm512_i32gather_epi32(_mm512_cvtepu8_epi32(_mm_loadu_si128((const __m128i*) q)), iq3xxs_grid, 4)
368                   : _mm512_set_epi32((int) iq3xxs_grid[q[15]], (int) iq3xxs_grid[q[14]], (int) iq3xxs_grid[q[13]], (int) iq3xxs_grid[q[12]],
369                             (int) iq3xxs_grid[q[11]], (int) iq3xxs_grid[q[10]], (int) iq3xxs_grid[q[9]], (int) iq3xxs_grid[q[8]],
370                             (int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]],
371                             (int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]);
372        const uint32_t a = u32(b + 2 + 64 + 8 * j), c = u32(b + 2 + 64 + 8 * j + 4);
373        m = sign_mask_from_idx(sign_idx_xxs(a, c));
374        const int sa = 2 * (int) (a >> 28) + 1, sb = 2 * (int) (c >> 28) + 1;
375        sc = scales4(sa, sa, sb, sb);
376    }
377};
378
379// ---- the DeepSeek CPU lane's exact rows (iq512x_rows): the same 64-value decode, but summed as ggml's AVX2 dots sum, so a
380// token's row is ggml-cpu's vec_dot bit for bit at any number of tokens: the integer sums of a block fold to ggml's eight lanes
381// (low half = the even 32-value chunk, high half = the odd one), the block scale is f16(d) * y.d, eight float lanes accumulate
382// across blocks, and K * ggml's hsum comes last.  vpdpwssd is the madd and the add in one.
383inline __m256i fold256(__m512i a) { return _mm256_add_epi32(_mm512_castsi512_si256(a), _mm512_extracti64x4_epi64(a, 1)); }
384
385inline float hsum8_ggml(__m256 x) {
386    __m128 s = _mm_add_ps(_mm256_extractf128_ps(x, 1), _mm256_castps256_ps128(x));
387    s = _mm_add_ps(s, _mm_movehl_ps(s, s));
388    s = _mm_add_ss(s, _mm_movehdup_ps(s));
389    return _mm_cvtss_f32(s);
390}
391
392template <int TY, int NT>
393inline void row_dot_x(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) {
394    __m256 accf[NT];
395    for (int t = 0; t < NT; ++t) accf[t] = _mm256_setzero_ps();
396    const __m512i zero = _mm512_setzero_si512();
397    for (int i = 0; i < nblocks; ++i) {
398        const uint8_t* blk = row + (size_t) i * FmtX<TY>::bytes;
399        if (prefetch_ahead > 0) {
400            const uint8_t* ahead = blk + (size_t) prefetch_ahead;
401            _mm_prefetch((const char*) ahead, _MM_HINT_T0);
402            _mm_prefetch((const char*) ahead + 64, _MM_HINT_T0);
403        }
404        __m512i acci[NT];
405        for (int t = 0; t < NT; ++t) acci[t] = _mm512_setzero_si512();
406        for (int j = 0; j < 4; ++j) {
407            __m512i g, sc;
408            __mmask64 m;
409            FmtX<TY>::decode(blk, j, g, m, sc);
410            for (int t = 0; t < NT; ++t) {
411                const __m512i yv = _mm512_loadu_si512((const void*) (y[t][i].qs + 64 * j));
412                const __m512i ys = _mm512_mask_sub_epi8(yv, m, zero, yv);
413                acci[t] = _mm512_dpwssd_epi32(acci[t], _mm512_maddubs_epi16(g, ys), sc);
414            }
415        }
416        const float dx = h2f(u16(blk));
417        for (int t = 0; t < NT; ++t)
418            accf[t] = _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(fold256(acci[t])), accf[t]);
419    }
420    for (int t = 0; t < NT; ++t) res[t] = FmtX<TY>::K * hsum8_ggml(accf[t]);
421}
422
423template <int TY, int NT>
424void dot_rows_x(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) {
425    const block_q8_K* y[NT];
426    for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
427    float res[NT];
428    for (int r = r0; r < r1; ++r) {
429        row_dot_x<TY, NT>(w + (size_t) r * row_bytes, n / QK_K, y, res);
430        for (int t = 0; t < NT; ++t) out[t][r] = res[t];
431    }
432}
433
434// many tokens an expert (the prompt): signed int8 weights decoded once per block, activations as u8 (q8 + 128, once a call),
435// sum(w * q) = sum(w * (q + 128)) - 128 * sum(w) with the second sum once a weight block; tokens in tiles of 16 and rows in
436// groups of 8 so the tile's slice of a block and the group's accumulators stay in L1 (the AVX2 form's layout)
437template <int TY>
438void dot_rows_wide(const uint8_t* w, size_t row_bytes, int n, const void* const* act, int T, float* const* out, int r0, int r1) {
439    constexpr int kTile = 16, kRows = 8;
440    const int nb = n / QK_K;
441    static thread_local std::vector<uint8_t> ubuf;
442    static thread_local std::vector<float> accb;
443    ubuf.resize((size_t) (T < kTile ? T : kTile) * n);
444    accb.resize((size_t) kRows * kTile * 8);
445    const __m512i zero = _mm512_setzero_si512(), one8 = _mm512_set1_epi8(1), flip = _mm512_set1_epi8((char) 0x80);
446    for (int t0 = 0; t0 < T; t0 += kTile) {
447        const int tt = T - t0 < kTile ? T - t0 : kTile;
448        const block_q8_K* y[kTile];
449        for (int t = 0; t < tt; ++t) {
450            y[t] = (const block_q8_K*) act[t0 + t];
451            uint8_t* u = ubuf.data() + (size_t) t * n;
452            for (int i = 0; i < nb; ++i)
453                for (int j = 0; j < 4; ++j)
454                    _mm512_storeu_si512((void*) (u + (size_t) i * 256 + 64 * j),
455                                        _mm512_xor_si512(_mm512_loadu_si512((const void*) (y[t][i].qs + 64 * j)), flip));
456        }
457        for (int rg = r0; rg < r1; rg += kRows) {
458            const int rr = r1 - rg < kRows ? r1 - rg : kRows;
459            for (int k = 0; k < rr * tt; ++k) _mm256_storeu_ps(&accb[(size_t) k * 8], _mm256_setzero_ps());
460            for (int i = 0; i < nb; ++i)
461                for (int q = 0; q < rr; ++q) {
462                    const uint8_t* blk = w + (size_t) (rg + q) * row_bytes + (size_t) i * FmtX<TY>::bytes;
463                    if (prefetch_ahead > 0) {
464                        _mm_prefetch((const char*) blk + prefetch_ahead, _MM_HINT_T0);
465                        _mm_prefetch((const char*) blk + prefetch_ahead + 64, _MM_HINT_T0);
466                    }
467                    __m512i w8[4], sc[4];
468                    __m512i corr = zero;
469                    for (int j = 0; j < 4; ++j) {
470                        __m512i g, s;
471                        __mmask64 m;
472                        FmtX<TY>::decode(blk, j, g, m, s);
473                        w8[j] = _mm512_mask_sub_epi8(g, m, zero, g);
474                        sc[j] = s;
475                        corr = _mm512_dpwssd_epi32(corr, _mm512_maddubs_epi16(one8, w8[j]), s);
476                    }
477                    const __m256i corr128 = _mm256_slli_epi32(fold256(corr), 7);
478                    const float dx = h2f(u16(blk));
479                    float* accq = &accb[(size_t) q * tt * 8];
480                    for (int t = 0; t < tt; ++t) {
481                        const uint8_t* u = ubuf.data() + (size_t) t * n + (size_t) i * 256;
482                        __m512i a = zero;
483                        for (int j = 0; j < 4; ++j)
484                            a = _mm512_dpwssd_epi32(a, _mm512_maddubs_epi16(_mm512_loadu_si512((const void*) (u + 64 * j)), w8[j]), sc[j]);
485                        const __m256i s = _mm256_sub_epi32(fold256(a), corr128);
486                        float* ap = accq + (size_t) t * 8;
487                        _mm256_storeu_ps(ap, _mm256_fmadd_ps(_mm256_set1_ps(dx * y[t][i].d), _mm256_cvtepi32_ps(s), _mm256_loadu_ps(ap)));
488                    }
489                }
490            for (int q = 0; q < rr; ++q)
491                for (int t = 0; t < tt; ++t)
492                    out[t0 + t][rg + q] = FmtX<TY>::K * hsum8_ggml(_mm256_loadu_ps(&accb[((size_t) q * tt + t) * 8]));
493        }
494    }
495}
496
497template <int TY>
498void dot_rows_x_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out, int r0, int r1) {
499    switch (nt) {
500        case 1: dot_rows_x<TY, 1>(w, row_bytes, n, act, out, r0, r1); break;
501        case 2: dot_rows_x<TY, 2>(w, row_bytes, n, act, out, r0, r1); break;
502        case 3: dot_rows_x<TY, 3>(w, row_bytes, n, act, out, r0, r1); break;
503        case 4: dot_rows_x<TY, 4>(w, row_bytes, n, act, out, r0, r1); break;
504        case 5: dot_rows_x<TY, 5>(w, row_bytes, n, act, out, r0, r1); break;
505        case 6: dot_rows_x<TY, 6>(w, row_bytes, n, act, out, r0, r1); break;
506        default: dot_rows_wide<TY>(w, row_bytes, n, act, nt, out, r0, r1); break;
507    }
508}
509
510
511// ---- IQ1_M (29), AVX-512, 1..6 tokens: ggml's dot lane for lane.  The grid indices come out of two pdep (as ggml's BMI2 path), the
512// +-1 delta signs out of one pext into an 8-bit mask a 64-value step; the signed grid bytes are split into |g| and a negative mask;
513// the delta dot is the pair sums of the activation (made once a call) times +-scale.  d is f16 in the top nibbles of the scales.
514inline void iq1m_pre(const block_q8_K* y, int nb, int16_t* p) {
515    const __m256i one8 = _mm256_set1_epi8(1);
516    for (int i = 0; i < nb; ++i)
517        for (int c = 0; c < 8; ++c)
518            _mm256_storeu_si256((__m256i*) (p + ((size_t) i * 8 + c) * 16),
519                                _mm256_maddubs_epi16(one8, _mm256_loadu_si256((const __m256i*) (y[i].qs + 32 * c))));
520}
521
522template <int NT>
523void rows_m(const uint8_t* w, size_t rb, int n, const block_q8_K* const* y, const int16_t* const* P, float* const* out, int r0, int r1) {
524    const int nb = n / QK_K;
525    const __m256i mask = _mm256_set1_epi16(0x7), mone = _mm256_set1_epi16(1), mtwo8 = _mm256_set1_epi8(2);
526    const __m256i scales_shift = _mm256_set_epi64x(9, 3, 6, 0);
527    const __m512i zero = _mm512_setzero_si512();
528    // the 32 scale words a 64-weight step (8 each of chunks 4 it .. 4 it + 3) out of the 16 decoded scales (their order: 4 e + j for
529    // shift e, word j): one vpermw a step instead of two vpshufb + adds + an insert
530    __m512i sidx[4];
531    for (int it = 0; it < 4; ++it)
532        sidx[it] = _mm512_set_epi16(12 + it, 12 + it, 12 + it, 12 + it, 12 + it, 12 + it, 12 + it, 12 + it, 4 + it, 4 + it, 4 + it, 4 + it, 4 + it, 4 + it,
533                                    4 + it, 4 + it, 8 + it, 8 + it, 8 + it, 8 + it, 8 + it, 8 + it, 8 + it, 8 + it, it, it, it, it, it, it, it, it);
534    for (int r = r0; r < r1; ++r) {
535        __m256 a1[NT], a2[NT];
536        for (int t = 0; t < NT; ++t) a1[t] = a2[t] = _mm256_setzero_ps();
537        const uint8_t* row = w + (size_t) r * rb;
538        for (int i = 0; i < nb; ++i) {
539            const uint8_t* blk = row + (size_t) i * 56;
540            const uint8_t* qs = blk;
541            const uint8_t* qh = blk + 32;
542            const uint8_t* scb = blk + 48;
543            if (prefetch_ahead > 0) {
544                _mm_prefetch((const char*) blk + prefetch_ahead, _MM_HINT_T0);
545                _mm_prefetch((const char*) blk + prefetch_ahead + 64, _MM_HINT_T0);
546            }
547            const uint16_t sc0 = u16(scb), sc1 = u16(scb + 2), sc2 = u16(scb + 4), sc3 = u16(scb + 6);
548            const uint16_t d16 = (uint16_t) ((sc0 >> 12) | ((sc1 >> 8) & 0x00f0) | ((sc2 >> 4) & 0x0f00) | (sc3 & 0xf000));
549            __m256i scales = _mm256_set1_epi64x((long long) u64(scb));
550            scales = _mm256_srlv_epi64(scales, scales_shift);
551            scales = _mm256_add_epi16(_mm256_slli_epi16(_mm256_and_si256(scales, mask), 1), mone);
552            const __m512i sctab = _mm512_castsi256_si512(scales);
553            __m512i s1[NT], s2[NT];
554            for (int t = 0; t < NT; ++t) s1[t] = s2[t] = zero;
555            for (int it = 0; it < 4; ++it) {
556                const uint32_t qh32 = u32(qh + 4 * it);
557                const uint64_t p1 = _pdep_u64(u32(qs + 8 * it), 0x00ff00ff00ff00ffULL) | _pdep_u64(qh32 & 0x7777, 0x0f000f000f000f00ULL);
558                const uint64_t p2 = _pdep_u64(u32(qs + 8 * it + 4), 0x00ff00ff00ff00ffULL) | _pdep_u64((qh32 >> 16) & 0x7777, 0x0f000f000f000f00ULL);
559                uint16_t ix[8];
560                std::memcpy(ix, &p1, 8);
561                std::memcpy(ix + 4, &p2, 8);
562                const __m512i g = _mm512_set_epi64((long long) iq1s_grid[ix[7]], (long long) iq1s_grid[ix[6]], (long long) iq1s_grid[ix[5]],
563                                                   (long long) iq1s_grid[ix[4]], (long long) iq1s_grid[ix[3]], (long long) iq1s_grid[ix[2]],
564                                                   (long long) iq1s_grid[ix[1]], (long long) iq1s_grid[ix[0]]);
565                const __m512i sc = _mm512_permutexvar_epi16(sidx[it], sctab);
566                // the delta sign of each 8-weight group (bit 3 of its qh nibble) negates that group's 4 scale words
567                const __mmask32 dneg = (__mmask32) (_pdep_u32(_pext_u32(qh32, 0x88888888u), 0x11111111u) * 15u);
568                const __m512i ssc = _mm512_mask_sub_epi16(sc, dneg, zero, sc);
569                const __m512i ag = _mm512_abs_epi8(g);
570                const __mmask64 gneg = _mm512_movepi8_mask(g);
571                for (int t = 0; t < NT; ++t) {
572                    const __m512i q8 = _mm512_loadu_si512((const void*) (y[t][i].qs + 64 * it));
573                    const __m512i pp = _mm512_loadu_si512((const void*) (P[t] + ((size_t) i * 8 + 2 * it) * 16));
574                    const __m512i ys = _mm512_mask_sub_epi8(q8, gneg, zero, q8);
575                    s1[t] = _mm512_dpwssd_epi32(s1[t], _mm512_maddubs_epi16(ag, ys), sc);
576                    s2[t] = _mm512_dpwssd_epi32(s2[t], pp, ssc);
577                }
578            }
579            const float dx = h2f(d16);
580            for (int t = 0; t < NT; ++t) {
581                const __m256 d = _mm256_set1_ps(y[t][i].d * dx);
582                a1[t] = _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(fold256(s1[t])), a1[t]);
583                a2[t] = _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(fold256(s2[t])), a2[t]);
584            }
585        }
586        for (int t = 0; t < NT; ++t) out[t][r] = hsum8_ggml(a1[t]) + 0.125f * hsum8_ggml(a2[t]);
587    }
588}
589
590void rows_m_nt(int nt, const uint8_t* w, size_t rb, int n, const void* const* act, float* const* out, int r0, int r1) {
591    const int nb = n / QK_K;
592    static thread_local std::vector<int16_t> pre;
593    for (int t0 = 0; t0 < nt; t0 += 6) {
594        const int k = nt - t0 < 6 ? nt - t0 : 6;
595        const block_q8_K* y[6];
596        const int16_t* P[6];
597        float* o[6];
598        pre.resize((size_t) k * n);
599        for (int t = 0; t < k; ++t) {
600            y[t] = (const block_q8_K*) act[t0 + t];
601            iq1m_pre(y[t], nb, pre.data() + (size_t) t * n);
602            P[t] = pre.data() + (size_t) t * n;
603            o[t] = out[t0 + t];
604        }
605        switch (k) {
606            case 1: rows_m<1>(w, rb, n, y, P, o, r0, r1); break;
607            case 2: rows_m<2>(w, rb, n, y, P, o, r0, r1); break;
608            case 3: rows_m<3>(w, rb, n, y, P, o, r0, r1); break;
609            case 4: rows_m<4>(w, rb, n, y, P, o, r0, r1); break;
610            case 5: rows_m<5>(w, rb, n, y, P, o, r0, r1); break;
611            default: rows_m<6>(w, rb, n, y, P, o, r0, r1); break;
612        }
613    }
614}
615
616}  // namespace
617
618void iq512_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
619                   float* const* ff, int r0, int r1) {
620    switch (type) {
621        case 16: gu_rows_nt<16>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
622        case 17: gu_rows_nt<17>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
623        case 18: gu_rows_nt<18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
624        case 21: gu_rows_nt<21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
625        case 22: gu_rows_nt<22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
626        default: break;
627    }
628}
629
630// The linked ggml AVX2 singleton order, for the formats validated against its production dot.
631void iq512_reference_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n,
632                             const void* const* act, int nt, float* const* ff, int r0, int r1) {
633    switch (type) {
634        case 18: gu_rows_nt<18, true>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
635        case 21: gu_rows_nt<21, true>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
636        case 22: gu_rows_nt<22, true>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
637        case 23: gu_rows_nt<23, true>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
638    }
639}
640
641void iq512_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
642                int r0, int r1) {
643    switch (type) {
644        case 16: dot_rows_nt<16>(nt, w, row_bytes, n, act, out, r0, r1); break;
645        case 17: dot_rows_nt<17>(nt, w, row_bytes, n, act, out, r0, r1); break;
646        case 18: dot_rows_nt<18>(nt, w, row_bytes, n, act, out, r0, r1); break;
647        case 21: dot_rows_nt<21>(nt, w, row_bytes, n, act, out, r0, r1); break;
648        case 22: dot_rows_nt<22>(nt, w, row_bytes, n, act, out, r0, r1); break;
649        default: break;
650    }
651}
652
653static bool has_vpopcnt() {
654    static const bool ok = [] {
655#if defined(_MSC_VER)
656        int r[4];
657        __cpuidex(r, 7, 0);
658        return ((r[2] >> 14) & 1) != 0;   // AVX512_VPOPCNTDQ
659#else
660        unsigned a, b, c, d;
661        __cpuid_count(7, 0, a, b, c, d);
662        return ((c >> 14) & 1u) != 0;
663#endif
664    }();
665    return ok;
666}
667
668bool iq512_gather_on() noexcept { return gather; }
669
670bool iq512x_supported(int type) noexcept {
671    return has_vpopcnt() && (type == 16 || type == 17 || type == 18 || type == 21 || type == 22 || type == 29);
672}
673
674void iq512x_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
675                 int r0, int r1) {
676    switch (type) {
677        case 16: dot_rows_x_nt<16>(nt, w, row_bytes, n, act, out, r0, r1); break;
678        case 17: dot_rows_x_nt<17>(nt, w, row_bytes, n, act, out, r0, r1); break;
679        case 18: dot_rows_x_nt<18>(nt, w, row_bytes, n, act, out, r0, r1); break;
680        case 21: dot_rows_x_nt<21>(nt, w, row_bytes, n, act, out, r0, r1); break;
681        case 22: dot_rows_x_nt<22>(nt, w, row_bytes, n, act, out, r0, r1); break;
682        case 23: dot_rows_x_nt<23>(nt, w, row_bytes, n, act, out, r0, r1); break;
683        case 29: rows_m_nt(nt, w, row_bytes, n, act, out, r0, r1); break;
684        default: break;
685    }
686}
687
688// ---- gate + up in ONE pass over the activations (the idea of PR 5243's row_gu_dot, bsorensen110): the weights of the two rows are decoded side by
689// side and each token's 64 activation bytes are loaded once and applied to both.  The sums are ggml's AVX2 dot's (the integer lanes folded to eight,
690// f16 scale times y.d, eight float lanes, its hsum, K last), so a token's gate and up are ggml-cpu's vec_dot bit for bit at any token count: the
691// same bits as the one-token path of native_expert.cpp (which runs ggml's dot), and the 2+ token rows differ from the 16-lane i-quant rows by
692// rounding only.  The sign masks of IQ2_XXS / IQ2_XS / IQ3_XXS come from VPOPCNTDQ (FmtX).
693namespace {
694
695template <int TY, int NT>
696void gu_fused(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, float* const* ff, int r0, int r1) {
697    const block_q8_K* y[NT];
698    for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
699    const int nb = n / QK_K;
700    const __m512i zero = _mm512_setzero_si512();
701    for (int r = r0; r < r1; ++r) {
702        const uint8_t* gr = blob + (size_t) r * gu_row;
703        const uint8_t* ur = blob + up_off + (size_t) r * gu_row;
704        __m256 ag[NT], au[NT];
705        for (int t = 0; t < NT; ++t) ag[t] = au[t] = _mm256_setzero_ps();
706        for (int i = 0; i < nb; ++i) {
707            const uint8_t* gb = gr + (size_t) i * FmtX<TY>::bytes;
708            const uint8_t* ub = ur + (size_t) i * FmtX<TY>::bytes;
709            if (prefetch_ahead > 0) {
710                _mm_prefetch((const char*) gb + prefetch_ahead, _MM_HINT_T0);
711                _mm_prefetch((const char*) gb + prefetch_ahead + 64, _MM_HINT_T0);
712                _mm_prefetch((const char*) ub + prefetch_ahead, _MM_HINT_T0);
713                _mm_prefetch((const char*) ub + prefetch_ahead + 64, _MM_HINT_T0);
714            }
715            __m512i ig[NT], iu[NT];
716            for (int t = 0; t < NT; ++t) ig[t] = iu[t] = zero;
717            for (int j = 0; j < 4; ++j) {
718                __m512i gg, gs, ug, us;
719                __mmask64 gm, um;
720                FmtX<TY>::decode(gb, j, gg, gm, gs);
721                FmtX<TY>::decode(ub, j, ug, um, us);
722                for (int t = 0; t < NT; ++t) {
723                    const __m512i yv = _mm512_loadu_si512((const void*) (y[t][i].qs + 64 * j));
724                    ig[t] = _mm512_dpwssd_epi32(ig[t], _mm512_maddubs_epi16(gg, _mm512_mask_sub_epi8(yv, gm, zero, yv)), gs);
725                    iu[t] = _mm512_dpwssd_epi32(iu[t], _mm512_maddubs_epi16(ug, _mm512_mask_sub_epi8(yv, um, zero, yv)), us);
726                }
727            }
728            const float dg = h2f(u16(gb)), du = h2f(u16(ub));
729            for (int t = 0; t < NT; ++t) {
730                const float yd = y[t][i].d;
731                ag[t] = _mm256_fmadd_ps(_mm256_set1_ps(dg * yd), _mm256_cvtepi32_ps(fold256(ig[t])), ag[t]);
732                au[t] = _mm256_fmadd_ps(_mm256_set1_ps(du * yd), _mm256_cvtepi32_ps(fold256(iu[t])), au[t]);
733            }
734        }
735        for (int t = 0; t < NT; ++t) {
736            const float g = FmtX<TY>::K * hsum8_ggml(ag[t]), u = FmtX<TY>::K * hsum8_ggml(au[t]);
737            ff[t][r] = (g / (1.f + std::exp(-g))) * u;
738        }
739    }
740}
741
742template <int TY>
743void gu_fused_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, float* const* ff, int r0, int r1) {
744    switch (nt) {
745        case 1: gu_fused<TY, 1>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
746        case 2: gu_fused<TY, 2>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
747        case 3: gu_fused<TY, 3>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
748        case 4: gu_fused<TY, 4>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
749        default:
750            for (int t0 = 0; t0 < nt; t0 += 4) {
751                const int k = nt - t0 < 4 ? nt - t0 : 4;
752                gu_fused_nt<TY>(k, blob, gu_row, up_off, n, act + t0, ff + t0, r0, r1);
753            }
754    }
755}
756
757}  // namespace
758
759bool iq512f_supported(int type) noexcept { return has_vpopcnt() && (type == 16 || type == 17 || type == 18 || type == 21 || type == 22); }
760
761void iq512_fused_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
762                         float* const* ff, int r0, int r1) {
763    switch (type) {
764        case 16: gu_fused_nt<16>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
765        case 17: gu_fused_nt<17>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
766        case 18: gu_fused_nt<18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
767        case 21: gu_fused_nt<21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
768        case 22: gu_fused_nt<22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
769        default: break;
770    }
771}
772
773// ---- Q5_0 (6) down rows in 512-bit lanes: two 32-value blocks a vector, the weights of a block pair decoded once for
774// every token.  The arithmetic is ggml-cpu's AVX2 dot, order for order: per block the 8 integer lanes (values 4l .. 4l+3 of the
775// block, one vpdpbusd lane each), converted, scaled by f16(dx) * f16(dy) and fused into ONE eight-lane float accumulator in block order,
776// hsum last: a token's row is ggml-cpu's dot bit for bit.  An odd block count ends on a 256-bit block.  (An IQ4_NL version of the same
777// shape measured 5-11% SLOWER than iq4nl256_down_rows on Zen 4 at 2-4 tokens and was dropped.)
778namespace {
779
780inline __m512i pair_q8_0(const block_q8_0* a, const block_q8_0* b) {
781    return _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_loadu_si256((const __m256i*) a->qs)),
782                              _mm256_loadu_si256((const __m256i*) b->qs), 1);
783}
784
785// 32 signed weights of a Q5_0 block: the nibble (low plane, then high plane) minus 16 where the fifth bit is clear
786inline __m256i q50_weights(const block_q5_0* x) {
787    const __m128i bits = _mm_loadu_si128((const __m128i*) x->qs);
788    const __m128i m4 = _mm_set1_epi8(0x0f);
789    const __m256i nib = _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_and_si128(bits, m4)), _mm_and_si128(_mm_srli_epi16(bits, 4), m4), 1);
790    uint32_t qh;
791    std::memcpy(&qh, x->qh, 4);
792    return _mm256_mask_sub_epi8(nib, (__mmask32) ~qh, nib, _mm256_set1_epi8(16));
793}
794
795template <int NT>
796void qd_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* const* y, float* const* out, int r0, int r1) {
797    constexpr size_t kBlk = sizeof(block_q5_0);
798    const int nb = n / 32;
799    const int pf = prefetch_ahead;
800    for (int r = r0; r < r1; ++r) {
801        const uint8_t* row = w + (size_t) r * row_bytes;
802        __m256 acc[NT];
803        for (int t = 0; t < NT; ++t) acc[t] = _mm256_setzero_ps();
804        int ib = 0;
805        for (; ib + 1 < nb; ib += 2) {
806            const uint8_t* b0 = row + (size_t) ib * kBlk;
807            if (pf > 0) { _mm_prefetch((const char*) b0 + pf, _MM_HINT_T0); _mm_prefetch((const char*) b0 + pf + 64, _MM_HINT_T0); }
808            const __m512i wq = _mm512_inserti64x4(_mm512_castsi256_si512(q50_weights((const block_q5_0*) b0)), q50_weights((const block_q5_0*) (b0 + kBlk)), 1);
809            const float d0 = h2f(((const block_q5_0*) b0)->d);
810            const float d1 = h2f(((const block_q5_0*) (b0 + kBlk))->d);
811            const __m512i aw = _mm512_abs_epi8(wq);
812            const __mmask64 neg = _mm512_movepi8_mask(wq);
813            for (int t = 0; t < NT; ++t) {
814                const __m512i yv = pair_q8_0(&y[t][ib], &y[t][ib + 1]);
815                const __m512i p = _mm512_dpbusd_epi32(_mm512_setzero_si512(), aw, _mm512_mask_sub_epi8(yv, neg, _mm512_setzero_si512(), yv));
816                const __m256 lo = _mm256_cvtepi32_ps(_mm512_castsi512_si256(p));
817                const __m256 hi = _mm256_cvtepi32_ps(_mm512_extracti64x4_epi64(p, 1));
818                acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d0 * h2f(y[t][ib].d)), lo, acc[t]);
819                acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d1 * h2f(y[t][ib + 1].d)), hi, acc[t]);
820            }
821        }
822        if (ib < nb) {
823            const uint8_t* b0 = row + (size_t) ib * kBlk;
824            const __m256i wq = q50_weights((const block_q5_0*) b0);
825            const float d0 = h2f(((const block_q5_0*) b0)->d);
826            for (int t = 0; t < NT; ++t) {
827                const __m256i yv = _mm256_loadu_si256((const __m256i*) y[t][ib].qs);
828                const __m256i p = _mm256_dpbusd_epi32(_mm256_setzero_si256(), _mm256_abs_epi8(wq), _mm256_sign_epi8(yv, wq));
829                acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d0 * h2f(y[t][ib].d)), _mm256_cvtepi32_ps(p), acc[t]);
830            }
831        }
832        for (int t = 0; t < NT; ++t) out[t][r] = hsum8_ggml(acc[t]);
833    }
834}
835
836void qd_rows_nt(int nt, const uint8_t* w, size_t row_bytes, int n, const void* const* hq, float* const* out, int r0, int r1) {
837    const block_q8_0* y[8];
838    for (int t = 0; t < nt; ++t) y[t] = (const block_q8_0*) hq[t];
839    switch (nt) {
840        case 1: qd_rows<1>(w, row_bytes, n, y, out, r0, r1); break;
841        case 2: qd_rows<2>(w, row_bytes, n, y, out, r0, r1); break;
842        case 3: qd_rows<3>(w, row_bytes, n, y, out, r0, r1); break;
843        case 4: qd_rows<4>(w, row_bytes, n, y, out, r0, r1); break;
844        default:
845            for (int t0 = 0; t0 < nt; t0 += 4) {
846                const int k = nt - t0 < 4 ? nt - t0 : 4;
847                qd_rows_nt(k, w, row_bytes, n, hq + t0, out + t0, r0, r1);
848            }
849    }
850}
851
852}  // namespace
853
854void q50_512_down_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, float* const* out, int r0, int r1) {
855    qd_rows_nt(nt, w, row_bytes, n, hq, out, r0, r1);
856}
857
858}  // namespace strata::kernels::cpu