okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
34.6 KiB663 linesraw
1// src/kernels/cpu/iq_avx2.cpp - the i-quant expert rows in 256-bit lanes, several tokens at once.
2//
3// The AVX-512 kernels' (iq_avx512.cpp) multi-token scheme on the CPUs without AVX-512 (AMD Zen 2/3, Intel
4// Core 12th-14th gen and Core Ultra): each 32-value chunk is decoded once - grid lookups, one sign vector,
5// one scale vector - and every token of the verify window applies them with a load, a `sign`, a `maddubs`,
6// a `madd` and an `add`.  ggml-cpu's own AVX2 dot products for these formats are single-token: every token
7// re-does the codebook lookups and the sign expansion.  The sign vector is ggml's bit_selector pattern
8// (ggml-cpu/arch/x86/quants.c): pshufb-broadcast of each sign byte, AND with the bit selector, CMPEQ, OR
9// with one, `vpsignb`.  The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references) - only the
10// order of the float additions differs.
11//
12// Formats: IQ2_XXS (16), IQ2_XS (17), IQ3_XXS (18), IQ3_S (21), IQ2_S (22), IQ4_XS (23).  IQ1_M stays on ggml-cpu.
13//
14// IQ3_XXS, IQ3_S and IQ2_S also have a gathered decode (Fmt32<118>, <121>, <122>): the grid indices built in a
15// register and read with one vpgather, the same words into the same lanes, so the same bits.  Where it is faster
16// depends on the core, so STRATA_IQ256_GATHER picks it per thread (expert_layout.hpp, cpu_gather_fast_here).
17//
18// Where the CPU has AVX-VNNI (cpu_avxvnni_ok: Alder Lake, Sapphire Rapids and later) the row kernels take a second
19// copy with vpdpwssd / vpdpbusd (iq_avx2_rows.inl), the same integer sums.
20//
21// This file is compiled for AVX2 and must not run anything before the engine's cpu_avx2_ok() check: no runtime
22// initializer at namespace scope (#391, 016ea2e), the switches are read on first use.
23#include "strata/kernels/cpu/iq_avx2.hpp"
24#include "strata/kernels/cpu/expert_layout.hpp"
25
26#define GGML_COMMON_DECL_CPP
27#define GGML_COMMON_IMPL_CPP
28#include "ggml-common.h"
29
30#include <immintrin.h>
31
32#include <cmath>
33#include <cstdlib>
34#include <cstring>
35#include <vector>
36
37// STRATA_AVXVNNI (CMake: the compiler has the AVX-VNNI intrinsics): GCC and Clang compile them only inside functions
38// with target("avxvnni") - the VNNI copy of iq_avx2_rows.inl.
39#if !defined(STRATA_AVXVNNI)
40#define STRATA_AVXVNNI 0
41#endif
42#if STRATA_AVXVNNI && (defined(__GNUC__) || defined(__clang__))
43#define STRATA_AVXVNNI_FN __attribute__((target("avxvnni")))
44#else
45#define STRATA_AVXVNNI_FN
46#endif
47
48namespace strata::kernels::cpu {
49namespace {
50
51inline float h2f(uint16_t h) { return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int) h))); }
52inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; }
53inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; }
54inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; }
55
56// 32 sign bits -> 32 bytes of -1 (bit set) / +1: ggml's bit_selector pattern, shared by all tokens.
57inline __m256i sgn_vec(uint32_t m) {
58    const __m128i bm = _mm_set1_epi32((int) m);
59    const __m128i lo = _mm_shuffle_epi8(bm, _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1));
60    const __m128i hi = _mm_shuffle_epi8(bm, _mm_setr_epi8(2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3));
61    const __m256i bits = _mm256_inserti128_si256(_mm256_castsi128_si256(lo), hi, 1);
62    const __m256i sel = _mm256_setr_epi8(1, 2, 4, 8, 16, 32, 64, (char) 0x80,
63                                         1, 2, 4, 8, 16, 32, 64, (char) 0x80,
64                                         1, 2, 4, 8, 16, 32, 64, (char) 0x80,
65                                         1, 2, 4, 8, 16, 32, 64, (char) 0x80);
66    const __m256i nz = _mm256_cmpeq_epi8(_mm256_and_si256(bits, sel), sel);
67    return _mm256_or_si256(nz, _mm256_set1_epi8(1));
68}
69
70// The same sign vector read in place from the half's four sign bytes (IQ3_S, IQ2_S): the bytes come in as one
71// broadcast load (vpbroadcastd from memory, a load uop) and ONE pshufb expands them, instead of sgn_vec's two
72// pshufb + inserti128 - three uops on the single shuffle port of Haswell-class cores, one here.
73inline __m256i sgn_vec_at(const uint8_t* p) {
74    const __m256i bits = _mm256_shuffle_epi8(_mm256_set1_epi32((int) u32(p)),
75                                             _mm256_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1,
76                                                              2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3));
77    const __m256i sel = _mm256_setr_epi8(1, 2, 4, 8, 16, 32, 64, (char) 0x80,
78                                         1, 2, 4, 8, 16, 32, 64, (char) 0x80,
79                                         1, 2, 4, 8, 16, 32, 64, (char) 0x80,
80                                         1, 2, 4, 8, 16, 32, 64, (char) 0x80);
81    const __m256i nz = _mm256_cmpeq_epi8(_mm256_and_si256(bits, sel), sel);
82    return _mm256_or_si256(nz, _mm256_set1_epi8(1));
83}
84
85// The two 16-value scales of one 32-value half (IQ2_XS, IQ2_S): int16 lanes 0-7 = a (values 0-15),
86// 8-15 = b (values 16-31).  NOT a broadcast dword [a,b] - that would alternate the scales lane by lane.
87inline __m256i sc16(int a, int b) {
88    return _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_set1_epi16((short) a)),
89                                   _mm_set1_epi16((short) b), 1);
90}
91// One scale for the whole 32-value half (IQ2_XXS, IQ3_XXS, IQ3_S).
92inline __m256i sc32(int s) { return _mm256_set1_epi16(s); }
93
94// keven_signs_q2xs (ggml keeps it static in arch/x86/quants.c): one u64 per 7-bit sign index, byte k
95// = 0xFF when bit k of ksigns_iq2xs[i] is set, 0x01 otherwise.  With this a whole 32-value sign vector
96// is four scalar loads and a set_epi64x - no ksigns byte packing chain and no bit_selector expansion.
97//
98// Computed at COMPILE time (constexpr), so this file has no static constructor at all.  This TU is compiled
99// for AVX2, and a runtime constructor here runs before main() on every CPU: MSVC turned its variable shift
100// into BMI2 `shlx` (#391, demetree: strata.exe exited 0xC000001D before printing anything on a Sandy Bridge
101// Xeon) and GCC vectorised the loop into AVX2 (`vpbroadcastb`, found on an AVX-only Xeon E5 by the
102// Strata_Dirigo fork).  ksigns_iq2xs[i] is i's 7 bits plus an even-parity bit 7 (ggml-common.h); a const
103// array is not usable in a constant expression, so the byte is derived the same way here, and
104// native_expert_parity checks these kernels against ggml-cpu's.
105struct EvenSigns {
106    uint64_t v[128];
107    constexpr EvenSigns() : v{} {
108        for (int i = 0; i < 128; ++i) {
109            int par = 0;
110            for (int k = 0; k < 7; ++k) par ^= (i >> k) & 1;
111            const int s = i | (par << 7);          // == ksigns_iq2xs[i]
112            uint64_t r = 0;
113            for (int k = 0; k < 8; ++k) r |= (uint64_t) (((s >> k) & 1) ? 0xFF : 0x01) << (8 * k);
114            v[i] = r;
115        }
116    }
117};
118static constexpr EvenSigns even_signs{};
119static_assert(even_signs.v[0] == 0x0101010101010101ull && even_signs.v[1] == 0xFF010101010101FFull,
120              "keven_signs_q2xs: byte k = 0xFF when bit k of ksigns_iq2xs[i] is set");
121
122// IQ3_S / IQ2_S grid indices: the high index bits of a 32-value half (one qh byte) spread one index per byte,
123// so a single punpcklbw puts them next to the low index bytes and every grid lookup is a 16-bit load plus the
124// table load - instead of a shift, a mask and an or per index.  IQ3_S: byte k = bit k (the 9th bit of index k).
125// IQ2_S: byte k = bits 2k,2k+1 (bits 8-9 of index k), k < 4.  constexpr for the same reason as EvenSigns.
126struct HiSpread {
127    uint64_t iq3s[256];
128    uint64_t iq2s[256];
129    constexpr HiSpread() : iq3s{}, iq2s{} {
130        for (int h = 0; h < 256; ++h) {
131            uint64_t r3 = 0, r2 = 0;
132            for (int k = 0; k < 8; ++k) r3 |= (uint64_t) ((h >> k) & 1) << (8 * k);
133            for (int k = 0; k < 4; ++k) r2 |= (uint64_t) ((h >> (2 * k)) & 3) << (8 * k);
134            iq3s[h] = r3;
135            iq2s[h] = r2;
136        }
137    }
138};
139static constexpr HiSpread hi_spread{};
140static_assert(hi_spread.iq3s[0x81] == 0x0100000000000001ull && hi_spread.iq2s[0xE4] == 0x0000000003020100ull,
141              "hi_spread: one high-bit group per index byte");
142
143// The (2s+1) scale vectors as tables (IQ3_S: one 4-bit scale per 32-value half; IQ2_S: one scale byte holding
144// the two 16-value scales of the half) - one load instead of the shift/or/broadcast chain of sc32()/sc16().
145struct ScaleVecs {
146    int16_t s32[16][16];    // all 16 lanes = 2s+1
147    int16_t s16[256][16];   // lanes 0-7 = 2*(b&15)+1, lanes 8-15 = 2*(b>>4)+1 (the layout sc16() builds)
148    constexpr ScaleVecs() : s32{}, s16{} {
149        for (int s = 0; s < 16; ++s)
150            for (int l = 0; l < 16; ++l) s32[s][l] = (int16_t) (2 * s + 1);
151        for (int b = 0; b < 256; ++b)
152            for (int l = 0; l < 8; ++l) {
153                s16[b][l] = (int16_t) (2 * (b & 15) + 1);
154                s16[b][l + 8] = (int16_t) (2 * (b >> 4) + 1);
155            }
156    }
157};
158static constexpr ScaleVecs scale_vecs{};
159static_assert(scale_vecs.s32[15][0] == 31 && scale_vecs.s16[0x2F][7] == 31 && scale_vecs.s16[0x2F][8] == 5,
160              "scale_vecs: 2s+1, low nibble in lanes 0-7");
161
162inline __m256i scale_vec(const int16_t* lanes) { return _mm256_loadu_si256((const __m256i*) lanes); }
163
164// The low index bytes q[0..7] interleaved with the spread high bits: eight 16-bit grid indices in sp[].
165inline void grid_indices(const uint8_t* q, uint64_t hi, uint16_t* sp) {
166    _mm_storeu_si128((__m128i*) sp, _mm_unpacklo_epi8(_mm_cvtsi64_si128((long long) u64(q)),
167                                                      _mm_cvtsi64_si128((long long) hi)));
168}
169
170inline float hsum8(__m256 v) {
171    const __m128 lo = _mm256_castps256_ps128(v), hi = _mm256_extractf128_ps(v, 1);
172    __m128 s = _mm_add_ps(lo, hi);
173    s = _mm_hadd_ps(s, s);
174    s = _mm_hadd_ps(s, s);
175    return _mm_cvtss_f32(s);
176}
177
178// E-2 (iq_avx512.cpp) on the AVX-2 path: the pool streams the expert rows from DRAM at ~25 GB/s (4 KB pages
179// when large pages are refused), so ask for the bytes a few blocks before the decode needs them - 2048 B is
180// two gate/up rows ahead, a row is ~1 KB.  Same switch as the AVX-512 kernels: STRATA_IQ_PREFETCH is the
181// distance in bytes, 0 = off, default 2048.  Measured on a Zen 3 5700X3D (no AVX-512) on IQ3_S decode: -4% on
182// the gate/up phase, +1.0 GB/s over the rows, -1.3% ms/round end to end.  The non-temporal hint measured
183// worse than T0 at the same distance, so this keeps T0.
184int prefetch_distance() {
185    static const int d = [] {
186        const char* v = std::getenv("STRATA_IQ_PREFETCH");
187        return v ? std::atoi(v) : 2048;
188    }();
189    return d;
190}
191
192inline void rows_ahead(const uint8_t* blk, int pf) {
193    if (pf <= 0) return;
194    _mm_prefetch((const char*) blk + pf, _MM_HINT_T0);
195    _mm_prefetch((const char*) blk + pf + 64, _MM_HINT_T0);
196}
197
198// ---- per format: one 32-value half (values 64*j + 32*half .. +31) -> grid magnitudes, sign vector, scales
199template <int TY> struct Fmt32;
200
201template <> struct Fmt32<16> {   // IQ2_XXS: d, qs[32] u16
202    static constexpr int bytes = 66;
203    static constexpr float K = 0.125f;
204    static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) {
205        const uint8_t* q = b + 2 + 16 * j + 8 * half;
206        const uint32_t w0 = u32(q), w1 = u32(q + 4);
207        g = _mm256_set_epi64x((long long) iq2xxs_grid[w0 >> 24], (long long) iq2xxs_grid[(w0 >> 16) & 255],
208                              (long long) iq2xxs_grid[(w0 >> 8) & 255], (long long) iq2xxs_grid[w0 & 255]);
209        sgn = _mm256_set_epi64x((long long) even_signs.v[(w1 >> 21) & 127], (long long) even_signs.v[(w1 >> 14) & 127],
210                                (long long) even_signs.v[(w1 >> 7) & 127], (long long) even_signs.v[w1 & 127]);
211        sc = sc32(2 * (int) (w1 >> 28) + 1);
212    }
213};
214
215template <> struct Fmt32<17> {   // IQ2_XS: d, qs[32] u16 (9-bit grid index + 7-bit sign index), scales[8]
216    static constexpr int bytes = 74;
217    static constexpr float K = 0.125f;
218    static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) {
219        uint16_t v[8];
220        std::memcpy(v, b + 2 + 16 * j, 16);
221        const int o = 4 * half;
222        g = _mm256_set_epi64x((long long) iq2xs_grid[v[o + 3] & 511], (long long) iq2xs_grid[v[o + 2] & 511],
223                              (long long) iq2xs_grid[v[o + 1] & 511], (long long) iq2xs_grid[v[o] & 511]);
224        uint32_t s = 0;
225        for (int l = 0; l < 4; ++l) s |= (uint32_t) ksigns_iq2xs[v[o + l] >> 9] << (8 * l);
226        sgn = sgn_vec(s);
227        const uint8_t sb = b[66 + 2 * j + half];
228        sc = sc16(2 * (sb & 15) + 1, 2 * (sb >> 4) + 1);
229    }
230};
231
232template <> struct Fmt32<22> {   // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes), qh[8], scales[8]
233    static constexpr int bytes = 82;
234    static constexpr float K = 0.125f;
235    static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) {
236        // grid_indices reads 8 index bytes; only the first 4 are this half's (the rest stay inside the block)
237        alignas(16) uint16_t sp[8];
238        grid_indices(b + 2 + 8 * j + 4 * half, hi_spread.iq2s[b[66 + 2 * j + half]], sp);
239        g = _mm256_set_epi64x((long long) iq2s_grid[sp[3]], (long long) iq2s_grid[sp[2]],
240                              (long long) iq2s_grid[sp[1]], (long long) iq2s_grid[sp[0]]);
241        sgn = sgn_vec_at(b + 2 + 32 + 8 * j + 4 * half);
242        sc = scale_vec(scale_vecs.s16[b[74 + 2 * j + half]]);
243    }
244};
245
246template <> struct Fmt32<18> {   // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-bit sign index + 4-bit scale)
247    static constexpr int bytes = 98;
248    static constexpr float K = 0.25f;
249    static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) {
250        const uint8_t* q = b + 2 + 16 * j + 8 * half;
251        g = _mm256_set_epi32((int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]], (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]],
252                             (int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]], (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]);
253        const uint32_t w = u32(b + 2 + 64 + 8 * j + 4 * half);
254        sgn = _mm256_set_epi64x((long long) even_signs.v[(w >> 21) & 127], (long long) even_signs.v[(w >> 14) & 127],
255                                (long long) even_signs.v[(w >> 7) & 127], (long long) even_signs.v[w & 127]);
256        sc = sc32(2 * (int) (w >> 28) + 1);
257    }
258};
259
260template <> struct Fmt32<21> {   // IQ3_S: d, qs[64], qh[8], signs[32], scales[4]
261    static constexpr int bytes = 110;
262    static constexpr float K = 1.0f;
263    static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) {
264        const uint8_t* q = b + 2 + 16 * j + 8 * half;
265        const uint32_t h = b[66 + 2 * j + half];
266        alignas(16) uint16_t sp[8];
267        grid_indices(q, hi_spread.iq3s[h], sp);
268#define G3(k) (int) iq3s_grid[sp[k]]
269        g = _mm256_set_epi32(G3(7), G3(6), G3(5), G3(4), G3(3), G3(2), G3(1), G3(0));
270#undef G3
271        sgn = sgn_vec_at(b + 74 + 8 * j + 4 * half);
272        const uint8_t s = b[106 + j];
273        sc = scale_vec(scale_vecs.s32[half ? s >> 4 : s & 15]);
274    }
275};
276
277// ---- the gathered decodes (STRATA_IQ256_GATHER, see the top of the file): each its format's Fmt32 bit for bit
278// The 32 sign bits of a half from the j's 8 sign bytes: one broadcast and one shuffle (sgn_vec: two and an insert).
279inline __m256i sgn_half(const uint8_t* m8, int half) {
280    const __m256i sb = _mm256_shuffle_epi8(
281        _mm256_set1_epi64x((long long) u64(m8)),
282        half ? _mm256_setr_epi8(4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7)
283             : _mm256_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3));
284    const __m256i sel = _mm256_set1_epi64x((long long) 0x8040201008040201ull);
285    return _mm256_or_si256(_mm256_cmpeq_epi8(_mm256_and_si256(sb, sel), sel), _mm256_set1_epi8(1));
286}
287// The four 7-bit even-sign indices of a u32 (bits 0-6, 7-13, 14-20, 21-27) -> their four masks, one gather.
288inline __m256i even_signs4(uint32_t w) {
289    const __m128i idx = _mm_and_si128(_mm_srlv_epi32(_mm_set1_epi32((int) w), _mm_setr_epi32(0, 7, 14, 21)),
290                                      _mm_set1_epi32(127));
291    return _mm256_i32gather_epi64((const long long*) even_signs.v, idx, 8);
292}
293
294// IQ3_S: the eight 9-bit grid indices built in one register (8 low bits from qs, the 9th from bit k of qh) and read
295// with one gather; the scalar form spends ~7 shuffle-port uops per half on vpinsrd and runs the index arithmetic on
296// the scalar ports.  On a 14900KF's P-cores, gate/up rows of an IQ3_S expert at three tokens: 0.40 -> 0.27 ms.
297template <> struct Fmt32<121> {
298    static constexpr int bytes = 110;
299    static constexpr float K = 1.0f;
300    static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) {
301        const uint8_t* q = b + 2 + 16 * j + 8 * half;
302        const uint32_t h = b[66 + 2 * j + half];
303        const __m256i lo = _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) q));
304        const __m256i hb = _mm256_and_si256(_mm256_sllv_epi32(_mm256_set1_epi32((int) h),
305                                                              _mm256_setr_epi32(8, 7, 6, 5, 4, 3, 2, 1)),
306                                            _mm256_set1_epi32(0x100));
307        g = _mm256_i32gather_epi32((const int*) iq3s_grid, _mm256_or_si256(lo, hb), 4);
308        sgn = sgn_half(b + 74 + 8 * j, half);
309        const uint8_t s = b[106 + j];
310        sc = sc32(half ? 2 * (s >> 4) + 1 : 2 * (s & 15) + 1);
311    }
312};
313
314// IQ3_XXS: the grid entries and the four even-sign masks each by one gather.  P-core gate/up rows at three tokens:
315// 0.26 -> 0.24 ms.
316template <> struct Fmt32<118> {
317    static constexpr int bytes = 98;
318    static constexpr float K = 0.25f;
319    static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) {
320        const uint8_t* q = b + 2 + 16 * j + 8 * half;
321        g = _mm256_i32gather_epi32((const int*) iq3xxs_grid, _mm256_cvtepu8_epi32(_mm_loadl_epi64((const __m128i*) q)), 4);
322        const uint32_t w = u32(b + 2 + 64 + 8 * j + 4 * half);
323        sgn = even_signs4(w);
324        sc = sc32(2 * (int) (w >> 28) + 1);
325    }
326};
327
328// IQ2_S: the four 10-bit grid indices (qs byte k, bits 2k and 2k+1 of qh at bits 8-9) by one 64-bit gather and the
329// explicit sign bits from one broadcast.  P-core gate/up rows at three tokens: 0.31 -> 0.27 ms.  IQ2_XXS measured 4%
330// slower gathered (its four 8-byte grid loads are few enough already) and IQ2_XS has its own sign decode, so both
331// keep their Fmt32 everywhere.
332template <> struct Fmt32<122> {
333    static constexpr int bytes = 82;
334    static constexpr float K = 0.125f;
335    static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) {
336        const uint8_t* qs = b + 2 + 8 * j + 4 * half;
337        const uint32_t h = b[66 + 2 * j + half];
338        const __m128i idx = _mm_or_si128(
339            _mm_cvtepu8_epi32(_mm_cvtsi32_si128((int) u32(qs))),
340            _mm_and_si128(_mm_sllv_epi32(_mm_set1_epi32((int) h), _mm_setr_epi32(8, 6, 4, 2)), _mm_set1_epi32(0x300)));
341        g = _mm256_i32gather_epi64((const long long*) iq2s_grid, idx, 8);
342        sgn = sgn_half(b + 2 + 32 + 8 * j, half);
343        const uint8_t sb = b[74 + 2 * j + half];
344        sc = sc16(2 * (sb & 15) + 1, 2 * (sb >> 4) + 1);
345    }
346};
347
348template <> struct Fmt32<23> {   // IQ4_XS: d, scales_h, scales_l[4], qs[128] - 136 B, 8 signed sub-scales
349    // ggml's ggml_vec_dot_iq4_xs_q8_K: the same 16-value codebook as IQ4_NL, but each of the eight 32-value
350    // sub-blocks carries its own 6-bit scale, read as two nibbles of scales_l[p] plus two bits of scales_h, and
351    // used SIGNED as (ls - 32).  The scale therefore folds into the int16 operand of madd_epi16 instead of
352    // becoming a float multiply per sub-block, and the codebook sign is carried the way iq4nl_rows does it.
353    static constexpr int bytes = 136;
354    static constexpr float K = 1.0f;
355    static inline void decode(const uint8_t* b, int j, int half, __m256i& g, __m256i& sgn, __m256i& sc) {
356        const int H = 2 * j + half;   // the eight 32-value sub-blocks, in the order the activation bytes come
357        const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl);
358        const __m128i bits = _mm_loadu_si128((const __m128i*) (b + 8 + 16 * H));
359        const __m128i m4 = _mm_set1_epi8(0x0f);
360        const __m256i q4 = _mm256_inserti128_si256(
361            _mm256_castsi128_si256(_mm_shuffle_epi8(values, _mm_and_si128(bits, m4))),
362            _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4)), 1);
363        g   = _mm256_sign_epi8(q4, q4);                       // |w|, the unsigned operand of maddubs
364        sgn = _mm256_sign_epi8(_mm256_set1_epi8(1), q4);      // w's sign, applied to the activation
365        const int ls = ((b[4 + (H >> 1)] >> (4 * (H & 1))) & 0xf) | (((u16(b + 2) >> (2 * H)) & 3) << 4);
366        sc = _mm256_set1_epi16((short) (ls - 32));
367    }
368};
369
370// ---- the row kernels, twice: the AVX2 forms and the AVX-VNNI ones (iq_avx2_rows.inl)
371namespace plain {
372#define STRATA_ROWS_VNNI 0
373#define STRATA_ROWS_FN
374#include "iq_avx2_rows.inl"
375}  // namespace plain
376#if STRATA_AVXVNNI
377namespace vnni {
378#define STRATA_ROWS_VNNI 1
379#define STRATA_ROWS_FN STRATA_AVXVNNI_FN
380#include "iq_avx2_rows.inl"
381}  // namespace vnni
382#endif
383
384bool vnni_on() { return STRATA_AVXVNNI && cpu_avxvnni_ok(); }
385
386}  // namespace
387
388// ggml's quantize_row_q8_K_ref (ggml-quants.c), which is also what ggml-cpu runs on x86 (no SIMD version there),
389// in AVX-2: the same per-value arithmetic - one IEEE multiply by the same iscale, the same 1.5*2^23 rounding add,
390// the same clamp - so the bytes are identical (q8k_quant_parity checks it).  The block's sign-carrying max is the
391// FIRST value of the largest magnitude, as in the scalar loop; NaNs are skipped as there (`ax > amax` is false for
392// them, and max_ps returns its second operand for a NaN first one).  A zero block leaves bsums as the reference
393// does.  A verify window quantizes up to 6 tokens per layer on the host before the pool can start.
394void q8k_quant_avx2(const float* x, void* vy, int64_t k) {
395    block_q8_K* y = (block_q8_K*) vy;
396    const int64_t nb = k / QK_K;
397    const __m256 absm = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff));
398    const __m256 magic = _mm256_set1_ps(12582912.f);
399    const __m256i mant = _mm256_set1_epi32(0x007fffff), off = _mm256_set1_epi32(0x00400000);
400    const __m256i c127 = _mm256_set1_epi32(127);
401    const __m256i perm = _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7);
402    for (int64_t i = 0; i < nb; ++i, x += QK_K) {
403        __m256 m = _mm256_setzero_ps();
404        for (int j = 0; j < QK_K; j += 8) m = _mm256_max_ps(_mm256_and_ps(_mm256_loadu_ps(x + j), absm), m);
405        __m128 h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps(m, 1));
406        h = _mm_max_ps(h, _mm_movehl_ps(h, h));
407        h = _mm_max_ss(h, _mm_movehdup_ps(h));
408        const float amax = _mm_cvtss_f32(h);
409        if (!amax) {
410            y[i].d = 0;
411            std::memset(y[i].qs, 0, QK_K);
412            continue;
413        }
414        float mx = 0.f;
415        const __m256 va = _mm256_set1_ps(amax);
416        for (int j = 0; j < QK_K; j += 8) {
417            const int msk = _mm256_movemask_ps(_mm256_cmp_ps(_mm256_and_ps(_mm256_loadu_ps(x + j), absm), va, _CMP_EQ_OQ));
418            if (msk) {
419                int b = 0;
420                while (!((msk >> b) & 1)) ++b;
421                mx = x[j + b];
422                break;
423            }
424        }
425        const float iscale = -127.f / mx;
426        const __m256 vis = _mm256_set1_ps(iscale);
427        for (int j = 0; j < QK_K; j += 32) {
428            __m256i v[4];
429            for (int q = 0; q < 4; ++q) {
430                __m256 p = _mm256_mul_ps(vis, _mm256_loadu_ps(x + j + 8 * q));
431#if defined(__GNUC__) && !defined(__clang__)
432                // GCC fuses a multiply and an add into an FMA by default (-ffp-contract=fast); the reference rounds
433                // the product before the add, so the product must stay a separate value
434                __asm__("" : "+x"(p));
435#endif
436                const __m256 t = _mm256_add_ps(p, magic);
437                v[q] = _mm256_min_epi32(_mm256_sub_epi32(_mm256_and_si256(_mm256_castps_si256(t), mant), off), c127);
438                // the reference stores MIN(127, v) into an int8 (keeps the low byte), and its bsums add those bytes:
439                // the same here, so even a degenerate block (iscale overflowing to inf) gives the same bytes
440                v[q] = _mm256_srai_epi32(_mm256_slli_epi32(v[q], 24), 24);
441            }
442            for (int q = 0; q < 2; ++q) {   // two 16-value sums
443                const __m256i s = _mm256_add_epi32(v[2 * q], v[2 * q + 1]);
444                __m128i s4 = _mm_add_epi32(_mm256_castsi256_si128(s), _mm256_extracti128_si256(s, 1));
445                s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0x4E));
446                s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0xB1));
447                y[i].bsums[j / 16 + q] = (int16_t) _mm_cvtsi128_si32(s4);
448            }
449            const __m256i p16a = _mm256_packs_epi32(v[0], v[1]), p16b = _mm256_packs_epi32(v[2], v[3]);
450            const __m256i p8 = _mm256_permutevar8x32_epi32(_mm256_packs_epi16(p16a, p16b), perm);
451            _mm256_storeu_si256((__m256i*) (y[i].qs + j), p8);
452        }
453        y[i].d = 1 / iscale;
454    }
455}
456
457void iq256_gu_rows_exact_one(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n,
458                             const void* act, float* ff, int r0, int r1) {
459    const auto* y = (const block_q8_K*) act;
460#if STRATA_AVXVNNI
461    if (vnni_on()) {
462        if (type == 16) vnni::gu_ggml_one<16>(blob, gu_row, up_off, n, y, ff, r0, r1);
463        else if (type == 17) vnni::gu_ggml_one<17>(blob, gu_row, up_off, n, y, ff, r0, r1);
464        else if (type == 18) {
465            if (iq256_variant() & kIq256Gather) vnni::gu_ggml_one<118>(blob, gu_row, up_off, n, y, ff, r0, r1);
466            else vnni::gu_ggml_one<18>(blob, gu_row, up_off, n, y, ff, r0, r1);
467        } else if (type == 21) {
468            if (iq256_variant() & kIq256Gather) vnni::gu_ggml_one<121>(blob, gu_row, up_off, n, y, ff, r0, r1);
469            else vnni::gu_ggml_one<21>(blob, gu_row, up_off, n, y, ff, r0, r1);
470        } else if (type == 22) {
471            if (iq256_variant() & kIq256Gather) vnni::gu_ggml_one<122>(blob, gu_row, up_off, n, y, ff, r0, r1);
472            else vnni::gu_ggml_one<22>(blob, gu_row, up_off, n, y, ff, r0, r1);
473        }
474        return;
475    }
476#endif
477    if (type == 16) plain::gu_ggml_one<16>(blob, gu_row, up_off, n, y, ff, r0, r1);
478    else if (type == 17) plain::gu_ggml_one<17>(blob, gu_row, up_off, n, y, ff, r0, r1);
479    else if (type == 18) {
480        if (iq256_variant() & kIq256Gather) plain::gu_ggml_one<118>(blob, gu_row, up_off, n, y, ff, r0, r1);
481        else plain::gu_ggml_one<18>(blob, gu_row, up_off, n, y, ff, r0, r1);
482    } else if (type == 21) {
483        if (iq256_variant() & kIq256Gather) plain::gu_ggml_one<121>(blob, gu_row, up_off, n, y, ff, r0, r1);
484        else plain::gu_ggml_one<21>(blob, gu_row, up_off, n, y, ff, r0, r1);
485    } else if (type == 22) {
486        if (iq256_variant() & kIq256Gather) plain::gu_ggml_one<122>(blob, gu_row, up_off, n, y, ff, r0, r1);
487        else plain::gu_ggml_one<22>(blob, gu_row, up_off, n, y, ff, r0, r1);
488    }
489}
490
491int iq256_variant() noexcept {
492    // STRATA_IQ256_GATHER=0/1 for every core; unset, where the calling thread's core gathers faster (per thread: a
493    // hybrid CPU's pool runs on P- and E-cores).  AVX-VNNI where cpu_avxvnni_ok().  The same bits either way.
494    const int s = iq256_gather_setting();
495    return ((s >= 0 ? s == 1 : cpu_gather_fast_here()) ? kIq256Gather : 0) | (vnni_on() ? kIq256Vnni : 0);
496}
497
498int iq256_variants() noexcept { return kIq256Gather | (vnni_on() ? kIq256Vnni : 0); }
499
500void iq256_gu_rows_v(int variant, int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n,
501                     const void* const* act, int nt, float* const* ff, int r0, int r1) {
502    const bool g = (variant & kIq256Gather) != 0;
503#if STRATA_AVXVNNI
504    if (variant & kIq256Vnni) {
505        if (g) vnni::gu_type<true>(type, nt, blob, gu_row, up_off, n, act, ff, r0, r1);
506        else vnni::gu_type<false>(type, nt, blob, gu_row, up_off, n, act, ff, r0, r1);
507        return;
508    }
509#endif
510    if (g) plain::gu_type<true>(type, nt, blob, gu_row, up_off, n, act, ff, r0, r1);
511    else plain::gu_type<false>(type, nt, blob, gu_row, up_off, n, act, ff, r0, r1);
512}
513
514void iq256_rows_v(int variant, int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt,
515                  float* const* out, int r0, int r1) {
516    const bool g = (variant & kIq256Gather) != 0;
517#if STRATA_AVXVNNI
518    if (variant & kIq256Vnni) {
519        if (g) vnni::dot_type<true>(type, nt, w, row_bytes, n, act, out, r0, r1);
520        else vnni::dot_type<false>(type, nt, w, row_bytes, n, act, out, r0, r1);
521        return;
522    }
523#endif
524    if (g) plain::dot_type<true>(type, nt, w, row_bytes, n, act, out, r0, r1);
525    else plain::dot_type<false>(type, nt, w, row_bytes, n, act, out, r0, r1);
526}
527
528void iq256_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act, int nt,
529                   float* const* ff, int r0, int r1) {
530    iq256_gu_rows_v(iq256_variant(), type, blob, gu_row, up_off, n, act, nt, ff, r0, r1);
531}
532
533void iq256_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
534                int r0, int r1) {
535    iq256_rows_v(iq256_variant(), type, w, row_bytes, n, act, nt, out, r0, r1);
536}
537
538bool iq256x_supported(int type) noexcept { return type == 16 || type == 17 || type == 18 || type == 21 || type == 22 || type == 29; }
539
540void iq256x_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* act, int nt, float* const* out,
541                 int r0, int r1) {
542    const int variant = iq256_variant();
543    const bool g = (variant & kIq256Gather) != 0;
544#if STRATA_AVXVNNI
545    if (variant & kIq256Vnni) {
546        if (g) vnni::dot_type<true, true>(type, nt, w, row_bytes, n, act, out, r0, r1);
547        else vnni::dot_type<false, true>(type, nt, w, row_bytes, n, act, out, r0, r1);
548        return;
549    }
550#endif
551    if (g) plain::dot_type<true, true>(type, nt, w, row_bytes, n, act, out, r0, r1);
552    else plain::dot_type<false, true>(type, nt, w, row_bytes, n, act, out, r0, r1);
553}
554
555void iq4nl256_down_rows_v(int variant, const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt,
556                          float* const* out, int r0, int r1) {
557    const block_q8_0* y[8];
558    for (int t = 0; t < nt; ++t) y[t] = (const block_q8_0*) hq[t];
559#if STRATA_AVXVNNI
560    if (variant & kIq256Vnni) {
561        vnni::iq4nl_nt(w, row_bytes, n, y, nt, out, r0, r1);
562        return;
563    }
564#endif
565    (void) variant;
566    plain::iq4nl_nt(w, row_bytes, n, y, nt, out, r0, r1);
567}
568
569void iq4nl256_down_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, float* const* out,
570                        int r0, int r1) {
571    iq4nl256_down_rows_v(vnni_on() ? kIq256Vnni : 0, w, row_bytes, n, hq, nt, out, r0, r1);
572}
573
574
575// Singleton-equivalent down accumulation; legacy/VNNI kernels above keep their order.
576namespace {
577namespace singleton_iq4nl {
578
579float h2f(uint16_t x) {
580    return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128(x)));
581}
582float hsum(__m256 x) {
583    __m128 s = _mm256_extractf128_ps(x, 1);
584    s = _mm_add_ps(s, _mm256_castps256_ps128(x));
585    s = _mm_add_ps(s, _mm_movehl_ps(s, s));
586    s = _mm_add_ss(s, _mm_movehdup_ps(s));
587    return _mm_cvtss_f32(s);
588}
589template <int NT>
590void rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, float* const* out, int r0, int r1) {
591    const __m128i values = _mm_loadu_si128((const __m128i*)kvalues_iq4nl), mask = _mm_set1_epi8(15);
592    const __m256i ones = _mm256_set1_epi16(1);
593    const int nb = n / QK4_NL;
594    for (int r = r0; r < r1; ++r) {
595        auto* x = (const block_iq4_nl*)(w + r * row_bytes);
596        __m256 even[NT], odd[NT];
597        for (int t = 0; t < NT; ++t) {
598            even[t] = _mm256_setzero_ps();
599            odd[t] = _mm256_setzero_ps();
600        }
601        int ib = 0;
602        for (; ib + 1 < nb; ib += 2) {
603            const __m128i b0 = _mm_loadu_si128((const __m128i*)x[ib].qs),
604                          b1 = _mm_loadu_si128((const __m128i*)x[ib + 1].qs);
605            const __m256i w0 =
606                _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_shuffle_epi8(values, _mm_and_si128(b0, mask))),
607                                        _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(b0, 4), mask)), 1);
608            const __m256i w1 =
609                _mm256_inserti128_si256(_mm256_castsi128_si256(_mm_shuffle_epi8(values, _mm_and_si128(b1, mask))),
610                                        _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(b1, 4), mask)), 1);
611            const __m256i a0 = _mm256_sign_epi8(w0, w0), a1 = _mm256_sign_epi8(w1, w1);
612            const float d0 = h2f(x[ib].d), d1 = h2f(x[ib + 1].d);
613            for (int t = 0; t < NT; ++t) {
614                auto* y = (const block_q8_0*)hq[t];
615                auto p0 = _mm256_madd_epi16(
616                    _mm256_maddubs_epi16(a0, _mm256_sign_epi8(_mm256_loadu_si256((const __m256i*)y[ib].qs), w0)), ones);
617                auto p1 = _mm256_madd_epi16(
618                    _mm256_maddubs_epi16(a1, _mm256_sign_epi8(_mm256_loadu_si256((const __m256i*)y[ib + 1].qs), w1)),
619                    ones);
620                even[t] = _mm256_fmadd_ps(_mm256_set1_ps(h2f(y[ib].d) * d0), _mm256_cvtepi32_ps(p0), even[t]);
621                odd[t] = _mm256_fmadd_ps(_mm256_set1_ps(h2f(y[ib + 1].d) * d1), _mm256_cvtepi32_ps(p1), odd[t]);
622            }
623        }
624        for (int t = 0; t < NT; ++t) {
625            float s = hsum(_mm256_add_ps(even[t], odd[t]));
626            if (ib < nb) {
627                auto* y = (const block_q8_0*)hq[t];
628                int a = 0, b = 0;
629                for (int j = 0; j < QK4_NL / 2; ++j) {
630                    a += kvalues_iq4nl[x[ib].qs[j] & 15] * y[ib].qs[j];
631                    b += kvalues_iq4nl[x[ib].qs[j] >> 4] * y[ib].qs[j + QK4_NL / 2];
632                }
633                const float d = h2f(y[ib].d) * h2f(x[ib].d);
634                s += d * (a + b);
635            }
636            out[t][r] = s;
637        }
638    }
639}
640} // namespace singleton_iq4nl
641} // namespace
642void iq4nl_reference_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt, float* const* out,
643                          int r0, int r1) {
644    for (int at = 0; at < nt; at += 4) {
645        int k = nt - at < 4 ? nt - at : 4;
646        switch (k) {
647        case 1:
648            singleton_iq4nl::rows<1>(w, row_bytes, n, hq + at, out + at, r0, r1);
649            break;
650        case 2:
651            singleton_iq4nl::rows<2>(w, row_bytes, n, hq + at, out + at, r0, r1);
652            break;
653        case 3:
654            singleton_iq4nl::rows<3>(w, row_bytes, n, hq + at, out + at, r0, r1);
655            break;
656        case 4:
657            singleton_iq4nl::rows<4>(w, row_bytes, n, hq + at, out + at, r0, r1);
658            break;
659        }
660    }
661}
662
663} // namespace strata::kernels::cpu