okami.mom/strata

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

Niko1221Merge f-142b-cuda into f-14254d7f7d7c

main
25.9 KiB511 linesraw
1// src/kernels/cpu/iq_avx1.cpp - the i-quant expert rows for CPUs without AVX2 (STRATA_ISA_FLOOR=avx:
2// Sandy/Ivy Bridge, Xeon E5 v1/v2, Bulldozer).  See iq_avx1.hpp.
3//
4// iq_avx2.cpp's multi-token scheme in 128-bit lanes: each 32-value chunk is decoded once per verify window
5// (grid lookups, one sign vector, one scale vector) and every token applies it with a load, a sign, a
6// maddubs, a madd and an add - all SSSE3/SSE2, all available since Core 2.  The 256-bit integer ops of the
7// AVX2 kernel (pshufb/maddubs/sign_epi8 in __m256i, vpgather, vpdpbusd) have no AVX1 form and no FMA exists
8// there, so the float accumulation is a plain SSE2 mul+add.  Without these kernels such a CPU runs every
9// expert on ggml-cpu's scalar `_generic` dots (every x86 i-quant dot is #if defined(__AVX2__)).
10//
11// The arithmetic is ggml's (ggml-cpu/quants.c, the `_generic` references) - only the order of the float
12// additions differs; the integer sums are exact.  iq_avx1_parity checks: rows vs ggml-cpu's dot rel <= 1e-5,
13// and a multi-token row bit for bit the same kernel's single-token row for that token (#152).
14//
15// Formats: gate/up IQ3_XXS (18), IQ3_S (21), IQ2_S (22), IQ4_XS (23); down IQ4_NL (20) and Q2_0 (42, the
16// fork's type).  IQ2_XXS/IQ2_XS have no layer in the packs that need this and stay on ggml-cpu's dot.
17//
18// This file is compiled for SSE4.2 + AVX with AVX2/FMA/F16C explicitly off (CMakeLists.txt), and the engine
19// calls it only behind cpu_avx1_ok().  No static constructors at namespace scope (#391): the tables below
20// are constexpr, like iq_avx2.cpp's.
21#include "strata/kernels/cpu/iq_avx1.hpp"
22
23#include "ggml.h"
24
25#define GGML_COMMON_DECL_CPP
26#define GGML_COMMON_IMPL_CPP
27#include "ggml-common.h"
28
29#include <immintrin.h>
30
31#include <cmath>
32#include <cstdlib>
33#include <cstring>
34
35#if !defined(__AVX__)
36#error "iq_avx1.cpp must be compiled with AVX enabled (see the per-source flags in CMakeLists.txt)"
37#endif
38#if defined(__FMA__) || defined(__F16C__)
39#error "iq_avx1.cpp must be compiled without FMA/F16C: it runs on CPUs (Sandy/Ivy Bridge) that lack them"
40#endif
41
42namespace strata::kernels::cpu {
43namespace {
44
45// fp16 -> fp32 without F16C (expert.cpp's h2f: the conversion written out, subnormals included).
46inline float h2f(uint16_t h) {
47    const uint32_t sign = (uint32_t) (h >> 15) & 1u;
48    uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f;
49    if (exp == 0) {
50        if (man == 0) {
51            f = sign << 31;
52        } else {
53            exp = 127 - 15 + 1;
54            while (!(man & 0x400u)) { man <<= 1; --exp; }
55            man &= 0x3FFu;
56            f = (sign << 31) | (exp << 23) | (man << 13);
57        }
58    } else if (exp == 31) {
59        f = (sign << 31) | 0x7F800000u | (man << 13);
60    } else {
61        f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13);
62    }
63    float out;
64    std::memcpy(&out, &f, 4);
65    return out;
66}
67
68inline uint32_t u32(const uint8_t* p) { uint32_t v; std::memcpy(&v, p, 4); return v; }
69inline uint16_t u16(const uint8_t* p) { uint16_t v; std::memcpy(&v, p, 2); return v; }
70inline uint64_t u64(const uint8_t* p) { uint64_t v; std::memcpy(&v, p, 8); return v; }
71
72// The sign-vector pattern of iq_avx2.cpp's sgn_vec_at in 128-bit: 16 values from two sign bytes.
73// bits = the two bytes broadcast over the 16 lanes, sel = bit k of each byte per lane, -> 16 bytes of
74// -1 (bit set) / +1.  ggml's bit_selector pattern, same bits.
75inline __m128i sgn16(uint32_t w, int byte_pair) {   // byte_pair 0: bytes 0-1 (values 0-15), 1: bytes 2-3
76    const __m128i bits = _mm_shuffle_epi8(_mm_set1_epi32((int) w),
77                                          byte_pair ? _mm_setr_epi8(2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3)
78                                                    : _mm_setr_epi8(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1));
79    const __m128i sel = _mm_setr_epi8(1, 2, 4, 8, 16, 32, 64, (char) 0x80, 1, 2, 4, 8, 16, 32, 64, (char) 0x80);
80    return _mm_or_si128(_mm_cmpeq_epi8(_mm_and_si128(bits, sel), sel), _mm_set1_epi8(1));
81}
82
83// keven_signs_q2xs as a constexpr table (iq_avx2.cpp's EvenSigns; byte k = 0xFF when bit k of
84// ksigns_iq2xs[i] is set, 0x01 otherwise).  constexpr, not a runtime constructor (#391).
85struct EvenSigns {
86    uint64_t v[128];
87    constexpr EvenSigns() : v{} {
88        for (int i = 0; i < 128; ++i) {
89            int par = 0;
90            for (int k = 0; k < 7; ++k) par ^= (i >> k) & 1;
91            const int s = i | (par << 7);          // == ksigns_iq2xs[i]
92            uint64_t r = 0;
93            for (int k = 0; k < 8; ++k) r |= (uint64_t) (((s >> k) & 1) ? 0xFF : 0x01) << (8 * k);
94            v[i] = r;
95        }
96    }
97};
98static constexpr EvenSigns even_signs{};
99static_assert(even_signs.v[0] == 0x0101010101010101ull && even_signs.v[1] == 0xFF010101010101FFull,
100              "keven_signs_q2xs: byte k = 0xFF when bit k of ksigns_iq2xs[i] is set");
101
102// The high index bits of a 32-value half spread one per byte (iq_avx2.cpp's HiSpread): punpcklbw puts them
103// next to the low index bytes, so every grid index is a 16-bit load.  IQ3_S: byte k = bit k (the 9th bit of
104// index k).  IQ2_S: byte k = bits 2k,2k+1 (bits 8-9 of index k), k < 4.
105struct HiSpread {
106    uint64_t iq3s[256];
107    uint64_t iq2s[256];
108    constexpr HiSpread() : iq3s{}, iq2s{} {
109        for (int h = 0; h < 256; ++h) {
110            uint64_t r3 = 0, r2 = 0;
111            for (int k = 0; k < 8; ++k) r3 |= (uint64_t) ((h >> k) & 1) << (8 * k);
112            for (int k = 0; k < 4; ++k) r2 |= (uint64_t) ((h >> (2 * k)) & 3) << (8 * k);
113            iq3s[h] = r3;
114            iq2s[h] = r2;
115        }
116    }
117};
118static constexpr HiSpread hi_spread{};
119static_assert(hi_spread.iq3s[0x81] == 0x0100000000000001ull && hi_spread.iq2s[0xE4] == 0x0000000003020100ull,
120              "hi_spread: one high-bit group per index byte");
121
122// The low index bytes interleaved with the spread high bits: eight 16-bit grid indices in one register.
123// (iq_avx2.cpp's grid_indices stores them to memory; on Ivy Bridge that store -> narrow-load round trip
124// costs a forwarding stall per index, so the decoders below read the lanes with _mm_extract_epi16 instead.)
125inline __m128i grid_idx(const uint8_t* q, uint64_t hi) {
126    return _mm_unpacklo_epi8(_mm_loadl_epi64((const __m128i*) q), _mm_cvtsi64_si128((long long) hi));
127}
128
129inline float hsum4(__m128 v) {
130    __m128 s = _mm_add_ps(v, _mm_movehl_ps(v, v));
131    s = _mm_add_ss(s, _mm_movehdup_ps(s));
132    return _mm_cvtss_f32(s);
133}
134
135// E-2 prefetching, the same knob as the AVX-2/512 kernels: STRATA_IQ_PREFETCH is the distance in bytes.
136int prefetch_distance() {
137    static const int d = [] {
138        const char* v = std::getenv("STRATA_IQ_PREFETCH");
139        return v ? std::atoi(v) : 2048;
140    }();
141    return d;
142}
143
144inline void rows_ahead(const uint8_t* blk, int pf) {
145    if (pf <= 0) return;
146    _mm_prefetch((const char*) blk + pf, _MM_HINT_T0);
147    _mm_prefetch((const char*) blk + pf + 64, _MM_HINT_T0);
148}
149
150// ---- per format: one 32-value half (values 64*j + 32*half .. +31) -> grid magnitudes, sign vector and
151// scales as TWO 16-value halves (g0/g1, s0/s1, c0/c1).
152template <int TY> struct Fmt128;
153
154template <> struct Fmt128<18> {   // IQ3_XXS: d, qs[64] grid bytes, 8 x u32 (4 x 7-bit sign index + 4-bit scale)
155    static constexpr int bytes = 98;
156    static constexpr float K = 0.25f;
157    static inline void decode(const uint8_t* b, int j, int half,
158                              __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) {
159        const uint8_t* q = b + 2 + 16 * j + 8 * half;
160        g0 = _mm_set_epi32((int) iq3xxs_grid[q[3]], (int) iq3xxs_grid[q[2]],
161                           (int) iq3xxs_grid[q[1]], (int) iq3xxs_grid[q[0]]);
162        g1 = _mm_set_epi32((int) iq3xxs_grid[q[7]], (int) iq3xxs_grid[q[6]],
163                           (int) iq3xxs_grid[q[5]], (int) iq3xxs_grid[q[4]]);
164        const uint32_t w = u32(b + 2 + 64 + 8 * j + 4 * half);
165        s0 = _mm_set_epi64x((long long) even_signs.v[(w >> 7) & 127], (long long) even_signs.v[w & 127]);
166        s1 = _mm_set_epi64x((long long) even_signs.v[(w >> 21) & 127], (long long) even_signs.v[(w >> 14) & 127]);
167        c0 = c1 = _mm_set1_epi16((short) (2 * (int) (w >> 28) + 1));
168    }
169};
170
171template <> struct Fmt128<21> {   // IQ3_S: d, qs[64], qh[8], signs[32], scales[4]
172    static constexpr int bytes = 110;
173    static constexpr float K = 1.0f;
174    static inline void decode(const uint8_t* b, int j, int half,
175                              __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) {
176        const uint8_t* q = b + 2 + 16 * j + 8 * half;
177        const __m128i idx = grid_idx(q, hi_spread.iq3s[b[66 + 2 * j + half]]);
178#define G3(k) (int) iq3s_grid[_mm_extract_epi16(idx, k)]
179        g0 = _mm_set_epi32(G3(3), G3(2), G3(1), G3(0));
180        g1 = _mm_set_epi32(G3(7), G3(6), G3(5), G3(4));
181#undef G3
182        const uint32_t sg = u32(b + 74 + 8 * j + 4 * half);
183        s0 = sgn16(sg, 0);
184        s1 = sgn16(sg, 1);
185        const uint8_t s = b[106 + j];
186        c0 = c1 = _mm_set1_epi16((short) (2 * (int) (half ? s >> 4 : s & 15) + 1));
187    }
188};
189
190template <> struct Fmt128<22> {   // IQ2_S: d, qs[64] (32 grid bytes, 32 sign bytes), qh[8], scales[8]
191    static constexpr int bytes = 82;
192    static constexpr float K = 0.125f;
193    static inline void decode(const uint8_t* b, int j, int half,
194                              __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) {
195        // only the first 4 index bytes are this half's (the load's rest stays inside the block)
196        const __m128i idx = grid_idx(b + 2 + 8 * j + 4 * half, hi_spread.iq2s[b[66 + 2 * j + half]]);
197        g0 = _mm_set_epi64x((long long) iq2s_grid[_mm_extract_epi16(idx, 1)],
198                            (long long) iq2s_grid[_mm_extract_epi16(idx, 0)]);
199        g1 = _mm_set_epi64x((long long) iq2s_grid[_mm_extract_epi16(idx, 3)],
200                            (long long) iq2s_grid[_mm_extract_epi16(idx, 2)]);
201        const uint32_t sg = u32(b + 2 + 32 + 8 * j + 4 * half);
202        s0 = sgn16(sg, 0);
203        s1 = sgn16(sg, 1);
204        const uint8_t sb = b[74 + 2 * j + half];
205        c0 = _mm_set1_epi16((short) (2 * (sb & 15) + 1));
206        c1 = _mm_set1_epi16((short) (2 * (sb >> 4) + 1));
207    }
208};
209
210template <> struct Fmt128<23> {   // IQ4_XS: d, scales_h, scales_l[4], qs[128] - 136 B, 8 signed sub-scales
211    // ggml's ggml_vec_dot_iq4_xs_q8_K: the same 16-value codebook as IQ4_NL, one 6-bit scale per 32-value
212    // sub-block read as two nibbles of scales_l plus two bits of scales_h, used SIGNED as (ls - 32): the
213    // scale folds into the int16 operand of madd_epi16.  The codebook sign rides on sign_epi8, |w| is the
214    // unsigned maddubs operand (a pair is at most 2 * 127 * 128, no saturation).
215    static constexpr int bytes = 136;
216    static constexpr float K = 1.0f;
217    static inline void decode(const uint8_t* b, int j, int half,
218                              __m128i& g0, __m128i& g1, __m128i& s0, __m128i& s1, __m128i& c0, __m128i& c1) {
219        const int H = 2 * j + half;
220        const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl);
221        const __m128i bits = _mm_loadu_si128((const __m128i*) (b + 8 + 16 * H));
222        const __m128i m4 = _mm_set1_epi8(0x0f);
223        const __m128i v0 = _mm_shuffle_epi8(values, _mm_and_si128(bits, m4));
224        const __m128i v1 = _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4));
225        g0 = _mm_sign_epi8(v0, v0);
226        g1 = _mm_sign_epi8(v1, v1);
227        s0 = _mm_sign_epi8(_mm_set1_epi8(1), v0);
228        s1 = _mm_sign_epi8(_mm_set1_epi8(1), v1);
229        const int ls = ((b[4 + (H >> 1)] >> (4 * (H & 1))) & 0xf) | (((u16(b + 2) >> (2 * H)) & 3) << 4);
230        c0 = c1 = _mm_set1_epi16((short) (ls - 32));
231    }
232};
233
234// acc + madd(maddubs(g, sign(y, sgn)), sc): the AVX2 kernel's per-token application in 128-bit.
235inline __m128i madd_add(__m128i acc, __m128i g, __m128i sgn, __m128i yv, __m128i sc) {
236    return _mm_add_epi32(acc, _mm_madd_epi16(_mm_maddubs_epi16(g, _mm_sign_epi8(yv, sgn)), sc));
237}
238
239// ---- the row kernels (iq_avx2_rows.inl's row_dot in 128-bit lanes)
240template <int TY, int NT>
241inline void row_dot(const uint8_t* row, int nblocks, const block_q8_K* const* y, float* res) {
242    const int pf = prefetch_distance();
243    __m128 accf[NT];
244    for (int t = 0; t < NT; ++t) accf[t] = _mm_setzero_ps();
245    for (int i = 0; i < nblocks; ++i) {
246        const uint8_t* blk = row + (size_t) i * Fmt128<TY>::bytes;
247        rows_ahead(blk, pf);
248        __m128i acci[NT][2];
249        for (int t = 0; t < NT; ++t) acci[t][0] = acci[t][1] = _mm_setzero_si128();
250        for (int j = 0; j < 4; ++j) {
251            for (int half = 0; half < 2; ++half) {
252                __m128i g0, g1, s0, s1, c0, c1;
253                Fmt128<TY>::decode(blk, j, half, g0, g1, s0, s1, c0, c1);
254                const int off = 64 * j + 32 * half;
255                for (int t = 0; t < NT; ++t) {
256                    const uint8_t* q8 = (const uint8_t*) (y[t][i].qs + off);
257                    acci[t][0] = madd_add(acci[t][0], g0, s0, _mm_loadu_si128((const __m128i*) q8), c0);
258                    acci[t][1] = madd_add(acci[t][1], g1, s1, _mm_loadu_si128((const __m128i*) (q8 + 16)), c1);
259                }
260            }
261        }
262        const float dx = h2f(u16(blk)) * Fmt128<TY>::K;
263        for (int t = 0; t < NT; ++t) {
264            const __m128 f = _mm_add_ps(_mm_cvtepi32_ps(acci[t][0]), _mm_cvtepi32_ps(acci[t][1]));
265            accf[t] = _mm_add_ps(accf[t], _mm_mul_ps(_mm_set1_ps(dx * y[t][i].d), f));
266        }
267    }
268    for (int t = 0; t < NT; ++t) res[t] = hsum4(accf[t]);
269}
270
271template <int TY, int NT>
272inline void gu_rows(const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
273                    float* const* ff, int r0, int r1) {
274    const block_q8_K* y[NT];
275    for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
276    const int nb = n / QK_K;
277    float g[NT], u[NT];
278    for (int r = r0; r < r1; ++r) {
279        row_dot<TY, NT>(blob + (size_t) r * gu_row, nb, y, g);
280        row_dot<TY, NT>(blob + up_off + (size_t) r * gu_row, nb, y, u);
281        for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t];
282    }
283}
284
285template <int TY, int NT>
286inline void dot_rows(const uint8_t* w, size_t row_bytes, int n, const void* const* act, float* const* out,
287                     int r0, int r1) {
288    const block_q8_K* y[NT];
289    for (int t = 0; t < NT; ++t) y[t] = (const block_q8_K*) act[t];
290    float res[NT];
291    for (int r = r0; r < r1; ++r) {
292        row_dot<TY, NT>(w + (size_t) r * row_bytes, n / QK_K, y, res);
293        for (int t = 0; t < NT; ++t) out[t][r] = res[t];
294    }
295}
296
297template <int TY>
298void gu_rows_nt(int nt, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
299                float* const* ff, int r0, int r1) {
300    switch (nt) {
301        case 1: gu_rows<TY, 1>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
302        case 2: gu_rows<TY, 2>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
303        case 3: gu_rows<TY, 3>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
304        case 4: gu_rows<TY, 4>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
305        case 5: gu_rows<TY, 5>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
306        case 6: gu_rows<TY, 6>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
307        case 7: gu_rows<TY, 7>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
308        default: gu_rows<TY, 8>(blob, gu_row, up_off, n, act, ff, r0, r1); break;
309    }
310}
311
312// ---- IQ4_NL (20) down rows against Q8_0: ggml's dot is single-token even where it is vectorized (and
313// scalar here); decode the nibbles once, every token pays a sign, a maddubs, a madd and an fmadd-equivalent.
314template <int NT>
315void iq4nl_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* const* y, float* const* out,
316                int r0, int r1) {
317    const __m128i values = _mm_loadu_si128((const __m128i*) kvalues_iq4nl);
318    const __m128i m4b = _mm_set1_epi8(0x0f);
319    const __m128i ones = _mm_set1_epi16(1);
320    const int nb = n / QK4_NL;
321    const int pf = prefetch_distance();
322    for (int r = r0; r < r1; ++r) {
323        const uint8_t* row = w + (size_t) r * row_bytes;
324        __m128 accf[NT];
325        for (int t = 0; t < NT; ++t) accf[t] = _mm_setzero_ps();
326        for (int ib = 0; ib < nb; ++ib) {
327            const uint8_t* blk = row + (size_t) ib * sizeof(block_iq4_nl);
328            rows_ahead(blk, pf);
329            const __m128i bits = _mm_loadu_si128((const __m128i*) (blk + 2));
330            const __m128i v0 = _mm_shuffle_epi8(values, _mm_and_si128(bits, m4b));
331            const __m128i v1 = _mm_shuffle_epi8(values, _mm_and_si128(_mm_srli_epi16(bits, 4), m4b));
332            const __m128i aq0 = _mm_sign_epi8(v0, v0);   // |w|: the unsigned maddubs operand
333            const __m128i aq1 = _mm_sign_epi8(v1, v1);
334            const float dx = h2f(u16(blk));
335            for (int t = 0; t < NT; ++t) {
336                const uint8_t* q8 = (const uint8_t*) y[t][ib].qs;
337                const __m128i p0 = _mm_madd_epi16(_mm_maddubs_epi16(aq0, _mm_sign_epi8(_mm_loadu_si128((const __m128i*) q8), v0)), ones);
338                const __m128i p1 = _mm_madd_epi16(_mm_maddubs_epi16(aq1, _mm_sign_epi8(_mm_loadu_si128((const __m128i*) (q8 + 16)), v1)), ones);
339                const __m128 f = _mm_add_ps(_mm_cvtepi32_ps(p0), _mm_cvtepi32_ps(p1));
340                accf[t] = _mm_add_ps(accf[t], _mm_mul_ps(_mm_set1_ps(dx * h2f(y[t][ib].d)), f));
341            }
342        }
343        for (int t = 0; t < NT; ++t) out[t][r] = hsum4(accf[t]);
344    }
345}
346
347// ---- Q2_0 (42) down rows against Q8_0: ggml-cpu has only the scalar generic dot for this type on x86.
348// Codes {0,1,2,3} map to {c-1}: unpack to unsigned code bytes, dot them with maddubs, and subtract the
349// activation's pair sums - all integer, so the per-block sum is EXACTLY the generic dot's sumi_block.
350template <int NT>
351void q2_0_rows(const uint8_t* w, size_t row_bytes, int n, const block_q8_0* const* y, float* const* out,
352               int r0, int r1) {
353    const __m128i m3 = _mm_set1_epi8(3);
354    const __m128i ones = _mm_set1_epi16(1);
355    const int nb = n / QK2_0;
356    const int pf = prefetch_distance();
357    for (int r = r0; r < r1; ++r) {
358        const uint8_t* row = w + (size_t) r * row_bytes;
359        __m128 accf[NT];
360        for (int t = 0; t < NT; ++t) accf[t] = _mm_setzero_ps();
361        for (int i = 0; i < nb; ++i) {
362            const uint8_t* blk = row + (size_t) i * sizeof(block_q2_0);
363            rows_ahead(blk, pf);
364            const float dx = h2f(u16(blk));
365            const uint8_t* qs = blk + 2;
366            for (int k = 0; k < 2; ++k) {
367                // 8 code bytes -> 32 unsigned codes in order (c0..c3 = the four 2-bit groups of each byte)
368                const __m128i q = _mm_cvtsi64_si128((long long) u64(qs + 8 * k));
369                const __m128i c0 = _mm_and_si128(q, m3);
370                const __m128i c1 = _mm_and_si128(_mm_srli_epi16(q, 2), m3);
371                const __m128i c2 = _mm_and_si128(_mm_srli_epi16(q, 4), m3);
372                const __m128i c3 = _mm_and_si128(_mm_srli_epi32(q, 6), m3);
373                const __m128i t01 = _mm_unpacklo_epi8(c0, c1);
374                const __m128i t23 = _mm_unpacklo_epi8(c2, c3);
375                const __m128i k0 = _mm_unpacklo_epi16(t01, t23);   // codes 0..15
376                const __m128i k1 = _mm_unpackhi_epi16(t01, t23);   // codes 16..31
377                for (int t = 0; t < NT; ++t) {
378                    const uint8_t* q8 = (const uint8_t*) y[t][i * 2 + k].qs;
379                    const __m128i y0 = _mm_loadu_si128((const __m128i*) q8);
380                    const __m128i y1 = _mm_loadu_si128((const __m128i*) (q8 + 16));
381                    // (c-1)*qy per pair: c*qy - qy, both at int16 level (|result| <= 508, no saturation)
382                    const __m128i d0 = _mm_sub_epi16(_mm_maddubs_epi16(k0, y0), _mm_maddubs_epi16(_mm_set1_epi8(1), y0));
383                    const __m128i d1 = _mm_sub_epi16(_mm_maddubs_epi16(k1, y1), _mm_maddubs_epi16(_mm_set1_epi8(1), y1));
384                    const __m128 f = _mm_add_ps(_mm_cvtepi32_ps(_mm_madd_epi16(d0, ones)),
385                                                _mm_cvtepi32_ps(_mm_madd_epi16(d1, ones)));
386                    accf[t] = _mm_add_ps(accf[t], _mm_mul_ps(_mm_set1_ps(dx * h2f(y[t][i * 2 + k].d)), f));
387                }
388            }
389        }
390        for (int t = 0; t < NT; ++t) out[t][r] = hsum4(accf[t]);
391    }
392}
393
394}  // namespace
395
396bool iq128_supported(int type) noexcept {
397    // IQ4_XS (23) is deliberately NOT here: its ggml generic dot auto-vectorizes well and beats the 128-bit
398    // grid kernel (0.7-1.0x in iq_avx1_parity --bench on an E5-2470 v2); the generic stays for that format's
399    // gate/up rows.  Its down rows (IQ4_NL/Q2_0) still take iq128_down_rows.  The kernel itself stays built
400    // and parity-tested.
401    return type == 18 || type == 21 || type == 22;
402}
403
404bool iq128_down_supported(int type) noexcept {
405    return type == 20 || type == 42;
406}
407
408void iq128_gu_rows(int type, const uint8_t* blob, size_t gu_row, size_t up_off, int n, const void* const* act,
409                   int nt, float* const* ff, int r0, int r1) {
410    switch (type) {
411        case 18: gu_rows_nt<18>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
412        case 21: gu_rows_nt<21>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
413        case 22: gu_rows_nt<22>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
414        case 23: gu_rows_nt<23>(nt, blob, gu_row, up_off, n, act, ff, r0, r1); break;
415        default: break;
416    }
417}
418
419void iq128_down_rows(int type, const uint8_t* w, size_t row_bytes, int n, const void* const* hq, int nt,
420                     float* const* out, int r0, int r1) {
421    const block_q8_0* y[8];
422    for (int t = 0; t < nt && t < 8; ++t) y[t] = (const block_q8_0*) hq[t];
423    if (type == 20) {
424        for (int t0 = 0; t0 < nt; t0 += 4) {
425            const int k = nt - t0 < 4 ? nt - t0 : 4;
426            switch (k) {
427                case 1: iq4nl_rows<1>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
428                case 2: iq4nl_rows<2>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
429                case 3: iq4nl_rows<3>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
430                default: iq4nl_rows<4>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
431            }
432        }
433        return;
434    }
435    // Q2_0: the same 4-at-a-time chunking (NT is capped at 8 by the pool; prefill chunks larger than 8
436    // loop here, the per-token rows identical either way).
437    for (int t0 = 0; t0 < nt; t0 += 4) {
438        const int k = nt - t0 < 4 ? nt - t0 : 4;
439        switch (k) {
440            case 1: q2_0_rows<1>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
441            case 2: q2_0_rows<2>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
442            case 3: q2_0_rows<3>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
443            default: q2_0_rows<4>(w, row_bytes, n, y + t0, out + t0, r0, r1); break;
444        }
445    }
446}
447
448// ggml's quantize_row_q8_K_ref in SSE4.2/AVX1: q8k_quant_avx2's arithmetic, 128-bit lanes (its packs need no
449// lane-crossing permute at 128-bit).  The same per-value operations as the scalar reference - one IEEE multiply
450// by the same iscale, the same 1.5*2^23 rounding add, the same clamp - so the bytes are identical
451// (q8k_quant_parity checks it), including the NaN and degenerate-block behavior: `ax > amax` is false for a NaN
452// and max_ps returns its second operand for a NaN first one, and a zero block leaves bsums as the reference does.
453void q8k_quant_avx1(const float* x, void* vy, int64_t k) {
454    block_q8_K* y = (block_q8_K*) vy;
455    const int64_t nb = k / QK_K;
456    const __m128 absm = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff));
457    const __m128 magic = _mm_set1_ps(12582912.f);
458    const __m128i mant = _mm_set1_epi32(0x007fffff), off = _mm_set1_epi32(0x00400000);
459    const __m128i c127 = _mm_set1_epi32(127);
460    for (int64_t i = 0; i < nb; ++i, x += QK_K) {
461        __m128 m = _mm_setzero_ps();
462        for (int j = 0; j < QK_K; j += 4) m = _mm_max_ps(_mm_and_ps(_mm_loadu_ps(x + j), absm), m);
463        __m128 h = _mm_max_ps(m, _mm_movehl_ps(m, m));
464        h = _mm_max_ss(h, _mm_movehdup_ps(h));
465        const float amax = _mm_cvtss_f32(h);
466        if (!amax) {
467            y[i].d = 0;
468            std::memset(y[i].qs, 0, QK_K);
469            continue;
470        }
471        float mx = 0.f;
472        const __m128 va = _mm_set1_ps(amax);
473        for (int j = 0; j < QK_K; j += 4) {
474            const int msk = _mm_movemask_ps(_mm_cmpeq_ps(_mm_and_ps(_mm_loadu_ps(x + j), absm), va));
475            if (msk) {
476                int b = 0;
477                while (!((msk >> b) & 1)) ++b;
478                mx = x[j + b];
479                break;
480            }
481        }
482        const float iscale = -127.f / mx;
483        const __m128 vis = _mm_set1_ps(iscale);
484        for (int j = 0; j < QK_K; j += 16) {
485            __m128i v[4];
486            for (int q = 0; q < 4; ++q) {
487                __m128 p = _mm_mul_ps(vis, _mm_loadu_ps(x + j + 4 * q));
488#if defined(__GNUC__) && !defined(__clang__)
489                // GCC fuses a multiply and an add into an FMA by default (-ffp-contract=fast); the reference
490                // rounds the product before the add, so the product must stay a separate value (no FMA under
491                // -mavx, but the barrier keeps the contract if the file is ever built with a newer floor)
492                __asm__("" : "+x"(p));
493#endif
494                const __m128 t = _mm_add_ps(p, magic);
495                v[q] = _mm_min_epi32(_mm_sub_epi32(_mm_and_si128(_mm_castps_si128(t), mant), off), c127);
496                // the reference stores MIN(127, v) into an int8 (keeps the low byte), and its bsums add those
497                // bytes: the same here, so even a degenerate block (iscale overflowing to inf) gives the same bytes
498                v[q] = _mm_srai_epi32(_mm_slli_epi32(v[q], 24), 24);
499            }
500            __m128i s = _mm_add_epi32(_mm_add_epi32(v[0], v[1]), _mm_add_epi32(v[2], v[3]));
501            s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0x4E));
502            s = _mm_add_epi32(s, _mm_shuffle_epi32(s, 0xB1));
503            y[i].bsums[j / 16] = (int16_t) _mm_cvtsi128_si32(s);
504            _mm_storeu_si128((__m128i*) (y[i].qs + j),
505                             _mm_packs_epi16(_mm_packs_epi32(v[0], v[1]), _mm_packs_epi32(v[2], v[3])));
506        }
507        y[i].d = 1 / iscale;
508    }
509}
510
511}  // namespace strata::kernels::cpu