okami.mom/strata

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

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

main
35.5 KiB681 linesraw
1// src/kernels/cpu/expert.cpp - P2.S3: the Q2_0 expert kernel, promoted from bench/micro/cpu_s2.cpp.
2//
3// The body is the validated kernel, moved rather than rewritten: it carries the P0.T2 parity result
4// (rel 1.461e-06 against the ggml formula) and the three performance findings recorded in
5// include/strata/kernels/cpu/expert.hpp.  Read that header first; it says why each piece is shaped this way.
6#include "strata/kernels/cpu/expert.hpp"
7#include "strata/kernels/cpu/expert_layout.hpp"
8
9#include <immintrin.h>
10#if defined(_MSC_VER)
11#include <intrin.h>
12#else
13#include <cpuid.h>
14#endif
15
16#include <cmath>
17#include <atomic>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21
22namespace strata::kernels::cpu {
23namespace {
24
25/// fp16 -> fp32, written out rather than using `_cvtsh_ss`, because the F16C intrinsic's behaviour on
26/// subnormals is the one place the two can differ and the scales in this artifact are small.
27inline float h2f(const uint8_t* p) {
28    uint16_t h;
29    std::memcpy(&h, p, 2);
30    const uint32_t sign = (uint32_t) (h >> 15) & 1u;
31    uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f;
32    if (exp == 0) {
33        if (man == 0) {
34            f = sign << 31;
35        } else {
36            exp = 127 - 15 + 1;
37            while (!(man & 0x400u)) { man <<= 1; --exp; }
38            man &= 0x3FFu;
39            f = (sign << 31) | (exp << 23) | (man << 13);
40        }
41    } else if (exp == 31) {
42        f = (sign << 31) | 0x7F800000u | (man << 13);
43    } else {
44        f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13);
45    }
46    float out;
47    std::memcpy(&out, &f, 4);
48    return out;
49}
50
51// The x86 Q8_0 quantization and generic Q2_0 dot sequences are adapted from llama.cpp
52// 3cf03257f219afbe7334045ff7c6a06ac68c627d,
53// ggml/src/ggml-cpu/arch/x86/quants.c: quantize_row_q8_0 and
54// ggml/src/ggml-cpu/quants.c: ggml_vec_dot_q2_0_q8_0_generic.
55//
56// MIT License
57// Copyright (c) 2023-2026 The ggml authors
58//
59// Permission is hereby granted, free of charge, to any person obtaining a copy
60// of this software and associated documentation files (the "Software"), to deal
61// in the Software without restriction, including without limitation the rights
62// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
63// copies of the Software, and to permit persons to whom the Software is
64// furnished to do so, subject to the following conditions:
65//
66// The above copyright notice and this permission notice shall be included in all
67// copies or substantial portions of the Software.
68//
69// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
70// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
71// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
72// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
73// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
74// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
75// SOFTWARE.
76void quantize_oracle_q8_0(const float* x, int n, ActQ& a) {
77    a.nchunks = n / QKA;
78    for (int chunk = 0; chunk < a.nchunks; ++chunk) {
79        const float* xb = x + chunk * QKA;
80        __m256 v0 = _mm256_loadu_ps(xb);
81        __m256 v1 = _mm256_loadu_ps(xb + 8);
82        __m256 v2 = _mm256_loadu_ps(xb + 16);
83        __m256 v3 = _mm256_loadu_ps(xb + 24);
84        const __m256 sign = _mm256_set1_ps(-0.0f);
85        __m256 maximum = _mm256_andnot_ps(sign, v0);
86        maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v1));
87        maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v2));
88        maximum = _mm256_max_ps(maximum, _mm256_andnot_ps(sign, v3));
89        __m128 max4 = _mm_max_ps(_mm256_extractf128_ps(maximum, 1), _mm256_castps256_ps128(maximum));
90        max4 = _mm_max_ps(max4, _mm_movehl_ps(max4, max4));
91        max4 = _mm_max_ss(max4, _mm_movehdup_ps(max4));
92        const float amax = _mm_cvtss_f32(max4);
93        const float d = amax / 127.0f;
94        const uint16_t half_d = (uint16_t) _mm_cvtsi128_si32(_mm_cvtps_ph(_mm_set_ss(d), 0));
95        const __m256 inverse = _mm256_set1_ps(amax != 0.0f ? 127.0f / amax : 0.0f);
96        v0 = _mm256_round_ps(_mm256_mul_ps(v0, inverse), _MM_FROUND_TO_NEAREST_INT);
97        v1 = _mm256_round_ps(_mm256_mul_ps(v1, inverse), _MM_FROUND_TO_NEAREST_INT);
98        v2 = _mm256_round_ps(_mm256_mul_ps(v2, inverse), _MM_FROUND_TO_NEAREST_INT);
99        v3 = _mm256_round_ps(_mm256_mul_ps(v3, inverse), _MM_FROUND_TO_NEAREST_INT);
100        __m256i i0 = _mm256_packs_epi32(_mm256_cvtps_epi32(v0), _mm256_cvtps_epi32(v1));
101        const __m256i i2 = _mm256_packs_epi32(_mm256_cvtps_epi32(v2), _mm256_cvtps_epi32(v3));
102        i0 = _mm256_packs_epi16(i0, i2);
103        i0 = _mm256_permutevar8x32_epi32(i0, _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7));
104        int8_t* q = a.q + chunk * QKA;
105        _mm256_storeu_si256((__m256i*) q, i0);
106        int32_t sum = 0;
107        for (int j = 0; j < QKA; ++j) sum += q[j];
108        a.scale[chunk] = h2f((const uint8_t*) &half_d);
109        a.sum[chunk] = sum;
110        a.hx[chunk] = a.scale[chunk] * float(sum);
111    }
112}
113
114/// 2-bit unpack via VPMULTISHIFTQB.
115///
116/// ARGUMENT ORDER IS (control, data) AND WAS DETERMINED EMPIRICALLY (`bench/micro/probe_multishift.cpp`).
117/// The Intel guide states (a=data, b=control); using that produced 43 of 64 wrong codes.  `plan.md`'s sketch
118/// passes the shift pattern first, which is correct - so a "fix" that swapped it to match the guide was the
119/// bug, not the fix.  Within each 64-bit lane, output byte i is `(u16 >> 2i) & 0xFF`, so AND 3 yields the
120/// eight 2-bit codes in order.
121///
122/// The result is the 32 codes of ONE ACTIVATION CHUNK (4 qword lanes), which is the unit the Q8_1 scale is
123/// defined on - not the 64-weight block.
124inline __m256i unpack_q2_0(const uint8_t* codes) {
125    const __m128i packed = _mm_loadl_epi64((const __m128i*) codes);   // 8 bytes -> 4 u16 in the low half
126    const __m256i lanes = _mm256_cvtepu16_epi64(packed);              // 4 qwords, 8 codes each
127    const __m256i ctrl = _mm256_set1_epi64x((long long) 0x0E0C0A0806040200ULL);
128    return _mm256_and_si256(_mm256_multishift_epi64_epi8(ctrl, lanes), _mm256_set1_epi8(3));
129}
130
131/// 32 codes against 32 int8 activations. Codes 0 contribute nothing to `sum(c*xhat)`, so the zero lanes the
132/// narrow load leaves behind are harmless.
133inline __m256i block_dot(const uint8_t* codes, const int8_t* xq) {
134    return _mm256_dpbusd_epi32(_mm256_setzero_si256(), unpack_q2_0(codes),
135                               _mm256_load_si256((const __m256i*) xq));
136}
137
138inline float hsum_ps(__m256 v) {
139    const __m128 s = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
140    return _mm_cvtss_f32(_mm_hadd_ps(_mm_hadd_ps(s, s), s));
141}
142
143// ================================ plan v0.3 P6: the row dot in 512-bit lanes ================================
144//
145// The 256-bit row dot below spent ~12 cycles per 64-weight block: two unpacks, two VNNI dots, two converts, two
146// scalar scale products broadcast into two FMAs, an fp16 conversion and a scalar correction - compute-bound at
147// ~39 GB/s while the machine streams 52.  Here a block is ONE unpack (16 code bytes -> 64 codes), ONE VNNI dot
148// over 64 activations, ONE convert and ONE FMA whose per-chunk scales come from a permute of a vector of scale
149// products built for eight blocks at a time; the weight-independent correction is one FMA per eight blocks.
150// The sum order differs from the 256-bit kernel (last-bit differences); the verify window and plain decode both
151// use this kernel, so speculative decode still reproduces plain decode exactly.
152static const bool kZmm = std::getenv("STRATA_CPU_YMM") == nullptr;
153
154inline __m512i unpack64_q2_0_ms(const uint8_t* codes) {
155    const __m128i packed = _mm_loadu_si128((const __m128i*) codes);          // 8 u16 = 64 codes
156    const __m512i lanes = _mm512_cvtepu16_epi64(packed);                    // 8 qwords, 8 codes each
157    const __m512i ctrl = _mm512_set1_epi64((long long) 0x0E0C0A0806040200ULL);
158    return _mm512_and_si512(_mm512_multishift_epi64_epi8(ctrl, lanes), _mm512_set1_epi8(3));
159}
160
161/// 2-bit unpack WITHOUT VPMULTISHIFTQB (the one VBMI op): byte for byte the multishift's result - output byte j
162/// (code j) is (u16[j/8] >> 2*(j%8)) & 3 - for a CPU with AVX-512 VNNI (dpbusd) but no VBMI (Cascade Lake Xeon;
163/// these used to fall back to the whole AVX-2 kernel).  Four vectors of 16 codes (the u16 pairs 2R and 2R+1), each
164/// a VPERMW source-select + VPSRLVD bit-position shift + mask, truncated to bytes and concatenated in order.  ~8
165/// more instructions per 64 codes: a part of the block's work.
166template <int R>
167inline __m128i unpack_round(const __m512i words, const __m512i shift, const __m512i three) {
168    const __m256i src = _mm256_permutexvar_epi16(                        // code j/8's u16 for j = 16R..16R+15
169        _mm256_setr_epi16((int16_t) (2 * R), (int16_t) (2 * R), (int16_t) (2 * R), (int16_t) (2 * R),
170                          (int16_t) (2 * R), (int16_t) (2 * R), (int16_t) (2 * R), (int16_t) (2 * R),
171                          (int16_t) (2 * R + 1), (int16_t) (2 * R + 1), (int16_t) (2 * R + 1),
172                          (int16_t) (2 * R + 1), (int16_t) (2 * R + 1), (int16_t) (2 * R + 1),
173                          (int16_t) (2 * R + 1), (int16_t) (2 * R + 1)),
174        _mm512_castsi512_si256(words));                                  // the 16 source words
175    const __m512i codes_d = _mm512_and_si512(                            // 16 codes, shifted their bit
176        _mm512_srlv_epi32(_mm512_cvtepu16_epi32(src), shift), _mm512_set1_epi8(3));
177    return _mm512_cvtepi32_epi8(codes_d);                                // 16 dwords -> 16 bytes (VL truncate)
178}
179
180inline __m512i unpack64_q2_0_sw(const uint8_t* codes) {
181    const __m512i words = _mm512_inserti32x4(_mm512_setzero_si512(),      // 8 u16, the rest zero
182                                            _mm_loadu_si128((const __m128i*) codes), 0);
183    const __m512i shift = _mm512_setr_epi32(0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14);
184    const __m512i three = _mm512_set1_epi8(3);
185    return _mm512_inserti32x4(
186        _mm512_inserti32x4(_mm512_inserti32x4(_mm512_inserti32x4(_mm512_setzero_si512(),
187                                                                 unpack_round<0>(words, shift, three), 0),
188                                              unpack_round<1>(words, shift, three), 1),
189                           unpack_round<2>(words, shift, three), 2),
190        unpack_round<3>(words, shift, three), 3);
191}
192
193inline __m512i unpack64_q2_0(const uint8_t* codes) {
194    static const bool vbmi = cpu_vbmi_ok();          // VPMULTISHIFTQB, or the substitute (bit-shifting) one here
195    return vbmi ? unpack64_q2_0_ms(codes) : unpack64_q2_0_sw(codes);
196}
197
198/// STRATA_CPU_YMM=1 keeps the 256-bit rows (whose unpack keeps the multishift): a machine with VNNI but no VBMI
199/// takes the zmm rows (the substitute unpack above), and anything older takes the AVX-2 kernel (expert_layout.cpp's
200/// dispatch).  So one value answers "can this engine's 512-bit q2 path run at all".
201// For blocks [b0, b0+nb) (nb <= 8): p[2i+h] = d_{b0+i} * xscale[2(b0+i)+h], dd[2i+h] = d_{b0+i}.
202inline void scales8(const uint8_t* wscales, const ActQ& a, int b0, int nb, __m512& p, __m512& dd) {
203    const __mmask8 m8 = nb >= 8 ? (__mmask8) 0xFF : (__mmask8) ((1u << nb) - 1u);
204    const __m128i h = _mm_maskz_loadu_epi16(m8, wscales + 2 * b0);
205    const __m512 d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(h));
206    const __m512i dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7);
207    dd = _mm512_permutexvar_ps(dup, d8);
208    const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u);
209    dd = _mm512_maskz_mov_ps(m16, dd);
210    p = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(m16, a.scale + 2 * b0));
211}
212
213inline float row_dot_z(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) {
214    __m512 acc = _mm512_setzero_ps(), corr = _mm512_setzero_ps();
215    const __m512i base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
216    for (int b0 = 0; b0 < nblocks; b0 += 8) {
217        const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8;
218        __m512 p, dd;
219        scales8(scales, a, b0, nb, p, dd);
220        const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u);
221        corr = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a.hx + 2 * b0), corr);
222        for (int i = 0; i < nb; ++i) {
223            const int b = b0 + i;
224            const __m512i dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), unpack64_q2_0(codes + b * 16),
225                                                    _mm512_load_si512((const void*) (a.q + b * QK)));
226            const __m512 sv = _mm512_permutexvar_ps(_mm512_add_epi32(base, _mm512_set1_epi32(2 * i)), p);
227            acc = _mm512_fmadd_ps(sv, _mm512_cvtepi32_ps(dot), acc);
228        }
229    }
230    return _mm512_reduce_add_ps(acc) - _mm512_reduce_add_ps(corr);
231}
232
233template<int NT>
234inline void row_dot_multi_z(const uint8_t* codes, const uint8_t* scales, const ActQ* const* a, int nblocks,
235                            float* res) {
236    __m512 acc[NT], corr[NT];
237    for (int t = 0; t < NT; ++t) { acc[t] = _mm512_setzero_ps(); corr[t] = _mm512_setzero_ps(); }
238    const __m512i base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
239    for (int b0 = 0; b0 < nblocks; b0 += 8) {
240        const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8;
241        const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u);
242        __m512 p[NT];
243        for (int t = 0; t < NT; ++t) {
244            __m512 dd;
245            scales8(scales, *a[t], b0, nb, p[t], dd);
246            corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a[t]->hx + 2 * b0), corr[t]);
247        }
248        for (int i = 0; i < nb; ++i) {
249            const int b = b0 + i;
250            const __m512i w = unpack64_q2_0(codes + b * 16);
251            const __m512i idx = _mm512_add_epi32(base, _mm512_set1_epi32(2 * i));
252            for (int t = 0; t < NT; ++t) {
253                const __m512i dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), w,
254                                                        _mm512_load_si512((const void*) (a[t]->q + b * QK)));
255                acc[t] = _mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p[t]), _mm512_cvtepi32_ps(dot), acc[t]);
256            }
257        }
258    }
259    for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]);
260}
261
262/// One weight row against a quantized activation.
263///
264///     sum_j (c_j - 1) d_w xhat_j d_x  ==  d_w * ( d_x*sum(c*xhat) - d_x*sum(xhat) )
265///
266/// split per 32-chunk because `d_x` changes at the chunk boundary while `d_w` does not.
267///
268/// The accumulator stays a FLOAT VECTOR for the whole row and is reduced once at the end.  Reducing per
269/// 64-weight block (two 8-lane horizontal sums: a store plus 16 scalar adds) cost far more than the dot
270/// products themselves - it made the kernel compute-bound at 21 GB/s instead of DRAM-bound at 32.
271inline float row_dot(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) {
272    if (kZmm) return row_dot_z(codes, scales, a, nblocks);
273    __m256 acc = _mm256_setzero_ps();
274    // The -sum(xhat) term is a SCALAR: broadcasting it into all 8 lanes and letting hsum_ps add them would
275    // apply it eight times per block.
276    float corr = 0.f;
277    for (int b = 0; b < nblocks; ++b) {
278        const float d = h2f(scales + 2 * b);
279        const __m256 slo = _mm256_cvtepi32_ps(block_dot(codes + b * 16, a.q + b * QK));
280        const __m256 shi = _mm256_cvtepi32_ps(block_dot(codes + b * 16 + 8, a.q + b * QK + QKA));
281        acc = _mm256_fmadd_ps(_mm256_set1_ps(d * a.scale[2 * b]), slo, acc);
282        acc = _mm256_fmadd_ps(_mm256_set1_ps(d * a.scale[2 * b + 1]), shi, acc);
283        corr += d * (a.hx[2 * b] + a.hx[2 * b + 1]);
284    }
285    return hsum_ps(acc) - corr;
286}
287
288// VNNI's integer partial sums are exact. Remove the Q2_0 code offset BEFORE
289// conversion to float, then follow the pinned generic CPU dot's two-chunk and
290// per-64-block reduction. Its x86 type trait selects this generic reduction even
291// in the AVX-512 oracle build. The legacy eight-lane FP32 reduction above has a
292// different rounding order and remains the default.
293inline int chunk_dot_oracle(const uint8_t* codes, const int8_t* q, int sum) {
294    const __m256i lanes = block_dot(codes, q);
295    const __m128i halves = _mm_add_epi32(_mm256_castsi256_si128(lanes), _mm256_extracti128_si256(lanes, 1));
296    const __m128i pairs = _mm_hadd_epi32(halves, halves);
297    return _mm_cvtsi128_si32(_mm_hadd_epi32(pairs, pairs)) - sum;
298}
299
300inline float row_dot_oracle(const uint8_t* codes, const uint8_t* scales, const ActQ& a, int nblocks) {
301    float result = 0.0f;
302    for (int b = 0; b < nblocks; ++b) {
303        float block = 0.0f;
304        for (int half = 0; half < 2; ++half) {
305            const int chunk = 2 * b + half;
306            const int dot = chunk_dot_oracle(codes + b * 16 + half * 8, a.q + chunk * QKA, a.sum[chunk]);
307            block += a.scale[chunk] * float(dot);
308        }
309        result += h2f(scales + 2 * b) * block;
310    }
311    return result;
312}
313
314/// `row_dot` for NT activations at once: the codes of each block are unpacked once, and each token's
315/// accumulator sees exactly the operations `row_dot` would apply to it, in the same order.
316template<int NT>
317inline void row_dot_multi(const uint8_t* codes, const uint8_t* scales, const ActQ* const* a, int nblocks,
318                          float* res) {
319    if (kZmm) { row_dot_multi_z<NT>(codes, scales, a, nblocks, res); return; }
320    __m256 acc[NT];
321    float corr[NT];
322    for (int t = 0; t < NT; ++t) { acc[t] = _mm256_setzero_ps(); corr[t] = 0.f; }
323    for (int b = 0; b < nblocks; ++b) {
324        const float d = h2f(scales + 2 * b);
325        const __m256i lo = unpack_q2_0(codes + b * 16);
326        const __m256i hi = unpack_q2_0(codes + b * 16 + 8);
327        for (int t = 0; t < NT; ++t) {
328            const __m256 slo = _mm256_cvtepi32_ps(
329                _mm256_dpbusd_epi32(_mm256_setzero_si256(), lo, _mm256_load_si256((const __m256i*) (a[t]->q + b * QK))));
330            const __m256 shi = _mm256_cvtepi32_ps(
331                _mm256_dpbusd_epi32(_mm256_setzero_si256(), hi,
332                                    _mm256_load_si256((const __m256i*) (a[t]->q + b * QK + QKA))));
333            acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b]), slo, acc[t]);
334            acc[t] = _mm256_fmadd_ps(_mm256_set1_ps(d * a[t]->scale[2 * b + 1]), shi, acc[t]);
335            corr[t] += d * (a[t]->hx[2 * b] + a[t]->hx[2 * b + 1]);
336        }
337    }
338    for (int t = 0; t < NT; ++t) res[t] = hsum_ps(acc[t]) - corr[t];
339}
340
341template<int NT>
342void expert_multi(const uint8_t* blob, const ActQ* const* a1, float* const* out, ExpertScratchMulti& ws) {
343    float g[NT], u[NT];
344    for (int r = 0; r < FF; ++r) {
345        row_dot_multi<NT>(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU,
346                          blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU, g);
347        row_dot_multi<NT>(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU,
348                          blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU, u);
349        for (int t = 0; t < NT; ++t) ws.ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t];
350    }
351    const ActQ* a2[NT];
352    for (int t = 0; t < NT; ++t) {
353        act_quant_q8_1(ws.ff[t], FF, ws.a2[t]);
354        a2[t] = &ws.a2[t];
355    }
356    float o[NT];
357    for (int r = 0; r < H; ++r) {
358        row_dot_multi<NT>(blob + O_D_CODES + (size_t) r * ROW_D, blob + O_D_SCALES + (size_t) r * SC_D * 2, a2,
359                          SC_D, o);
360        for (int t = 0; t < NT; ++t) out[t][r] = o[t];
361    }
362}
363
364void expert_oracle_q8_0(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws) {
365    for (int r = 0; r < FF; ++r) {
366        const float g = row_dot_oracle(blob + O_GU_CODES + size_t(2 * r) * ROW_GU,
367                                      blob + O_GU_SCALES + size_t(2 * r) * SC_GU * 2, a1, SC_GU);
368        const float u = row_dot_oracle(blob + O_GU_CODES + size_t(2 * r + 1) * ROW_GU,
369                                      blob + O_GU_SCALES + size_t(2 * r + 1) * SC_GU * 2, a1, SC_GU);
370        ws.ff[r] = (g / (1.f + std::exp(-g))) * u;
371    }
372    quantize_oracle_q8_0(ws.ff, FF, ws.a2);
373    for (int r = 0; r < H; ++r)
374        out[r] = row_dot_oracle(blob + O_D_CODES + size_t(r) * ROW_D,
375                               blob + O_D_SCALES + size_t(r) * SC_D * 2, ws.a2, SC_D);
376}
377
378bool q2_rows_512_ok() {
379    return kZmm && cpu_vnni_ok();
380}
381}  // namespace
382
383// CpuFeatures::reason, cpu_features, cpu_require_expert_support and the oracle flag live in expert_layout.cpp: this
384// file is compiled for AVX-512, and the code that finds out whether the CPU has AVX-512 must not be in it (#795).
385void act_quant_q8_1(const float* x, int n, ActQ& a) {
386    if (expert_oracle_q8_0_enabled()) {
387        quantize_oracle_q8_0(x, n, a);
388        return;
389    }
390    a.nchunks = n / QKA;
391    // Plan v0.3 P6: AVX-512, the same operations per element as the scalar loop below (max of |x|, one multiply,
392    // +-0.5 away from zero, truncation, clamp), so the result is bitwise the scalar one.  The scalar loop took
393    // ~22 us per 2560 values - 3.2 ms of every speculative round.
394    {
395        const __m512 half = _mm512_set1_ps(0.5f), mhalf = _mm512_set1_ps(-0.5f), zero = _mm512_setzero_ps();
396        const __m512i lo = _mm512_set1_epi32(-127), hi = _mm512_set1_epi32(127);
397        const __m512 absmask = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
398        for (int k = 0; k < a.nchunks; ++k) {
399            const float* xb = x + k * QKA;
400            const __m512 x0 = _mm512_loadu_ps(xb), x1 = _mm512_loadu_ps(xb + 16);
401            const float amax = _mm512_reduce_max_ps(_mm512_max_ps(_mm512_and_ps(x0, absmask), _mm512_and_ps(x1, absmask)));
402            const float s = amax > 0.f ? amax / 127.f : 0.f;
403            const float inv = s > 0.f ? 1.f / s : 0.f;
404            const __m512 vinv = _mm512_set1_ps(inv);
405            const __m512 t0 = _mm512_mul_ps(x0, vinv), t1 = _mm512_mul_ps(x1, vinv);
406            const __m512 r0 = _mm512_add_ps(t0, _mm512_mask_blend_ps(_mm512_cmp_ps_mask(t0, zero, _CMP_GE_OQ), mhalf, half));
407            const __m512 r1 = _mm512_add_ps(t1, _mm512_mask_blend_ps(_mm512_cmp_ps_mask(t1, zero, _CMP_GE_OQ), mhalf, half));
408            __m512i v0 = _mm512_cvttps_epi32(r0), v1 = _mm512_cvttps_epi32(r1);
409            v0 = _mm512_min_epi32(_mm512_max_epi32(v0, lo), hi);
410            v1 = _mm512_min_epi32(_mm512_max_epi32(v1, lo), hi);
411            _mm_storeu_si128((__m128i*) (a.q + k * QKA), _mm512_cvtepi32_epi8(v0));
412            _mm_storeu_si128((__m128i*) (a.q + k * QKA + 16), _mm512_cvtepi32_epi8(v1));
413            const int32_t sum = _mm512_reduce_add_epi32(_mm512_add_epi32(v0, v1));
414            a.scale[k] = s;
415            a.sum[k] = sum;
416            a.hx[k] = s * (float) sum;
417        }
418        return;
419    }
420    for (int k = 0; k < a.nchunks; ++k) {
421        const float* xb = x + k * QKA;
422        float amax = 0.f;
423        for (int j = 0; j < QKA; ++j) amax = std::fmax(amax, std::fabs(xb[j]));
424        const float s = amax > 0.f ? amax / 127.f : 0.f;
425        const float inv = s > 0.f ? 1.f / s : 0.f;
426        int32_t sum = 0;
427        int8_t* q = a.q + k * QKA;
428        for (int j = 0; j < QKA; ++j) {
429            // **`std::lround` IS A FUNCTION CALL AND IT COST 51 us PER LAYER.**  Measured: quantizing 2560
430            // floats took 51.3 us - 20 ns per element, about 60 cycles for a fabs, a multiply and a round.
431            // `lround` respects the current rounding mode, so MSVC cannot inline it to a single instruction
432            // and emits a call per element.  48 layers x 51.3 us = 2.46 ms/token, which is 8.6% of the whole
433            // CPU expert term and is pure overhead.
434            //
435            // `t + copysign(0.5, t)` is EXACTLY `lround`'s rule - round half AWAY FROM ZERO - and it is
436            // branchless and vectorizable.  It is NOT `_mm256_round_ps`, which rounds half to EVEN and would
437            // quietly change the activation on the ties.  The cast is safe because `|t| <= 127` by construction
438            // (`s = amax/127`, so `|x_j|/s <= 127`), well inside int32.
439            const float t = xb[j] * inv;
440            const float r = t + (t >= 0.f ? 0.5f : -0.5f);
441            int v = (int) r;
442            v = v < -127 ? -127 : (v > 127 ? 127 : v);
443            q[j] = (int8_t) v;
444            sum += v;
445        }
446        a.scale[k] = s;
447        a.sum[k] = sum;
448        a.hx[k] = s * (float) sum;
449    }
450}
451
452void s2_expert_vnni(const uint8_t* blob, const float* x, float* out, ExpertScratch& ws) {
453    act_quant_q8_1(x, H, ws.a1);
454    s2_expert_vnni_q(blob, ws.a1, out, ws);
455}
456
457void s2_expert_vnni_q(const uint8_t* blob, const ActQ& a1, float* out, ExpertScratch& ws) {
458    if (expert_oracle_q8_0_enabled()) {
459        expert_oracle_q8_0(blob, a1, out, ws);
460        return;
461    }
462    for (int r = 0; r < FF; ++r) {
463        const float g = row_dot(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU,
464                                blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU);
465        const float u = row_dot(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU,
466                                blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU);
467        // SiLU on the GATE, multiplied by up - the same reading `docs/semantics.md` records for the shared
468        // expert, and the one that is wrong the other way round in a way that still produces a number.
469        ws.ff[r] = (g / (1.f + std::exp(-g))) * u;
470    }
471    act_quant_q8_1(ws.ff, FF, ws.a2);
472    for (int r = 0; r < H; ++r)
473        out[r] = row_dot(blob + O_D_CODES + (size_t) r * ROW_D,
474                         blob + O_D_SCALES + (size_t) r * SC_D * 2, ws.a2, SC_D);
475}
476
477
478void s2_expert_gu_rows(const uint8_t* blob, const ActQ& a1, float* ff, int r0, int r1) {
479    for (int r = r0; r < r1; ++r) {
480        const float g = row_dot(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU,
481                                blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU);
482        const float u = row_dot(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU,
483                                blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU);
484        ff[r] = (g / (1.f + std::exp(-g))) * u;
485    }
486}
487
488void s2_expert_down_rows(const uint8_t* blob, const ActQ& a2, float* out, int r0, int r1) {
489    for (int r = r0; r < r1; ++r)
490        out[r] = row_dot(blob + O_D_CODES + (size_t) r * ROW_D, blob + O_D_SCALES + (size_t) r * SC_D * 2, a2, SC_D);
491}
492
493namespace {
494template<int NT>
495void gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, float* const* ff, int r0, int r1) {
496    float g[NT], u[NT];
497    for (int r = r0; r < r1; ++r) {
498        row_dot_multi<NT>(blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU,
499                          blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2, a1, SC_GU, g);
500        row_dot_multi<NT>(blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU,
501                          blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2, a1, SC_GU, u);
502        for (int t = 0; t < NT; ++t) ff[t][r] = (g[t] / (1.f + std::exp(-g[t]))) * u[t];
503    }
504}
505template<int NT>
506void down_rows_multi(const uint8_t* blob, const ActQ* const* a2, float* const* out, int r0, int r1) {
507    float o[NT];
508    for (int r = r0; r < r1; ++r) {
509        row_dot_multi<NT>(blob + O_D_CODES + (size_t) r * ROW_D, blob + O_D_SCALES + (size_t) r * SC_D * 2, a2,
510                          SC_D, o);
511        for (int t = 0; t < NT; ++t) out[t][r] = o[t];
512    }
513}
514}  // namespace
515
516void s2_expert_gu_rows_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* ff, int r0,
517                             int r1) {
518    switch (n_tokens) {
519        case 1: gu_rows_multi<1>(blob, a1, ff, r0, r1); break;
520        case 2: gu_rows_multi<2>(blob, a1, ff, r0, r1); break;
521        case 3: gu_rows_multi<3>(blob, a1, ff, r0, r1); break;
522        case 4: gu_rows_multi<4>(blob, a1, ff, r0, r1); break;
523        case 5: gu_rows_multi<5>(blob, a1, ff, r0, r1); break;
524        case 6: gu_rows_multi<6>(blob, a1, ff, r0, r1); break;
525        case 7: gu_rows_multi<7>(blob, a1, ff, r0, r1); break;
526        default: gu_rows_multi<8>(blob, a1, ff, r0, r1); break;
527    }
528}
529
530void s2_expert_down_rows_multi(const uint8_t* blob, const ActQ* const* a2, int n_tokens, float* const* out, int r0,
531                               int r1) {
532    switch (n_tokens) {
533        case 1: down_rows_multi<1>(blob, a2, out, r0, r1); break;
534        case 2: down_rows_multi<2>(blob, a2, out, r0, r1); break;
535        case 3: down_rows_multi<3>(blob, a2, out, r0, r1); break;
536        case 4: down_rows_multi<4>(blob, a2, out, r0, r1); break;
537        case 5: down_rows_multi<5>(blob, a2, out, r0, r1); break;
538        case 6: down_rows_multi<6>(blob, a2, out, r0, r1); break;
539        case 7: down_rows_multi<7>(blob, a2, out, r0, r1); break;
540        default: down_rows_multi<8>(blob, a2, out, r0, r1); break;
541    }
542}
543
544// ================================ plan v0.3 P6: Q2_0 rows in the GGUF block layout ================================
545//
546// The IQ model files keep their down projections in Q2_0 GGUF blocks (fp16 d, then 16 code bytes: 18 bytes per
547// 64 weights, interleaved), which ggml-cpu computes with a scalar loop on x86.  This is `row_dot_multi_z` with
548// the block stride of the GGUF layout: the same unpack, the same VNNI dot, the same correction.
549namespace {
550template<int NT>
551inline void q2g_row_multi(const uint8_t* row, const ActQ* const* a, int nblocks, float* res) {
552    __m512 acc[NT], corr[NT];
553    for (int t = 0; t < NT; ++t) { acc[t] = _mm512_setzero_ps(); corr[t] = _mm512_setzero_ps(); }
554    const __m512i base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
555    const __m512i dup = _mm512_setr_epi32(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7);
556    for (int b0 = 0; b0 < nblocks; b0 += 8) {
557        const int nb = nblocks - b0 < 8 ? nblocks - b0 : 8;
558        const __mmask16 m16 = nb >= 8 ? (__mmask16) 0xFFFF : (__mmask16) ((1u << (2 * nb)) - 1u);
559        alignas(16) uint16_t sc[8] = {0, 0, 0, 0, 0, 0, 0, 0};
560        for (int i = 0; i < nb; ++i) std::memcpy(&sc[i], row + (size_t) (b0 + i) * 18, 2);
561        const __m512 d8 = _mm512_castps256_ps512(_mm256_cvtph_ps(_mm_load_si128((const __m128i*) sc)));
562        const __m512 dd = _mm512_maskz_mov_ps(m16, _mm512_permutexvar_ps(dup, d8));
563        __m512 p[NT];
564        for (int t = 0; t < NT; ++t) {
565            p[t] = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(m16, a[t]->scale + 2 * b0));
566            corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a[t]->hx + 2 * b0), corr[t]);
567        }
568        for (int i = 0; i < nb; ++i) {
569            const int b = b0 + i;
570            const __m512i w = unpack64_q2_0(row + (size_t) b * 18 + 2);
571            const __m512i idx = _mm512_add_epi32(base, _mm512_set1_epi32(2 * i));
572            for (int t = 0; t < NT; ++t) {
573                const __m512i dot = _mm512_dpbusd_epi32(_mm512_setzero_si512(), w,
574                                                        _mm512_load_si512((const void*) (a[t]->q + b * QK)));
575                acc[t] = _mm512_fmadd_ps(_mm512_permutexvar_ps(idx, p[t]), _mm512_cvtepi32_ps(dot), acc[t]);
576            }
577        }
578    }
579    for (int t = 0; t < NT; ++t) res[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]);
580}
581template<int NT>
582void q2g_rows(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, float* const* out, int r0, int r1) {
583    float res[NT];
584    for (int r = r0; r < r1; ++r) {
585        q2g_row_multi<NT>(w + (size_t) r * row_bytes, a, nblocks, res);
586        for (int t = 0; t < NT; ++t) out[t][r] = res[t];
587    }
588}
589}  // namespace
590
591void q2_0_gguf_rows_multi(const uint8_t* w, size_t row_bytes, int nblocks, const ActQ* const* a, int nt,
592                          float* const* out, int r0, int r1) {
593    switch (nt) {
594        case 1: q2g_rows<1>(w, row_bytes, nblocks, a, out, r0, r1); break;
595        case 2: q2g_rows<2>(w, row_bytes, nblocks, a, out, r0, r1); break;
596        case 3: q2g_rows<3>(w, row_bytes, nblocks, a, out, r0, r1); break;
597        case 4: q2g_rows<4>(w, row_bytes, nblocks, a, out, r0, r1); break;
598        case 5: q2g_rows<5>(w, row_bytes, nblocks, a, out, r0, r1); break;
599        case 6: q2g_rows<6>(w, row_bytes, nblocks, a, out, r0, r1); break;
600        case 7: q2g_rows<7>(w, row_bytes, nblocks, a, out, r0, r1); break;
601        default: q2g_rows<8>(w, row_bytes, nblocks, a, out, r0, r1); break;
602    }
603}
604
605void s2_expert_vnni_multi(const uint8_t* blob, const ActQ* const* a1, int n_tokens, float* const* out,
606                          ExpertScratchMulti& ws) {
607    if (expert_oracle_q8_0_enabled() || n_tokens < 1 || n_tokens > MAXT) {
608        for (int t = 0; t < n_tokens; ++t) s2_expert_vnni_q(blob, *a1[t], out[t], ws.single);
609        return;
610    }
611    switch (n_tokens) {
612        case 1: expert_multi<1>(blob, a1, out, ws); break;
613        case 2: expert_multi<2>(blob, a1, out, ws); break;
614        case 3: expert_multi<3>(blob, a1, out, ws); break;
615        case 4: expert_multi<4>(blob, a1, out, ws); break;
616        case 5: expert_multi<5>(blob, a1, out, ws); break;
617        case 6: expert_multi<6>(blob, a1, out, ws); break;
618        case 7: expert_multi<7>(blob, a1, out, ws); break;
619        default: expert_multi<8>(blob, a1, out, ws); break;
620    }
621}
622
623void s2_expert_scalar(const uint8_t* blob, const float* x_in, float* out, bool quant_acts) {
624    // BOTH STAGES, which is what `quant_acts` promises and what `bench/micro/cpu_s2.cpp` does NOT do.
625    //
626    // The original's comment says the oracle "consume[s] the SAME INT8 activation values the VNNI path uses,
627    // at both stages", but its code quantizes only the INTERMEDIATE - the gate/up projections still see raw
628    // f32 `x`.  Feeding it an already-quantized input (which is what the engine does) makes the two coincide
629    // and hides the discrepancy entirely; feeding it a raw f32 input makes the comparison one between two
630    // DIFFERENT computations, and the gap measured here was 1.19e-02 - three times P2.S3's tolerance, and
631    // read as a kernel bug when it was a fixture bug.
632    float xq[H];
633    const float* x = x_in;
634    if (quant_acts) {
635        ActQ a1;
636        act_quant_q8_1(x_in, H, a1);
637        for (int i = 0; i < H; ++i) xq[i] = a1.scale[i / QKA] * (float) a1.q[i];
638        x = xq;
639    }
640    float ff[FF];
641    for (int r = 0; r < FF; ++r) {
642        const uint8_t* gc = blob + O_GU_CODES + (size_t) (2 * r) * ROW_GU;
643        const uint8_t* gs = blob + O_GU_SCALES + (size_t) (2 * r) * SC_GU * 2;
644        const uint8_t* uc = blob + O_GU_CODES + (size_t) (2 * r + 1) * ROW_GU;
645        const uint8_t* us = blob + O_GU_SCALES + (size_t) (2 * r + 1) * SC_GU * 2;
646        float sg = 0.f, su = 0.f;
647        for (int b = 0; b < SC_GU; ++b) {
648            const float dg = h2f(gs + 2 * b), du = h2f(us + 2 * b);
649            for (int j = 0; j < QK; ++j) {
650                const int o = b * QK + j;
651                sg += (float) (((gc[b * 16 + (j >> 2)] >> (2 * (j & 3))) & 3) - 1) * dg * x[o];
652                su += (float) (((uc[b * 16 + (j >> 2)] >> (2 * (j & 3))) & 3) - 1) * du * x[o];
653            }
654        }
655        ff[r] = (sg / (1.f + std::exp(-sg))) * su;
656    }
657    if (quant_acts) {
658        // Replace the exact intermediate with the INT8 values the VNNI path actually sees, so the two differ
659        // only by FP32 evaluation order.
660        ActQ a2;
661        act_quant_q8_1(ff, FF, a2);
662        for (int i = 0; i < FF; ++i) ff[i] = a2.scale[i / QKA] * (float) a2.q[i];
663    }
664    for (int r = 0; r < H; ++r) {
665        const uint8_t* dc = blob + O_D_CODES + (size_t) r * ROW_D;
666        const uint8_t* ds = blob + O_D_SCALES + (size_t) r * SC_D * 2;
667        float acc = 0.f;
668        for (int b = 0; b < SC_D; ++b) {
669            const float d = h2f(ds + 2 * b);
670            for (int j = 0; j < QK; ++j)
671                acc += (float) (((dc[b * 16 + (j >> 2)] >> (2 * (j & 3))) & 3) - 1) * d * ff[b * QK + j];
672        }
673        out[r] = acc;
674    }
675}
676
677bool q2_rows_512_ok() {
678    return kZmm && cpu_vnni_ok();
679}
680
681}  // namespace strata::kernels::cpu