okami.mom/strata

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

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

main
14.8 KiB294 linesraw
1// src/kernels/cpu/q2_avx1.cpp - the Q2_0 expert rows and the activation quantizer for CPUs that have AVX but
2// no AVX2 (Sandy Bridge through Ivy Bridge Xeons; issue #623, #1375), the third rung of q2_rows_any /
3// act_quant_any below the AVX-2 one (issue #1699: those dispatchers used to hand AVX2 code to an AVX1 CPU).
4//
5// The arithmetic is q2_avx2.cpp's: codes 0..3 against the int8 activation per 32-value chunk, times the weight
6// scale and the chunk scale, minus the weight scale times the chunk's `hx`.  128-bit integer lanes (maddubs and
7// madd are SSSE3/SSE2), 256-bit float accumulation with mul+add (no FMA), fp16 scales converted in software (no
8// F16C).  The legacy row kernel keeps q2_avx2.cpp's lane pairing and reduction tree exactly, so the only
9// difference from an AVX2 CPU is its FMA becoming mul+add (last bits, unavoidable without FMA); the bit-plane
10// kernel's float summation order is its own (last bits, as documented for the AVX-2 one), and every token's
11// operations are the same whatever the window width (#152).
12//
13// Compiled with -msse4.2 -mavx -mno-avx2 -mno-fma -mno-f16c (CMakeLists.txt, the iq_avx1.cpp pattern) and called
14// only behind cpu_avx1_ok() && !cpu_avx2_ok(), so no CPU that lacks those features can reach it - and no CPU that
15// has AVX2 changes what it runs.
16#include "strata/kernels/cpu/expert.hpp"
17#include "strata/kernels/cpu/expert_layout.hpp"
18
19#include <immintrin.h>
20
21#include <cmath>
22#include <cstdint>
23#include <cstdlib>
24#include <cstring>
25
26#if defined(__AVX2__) || defined(__FMA__) || defined(__F16C__)
27#error "q2_avx1.cpp must be compiled without AVX2, FMA and F16C (see the per-source flags in CMakeLists.txt)"
28#endif
29
30namespace strata::kernels::cpu {
31namespace {
32
33// fp16 -> fp32 without F16C (the written-out conversion, subnormals included; iq_avx1.cpp's copy).
34inline float h2f(uint16_t h) {
35    const uint32_t sign = (uint32_t) (h >> 15) & 1u;
36    uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f;
37    if (exp == 0) {
38        if (man == 0) {
39            f = sign << 31;
40        } else {
41            exp = 127 - 15 + 1;
42            while (!(man & 0x400u)) { man <<= 1; --exp; }
43            man &= 0x3FFu;
44            f = (sign << 31) | (exp << 23) | (man << 13);
45        }
46    } else if (exp == 31) {
47        f = (sign << 31) | 0x7F800000u | (man << 13);
48    } else {
49        f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13);
50    }
51    float out;
52    std::memcpy(&out, &f, 4);
53    return out;
54}
55
56// 16 bytes of 2-bit codes -> 64 codes in value order, four 16-byte vectors: v0 values 0..15, v1 16..31,
57// v2 32..47, v3 48..63 (q2_avx2.cpp's unpack64 cut to 128-bit lanes; the same interleave).
58inline void unpack64(const uint8_t* codes, __m128i& v0, __m128i& v1, __m128i& v2, __m128i& v3) {
59    const __m128i b = _mm_loadu_si128((const __m128i*) codes);
60    const __m128i m3 = _mm_set1_epi8(3);
61    const __m128i c0 = _mm_and_si128(b, m3);
62    const __m128i c1 = _mm_and_si128(_mm_srli_epi16(b, 2), m3);
63    const __m128i c2 = _mm_and_si128(_mm_srli_epi16(b, 4), m3);
64    const __m128i c3 = _mm_and_si128(_mm_srli_epi16(b, 6), m3);
65    const __m128i a0 = _mm_unpacklo_epi8(c0, c1), a1 = _mm_unpacklo_epi8(c2, c3);   // bytes 0..7
66    const __m128i b0 = _mm_unpackhi_epi8(c0, c1), b1 = _mm_unpackhi_epi8(c2, c3);   // bytes 8..15
67    v0 = _mm_unpacklo_epi16(a0, a1);   // values 0..15
68    v1 = _mm_unpackhi_epi16(a0, a1);   // values 16..31
69    v2 = _mm_unpacklo_epi16(b0, b1);   // values 32..47
70    v3 = _mm_unpackhi_epi16(b0, b1);   // values 48..63
71}
72
73// 16 codes against 16 activations, four products per int32 lane (q2_avx2_rows.inl's dot4 at 128-bit;
74// maddubs cannot saturate: a pair is at most 2 * 3 * 128).
75inline __m128i dot4(__m128i codes, __m128i act) {
76    return _mm_madd_epi16(_mm_maddubs_epi16(codes, act), _mm_set1_epi16(1));
77}
78
79// The legacy row kernel.  The accumulator pairing matches q2_avx2.cpp's lane pairing: each 256-bit lane takes
80// the s0 contribution (values 0..31) and the s1 contribution (values 32..63) into the SAME lanes, block by
81// block, and the reduction tree is the same one ((L0+L4)+(L2+L6)) + ((L1+L5)+(L3+L7)) - the only difference
82// from an AVX2 CPU is that kernel's FMA being a mul+add here (last bits).
83template <int NT>
84inline void row_multi(const uint8_t* row, const ActQ* const* a, int nblocks, float* res) {
85    __m256 acc[NT];
86    float corr[NT];
87    for (int t = 0; t < NT; ++t) { acc[t] = _mm256_setzero_ps(); corr[t] = 0.f; }
88    for (int b = 0; b < nblocks; ++b) {
89        const uint8_t* blk = row + (size_t) b * 18;
90        const float d = h2f((uint16_t) (blk[0] | (blk[1] << 8)));
91        __m128i v0, v1, v2, v3;
92        unpack64(blk + 2, v0, v1, v2, v3);
93        for (int t = 0; t < NT; ++t) {
94            const int8_t* q = a[t]->q + b * 64;
95            // s0 = values 0..31: lanes 0..3 of accA's 128-bit halves; s1 = values 32..63 into the SAME lanes
96            const __m128i s0a = dot4(v0, _mm_loadu_si128((const __m128i*) q));        // values 0..15
97            const __m128i s0b = dot4(v1, _mm_loadu_si128((const __m128i*) (q + 16))); // values 16..31
98            const __m128i s1a = dot4(v2, _mm_loadu_si128((const __m128i*) (q + 32))); // values 32..47
99            const __m128i s1b = dot4(v3, _mm_loadu_si128((const __m128i*) (q + 48))); // values 48..63
100            const __m256 s0 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_cvtepi32_ps(s0a)), _mm_cvtepi32_ps(s0b), 1);
101            const __m256 s1 = _mm256_insertf128_ps(_mm256_castps128_ps256(_mm_cvtepi32_ps(s1a)), _mm_cvtepi32_ps(s1b), 1);
102            // exactly the AVX-2 kernel's two fmadds: the whole s0 (values 0..31) by scale[2b], the whole s1
103            // (values 32..63) by scale[2b+1], into the same lanes - lane pairing and reduce tree follow suit
104            acc[t] = _mm256_add_ps(acc[t], _mm256_mul_ps(_mm256_set1_ps(d * a[t]->scale[2 * b]), s0));
105            acc[t] = _mm256_add_ps(acc[t], _mm256_mul_ps(_mm256_set1_ps(d * a[t]->scale[2 * b + 1]), s1));
106            corr[t] += d * (a[t]->hx[2 * b] + a[t]->hx[2 * b + 1]);
107        }
108    }
109    for (int t = 0; t < NT; ++t) {
110        const __m128 h = _mm_add_ps(_mm256_castps256_ps128(acc[t]), _mm256_extractf128_ps(acc[t], 1));
111        const __m128 s = _mm_add_ps(h, _mm_movehl_ps(h, h));
112        res[t] = _mm_cvtss_f32(_mm_add_ss(s, _mm_movehdup_ps(s))) - corr[t];
113    }
114}
115
116template <int NT>
117void rows(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, float* const* out, int r0, int r1) {
118    float res[NT];
119    for (int r = r0; r < r1; ++r) {
120        row_multi<NT>(w + (size_t) r * row_bytes, a, nblocks, res);
121        for (int t = 0; t < NT; ++t) out[t][r] = res[t];
122    }
123}
124
125// ---- the bit-plane row kernel (STRATA_Q2_BITPLANE=1), 128-bit lanes: one 64-value block at a time instead of
126// a pair per 256-bit register.  The integer part is exact; the float summation order is this kernel's own (the
127// same statement as for the AVX-2 one), and every row reduces with the same tree alone or in a group (#152).
128template <int NT>
129inline void row_bp_acc(const uint8_t* row, const ActQ* const* a, int npairs, __m128* acc) {
130    for (int t = 0; t < NT; ++t) { acc[2 * t] = _mm_setzero_ps(); acc[2 * t + 1] = _mm_setzero_ps(); }
131    const __m128i m3 = _mm_set1_epi8(3);
132    const __m128i ones = _mm_set1_epi16(1);
133    for (int p = 0; p < npairs; ++p) {
134        const uint8_t* blk = row + (size_t) p * 36;
135        for (int h = 0; h < 2; ++h) {
136            uint16_t dh;
137            std::memcpy(&dh, blk + h * 18, 2);          // the block's fp16 scale: bytes 0..1 (block 1 at +18)
138            const __m128 d = _mm_set1_ps(h2f(dh));
139            const __m128i c = _mm_loadu_si128((const __m128i*) (blk + 2 + h * 18));   // its 16 code bytes
140            const __m128i c0 = _mm_and_si128(c, m3);
141            const __m128i c1 = _mm_and_si128(_mm_srli_epi16(c, 2), m3);
142            const __m128i c2 = _mm_and_si128(_mm_srli_epi16(c, 4), m3);
143            const __m128i c3 = _mm_and_si128(_mm_srli_epi16(c, 6), m3);
144            for (int t = 0; t < NT; ++t) {
145                const int8_t* q = a[t]->qp + (size_t) p * 128 + h * 16;
146                __m128i s = _mm_maddubs_epi16(c0, _mm_load_si128((const __m128i*) q));
147                s = _mm_add_epi16(s, _mm_maddubs_epi16(c1, _mm_load_si128((const __m128i*) (q + 32))));
148                s = _mm_add_epi16(s, _mm_maddubs_epi16(c2, _mm_load_si128((const __m128i*) (q + 64))));
149                s = _mm_add_epi16(s, _mm_maddubs_epi16(c3, _mm_load_si128((const __m128i*) (q + 96))));
150                const __m128i i32 = _mm_sub_epi32(_mm_madd_epi16(s, ones),
151                                                  _mm_load_si128((const __m128i*) (a[t]->psum + p * 8 + h * 4)));
152                const __m128 v = _mm_mul_ps(_mm_cvtepi32_ps(i32),
153                                            _mm_load_ps(a[t]->pscale + p * 8 + h * 4));
154                __m128& x = acc[2 * t + h];
155                x = _mm_add_ps(x, _mm_mul_ps(d, v));
156            }
157        }
158    }
159}
160
161inline float reduce1(__m128 a, __m128 b) {   // ((v0+v1)+(v2+v3)) + ((v4+v5)+(v6+v7)), the AVX-2 kernel's tree
162    __m128 ha = _mm_hadd_ps(a, a);                        // [a0+a1, a2+a3, a0+a1, a2+a3]
163    ha = _mm_add_ss(ha, _mm_movehdup_ps(ha));             // (v0+v1)+(v2+v3)
164    __m128 hb = _mm_hadd_ps(b, b);
165    hb = _mm_add_ss(hb, _mm_movehdup_ps(hb));             // (v4+v5)+(v6+v7)
166    return _mm_cvtss_f32(_mm_add_ss(ha, hb));
167}
168
169template <int NT>
170void rows_bp(const uint8_t* w, size_t row_bytes, int npairs, const ActQ* const* a, float* const* out, int r0, int r1) {
171    for (int r = r0; r < r1; ++r) {
172        __m128 acc[2 * NT];
173        row_bp_acc<NT>(w + (size_t) r * row_bytes, a, npairs, acc);
174        for (int t = 0; t < NT; ++t) out[t][r] = reduce1(acc[2 * t], acc[2 * t + 1]);
175    }
176}
177
178const bool kBitplane = [] {
179    const char* e = std::getenv("STRATA_Q2_BITPLANE");
180    return e != nullptr && e[0] == '1';
181}();
182
183// ActQ::qp / psum / pscale from q and scale: q2_avx2.cpp's bitplane_image, which is already pure SSE2/SSSE3
184// (shuffle_epi8, sad, unpack) - copied rather than shared so q2_avx2.cpp stays untouched.
185void bitplane_image(ActQ& a) {
186    if (a.nchunks % 4 != 0) { a.bp_pairs = 0; return; }
187    const int nblk = a.nchunks / 2;
188    const __m128i shuf = _mm_setr_epi8(0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15);
189    const __m128i bias = _mm_set1_epi8((char) 0x80);
190    for (int b = 0; b < nblk; ++b) {
191        const int8_t* q = a.q + b * 64;
192        __m128i s[4];
193        for (int g = 0; g < 4; ++g) {
194            const __m128i v = _mm_loadu_si128((const __m128i*) (q + 16 * g));
195            s[g] = _mm_shuffle_epi8(v, shuf);
196            const __m128i sad = _mm_sad_epu8(_mm_xor_si128(v, bias), _mm_setzero_si128());
197            a.psum[(b >> 1) * 8 + (b & 1) * 4 + g] =
198                _mm_cvtsi128_si32(sad) + _mm_extract_epi16(sad, 4) - 16 * 128;
199        }
200        const __m128i t0 = _mm_unpacklo_epi32(s[0], s[1]), t1 = _mm_unpacklo_epi32(s[2], s[3]);
201        const __m128i t2 = _mm_unpackhi_epi32(s[0], s[1]), t3 = _mm_unpackhi_epi32(s[2], s[3]);
202        int8_t* dst = a.qp + (b >> 1) * 128 + (b & 1) * 16;
203        _mm_store_si128((__m128i*) (dst), _mm_unpacklo_epi64(t0, t1));
204        _mm_store_si128((__m128i*) (dst + 32), _mm_unpackhi_epi64(t0, t1));
205        _mm_store_si128((__m128i*) (dst + 64), _mm_unpacklo_epi64(t2, t3));
206        _mm_store_si128((__m128i*) (dst + 96), _mm_unpackhi_epi64(t2, t3));
207    }
208    for (int c = 0; c < a.nchunks; ++c) {
209        a.pscale[2 * c] = a.scale[c];
210        a.pscale[2 * c + 1] = a.scale[c];
211    }
212    a.bp_pairs = nblk / 2;
213}
214
215}  // namespace
216
217void q2_0_gguf_rows_multi_avx1_legacy(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
218                                      float* const* out, int r0, int r1) {
219    switch (nt) {
220        case 1: rows<1>(w, row_bytes, nblocks, a, out, r0, r1); break;
221        case 2: rows<2>(w, row_bytes, nblocks, a, out, r0, r1); break;
222        case 3: rows<3>(w, row_bytes, nblocks, a, out, r0, r1); break;
223        case 4: rows<4>(w, row_bytes, nblocks, a, out, r0, r1); break;
224        default:
225            for (int t0 = 0; t0 < nt; t0 += 4) {
226                const int k = nt - t0 < 4 ? nt - t0 : 4;
227                q2_0_gguf_rows_multi_avx1_legacy(w, row_bytes, nblocks, a + t0, k, out + t0, r0, r1);
228            }
229    }
230}
231
232void q2_0_gguf_rows_multi_avx1(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
233                               float* const* out, int r0, int r1) {
234    bool bp = kBitplane && nblocks % 2 == 0;
235    for (int t = 0; t < nt && bp; ++t) bp = a[t]->bp_pairs == nblocks / 2;
236    if (!bp) {
237        q2_0_gguf_rows_multi_avx1_legacy(w, row_bytes, nblocks, a, nt, out, r0, r1);
238        return;
239    }
240    const int np = nblocks / 2;
241    switch (nt) {
242        case 1: rows_bp<1>(w, row_bytes, np, a, out, r0, r1); break;
243        case 2: rows_bp<2>(w, row_bytes, np, a, out, r0, r1); break;
244        case 3: rows_bp<3>(w, row_bytes, np, a, out, r0, r1); break;
245        case 4: rows_bp<4>(w, row_bytes, np, a, out, r0, r1); break;
246        default:
247            for (int t0 = 0; t0 < nt; t0 += 4) {
248                const int k = nt - t0 < 4 ? nt - t0 : 4;
249                q2_0_gguf_rows_multi_avx1(w, row_bytes, nblocks, a + t0, k, out + t0, r0, r1);
250            }
251    }
252}
253
254void act_quant_q8_1_avx1(const float* x, int n, ActQ& a) {
255    a.nchunks = n / QKA;
256    const __m128 absmask = _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff));
257    const __m128 half = _mm_set1_ps(0.5f), mhalf = _mm_set1_ps(-0.5f), zero = _mm_setzero_ps();
258    const __m128i lo = _mm_set1_epi32(-127), hi = _mm_set1_epi32(127);
259    for (int k = 0; k < a.nchunks; ++k) {
260        const float* xb = x + k * QKA;
261        __m128 v[8];
262        __m128 m = _mm_setzero_ps();
263        for (int i = 0; i < 8; ++i) {
264            v[i] = _mm_loadu_ps(xb + 4 * i);
265            m = _mm_max_ps(m, _mm_and_ps(v[i], absmask));
266        }
267        m = _mm_max_ps(m, _mm_movehl_ps(m, m));
268        const float amax = _mm_cvtss_f32(_mm_max_ss(m, _mm_movehdup_ps(m)));
269        const float s = amax > 0.f ? amax / 127.f : 0.f;
270        const float inv = s > 0.f ? 1.f / s : 0.f;
271        const __m128 vinv = _mm_set1_ps(inv);
272        __m128i sum = _mm_setzero_si128();
273        alignas(16) int32_t qi[QKA];
274        for (int i = 0; i < 8; ++i) {
275            const __m128 t = _mm_mul_ps(v[i], vinv);
276            const __m128 r = _mm_add_ps(t, _mm_blendv_ps(mhalf, half, _mm_cmp_ps(t, zero, _CMP_GE_OQ)));
277            __m128i q = _mm_cvttps_epi32(r);
278            q = _mm_min_epi32(_mm_max_epi32(q, lo), hi);
279            sum = _mm_add_epi32(sum, q);
280            _mm_store_si128((__m128i*) (qi + 4 * i), q);
281        }
282        for (int j = 0; j < QKA; ++j) a.q[k * QKA + j] = (int8_t) qi[j];
283        __m128i s4 = _mm_add_epi32(sum, _mm_shuffle_epi32(sum, 0x4E));
284        s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0xB1));
285        const int32_t total = _mm_cvtsi128_si32(s4);
286        a.scale[k] = s;
287        a.sum[k] = total;
288        a.hx[k] = s * (float) total;
289    }
290    if (kBitplane) bitplane_image(a);
291    else a.bp_pairs = 0;
292}
293
294}  // namespace strata::kernels::cpu