okami.mom/strata

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

waveringanaRestore the DeepSeek V4.1 engine and CPU tests removed upstream8ac8ce32e

main
16.3 KiB418 linesraw
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3// src/ds4/ds4_gguf_cpu.cpp - a GGUF's MXFP4 experts on the CPU lane (see ds4_gguf_cpu.hpp).
4#include "ds4_gguf_cpu.hpp"
5
6#include "strata/dsv41/exl3_cpu.hpp"
7
8#include <algorithm>
9#include <chrono>
10#include <cmath>
11#include <cstdio>
12#include <cstdlib>
13#include <cstring>
14#include <string>
15#include <vector>
16
17#if defined(__x86_64__) || defined(_M_X64)
18#define MX_X86 1
19#include <immintrin.h>
20#if defined(_MSC_VER)
21#include <intrin.h>
22#else
23#include <cpuid.h>
24#endif
25#endif
26
27// a function's instruction set (GCC / Clang, clang-cl too; MSVC compiles any intrinsic as it is): the file is built for
28// the baseline x86-64, and each tier's code runs only where detect() says the CPU and the OS take it
29#if defined(MX_X86) && (defined(__GNUC__) || defined(__clang__))
30#define MX_TARGET(s) __attribute__((target(s)))
31#else
32#define MX_TARGET(s)
33#endif
34#define MX_AVX2 MX_TARGET("avx2,fma")
35// AVX-VNNI's intrinsics: GCC 11, Clang 12, MSVC 2022
36#if defined(MX_X86) && (defined(_MSC_VER) || (defined(__clang__) && __clang_major__ >= 12) || \
37                        (!defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 11))
38#define MX_AVXVNNI 1
39#endif
40
41namespace strata::ds4::gguf {
42namespace {
43
44constexpr int kBlock = 32, kBytes = 17;
45constexpr float kValues[16] = {0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 6.0f, 8.0f, 12.0f,
46                               0.0f, -1.0f, -2.0f, -3.0f, -4.0f, -6.0f, -8.0f, -12.0f};
47constexpr int kCodes[16] = {0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12};
48
49float e8m0_half(uint32_t e) {   // 2^(e - 128), as the device's
50    const uint32_t bits = e < 2 ? 0x00200000u << e : (e - 1) << 23;
51    float f;
52    std::memcpy(&f, &bits, 4);
53    return f;
54}
55struct E8m0Table {
56    float v[256];
57    E8m0Table() {
58        for (int e = 0; e < 256; ++e) v[e] = e8m0_half((uint32_t) e);
59    }
60};
61const E8m0Table& e8() {
62    static const E8m0Table t;
63    return t;
64}
65
66void rows_scalar(const uint8_t* w, size_t rb, int k, int r0, int r1, const float* const* x, int n, float* const* y) {
67    for (int r = r0; r < r1; ++r) {
68        const uint8_t* p = w + (size_t) r * rb;
69        float acc[kMxCpuMaxN] = {};
70        for (int b = 0; b < k / kBlock; ++b, p += kBytes) {
71            const float d = e8m0_half(p[0]);
72            float wv[kBlock];
73            for (int j = 0; j < 16; ++j) {
74                wv[j] = kValues[p[1 + j] & 15] * d;
75                wv[j + 16] = kValues[p[1 + j] >> 4] * d;
76            }
77            for (int i = 0; i < n; ++i) {
78                const float* xb = x[i] + b * kBlock;
79                float s = 0.0f;
80                for (int j = 0; j < kBlock; ++j) s += wv[j] * xb[j];
81                acc[i] += s;
82            }
83        }
84        for (int i = 0; i < n; ++i) y[i][r - r0] = acc[i];
85    }
86}
87
88#if defined(MX_X86)
89MX_AVX2 float hsum(__m256 v) {
90    const __m128 a = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
91    const __m128 b = _mm_add_ps(a, _mm_movehl_ps(a, a));
92    return _mm_cvtss_f32(_mm_add_ss(b, _mm_shuffle_ps(b, b, 1)));
93}
94
95// a block: the 16 code bytes -> 32 int8 values through a shuffle table (low nibbles: values 0..15, high: 16..31),
96// widened to F32 in 4 x 8, times the block's scale (exact), FMAs against each activation
97MX_AVX2 void rows_avx2(const uint8_t* w, size_t rb, int k, int r0, int r1, const float* const* x, int n,
98                       float* const* y) {
99    const __m128i lut = _mm_setr_epi8(0, 1, 2, 3, 4, 6, 8, 12, 0, -1, -2, -3, -4, -6, -8, -12);
100    const __m128i m4 = _mm_set1_epi8(0x0f);
101    for (int r = r0; r < r1; ++r) {
102        const uint8_t* p = w + (size_t) r * rb;
103        __m256 acc[kMxCpuMaxN];
104        for (int i = 0; i < n; ++i) acc[i] = _mm256_setzero_ps();
105        for (int b = 0; b < k / kBlock; ++b, p += kBytes) {
106            const __m256 d = _mm256_set1_ps(e8m0_half(p[0]));
107            const __m128i q = _mm_loadu_si128((const __m128i*) (p + 1));
108            const __m128i lo = _mm_shuffle_epi8(lut, _mm_and_si128(q, m4));
109            const __m128i hi = _mm_shuffle_epi8(lut, _mm_and_si128(_mm_srli_epi16(q, 4), m4));
110            const __m256 w0 = _mm256_mul_ps(d, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(lo)));
111            const __m256 w1 = _mm256_mul_ps(d, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(lo, 8))));
112            const __m256 w2 = _mm256_mul_ps(d, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(hi)));
113            const __m256 w3 = _mm256_mul_ps(d, _mm256_cvtepi32_ps(_mm256_cvtepi8_epi32(_mm_srli_si128(hi, 8))));
114            for (int i = 0; i < n; ++i) {
115                const float* xb = x[i] + b * kBlock;
116                __m256 a = acc[i];
117                a = _mm256_fmadd_ps(w0, _mm256_loadu_ps(xb), a);
118                a = _mm256_fmadd_ps(w1, _mm256_loadu_ps(xb + 8), a);
119                a = _mm256_fmadd_ps(w2, _mm256_loadu_ps(xb + 16), a);
120                a = _mm256_fmadd_ps(w3, _mm256_loadu_ps(xb + 24), a);
121                acc[i] = a;
122            }
123        }
124        for (int i = 0; i < n; ++i) y[i][r - r0] = hsum(acc[i]);
125    }
126}
127
128// ---- the int8 path's vector tiers (ds4_mx_kern.inc)
129#define MXK_NS mx_avx2
130#define MXK_ATTR MX_TARGET("avx2,fma")
131#define MXK_256 1
132#include "ds4_mx_kern.inc"
133#if defined(MX_AVXVNNI)
134#define MXK_NS mx_avxvnni
135#define MXK_ATTR MX_TARGET("avx2,fma,avxvnni")
136#define MXK_256 1
137#define MXK_VNNI 1
138#include "ds4_mx_kern.inc"
139#endif
140#define MXK_NS mx_avx512
141#define MXK_ATTR MX_TARGET("avx512f,avx512bw,fma")
142#define MXK_512 1
143#include "ds4_mx_kern.inc"
144#define MXK_NS mx_avx512vnni
145#define MXK_ATTR MX_TARGET("avx512f,avx512bw,avx512vnni,fma")
146#define MXK_512 1
147#define MXK_VNNI 1
148#include "ds4_mx_kern.inc"
149#endif
150
151// ---- the int8 path's scalar tier: ds4_mx_kern.inc's order (8 accumulators, block j of a group of 8 into L(j)), so it
152// gives the vector tiers' bits - also the tests' check on them.  The activation's layout (ds4_mx_kern.inc), for any k
153// % 32 == 0: the int8 values in quads (a partial last quad padded), then per group of 8 blocks the scales and the
154// offset corrections in lane order (a partial last group padded)
155inline int act_lane(int b) { return 8 * (b >> 3) + ((b & 7) & 1) * 4 + ((b & 7) >> 1); }
156inline size_t act_qbytes(int k) { return (size_t) 128 * (size_t) ((k / kBlock + 3) / 4); }
157inline size_t act_groups(int k) { return (size_t) ((k / kBlock + 7) / 8); }
158inline int act_q(const uint8_t* act, int b, int j) {   // block b's value j (0..31)
159    return ((const int8_t*) act)[(b >> 2) * 128 + (j >= 16 ? 64 : 0) + 16 * (b & 3) + (j & 15)];
160}
161inline float act_d(const uint8_t* act, int k, int b) { return ((const float*) (act + act_qbytes(k)))[act_lane(b)]; }
162
163void quant_scalar(const float* x, int b0, int b1, uint8_t* act, int k) {
164    int8_t* q = (int8_t*) act;
165    float* dx = (float*) (act + act_qbytes(k));
166    int32_t* corr = (int32_t*) (act + act_qbytes(k) + 32 * act_groups(k));
167    for (int b = b0; b < b1; ++b, x += kBlock) {
168        float am = 0.0f;
169        for (int j = 0; j < kBlock; ++j) am = std::max(am, std::fabs(x[j]));
170        const float sc = am / 127.0f;
171        int8_t v[kBlock];
172        int s = 0;
173        for (int j = 0; j < kBlock; ++j) {
174            v[j] = am > 0.0f ? (int8_t) (int) std::nearbyint(x[j] / sc) : (int8_t) 0;
175            s += v[j];
176        }
177        int8_t* lo = q + (b >> 2) * 128 + 16 * (b & 3);
178        for (int j = 0; j < 16; ++j) {
179            lo[j] = v[j];
180            lo[64 + j] = v[16 + j];
181        }
182        dx[act_lane(b)] = sc;
183        corr[act_lane(b)] = -12 * s;
184    }
185}
186
187void rows_q_scalar(const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, int n, float* const* y) {
188    const float* t = e8().v;
189    for (int r = r0; r < r1; ++r) {
190        const uint8_t* p = w + (size_t) r * rb;
191        float acc[kMxCpuMaxN][8] = {};
192        for (int b = 0; b < k / kBlock; ++b, p += kBytes) {
193            int wv[kBlock];
194            for (int j = 0; j < 16; ++j) {
195                wv[j] = kCodes[p[1 + j] & 15];
196                wv[j + 16] = kCodes[p[1 + j] >> 4];
197            }
198            const int l = act_lane(b) & 7;
199            for (int i = 0; i < n; ++i) {
200                const uint8_t* a = (const uint8_t*) act[i];
201                int s = 0;
202                for (int j = 0; j < kBlock; ++j) s += wv[j] * act_q(a, b, j);
203                acc[i][l] = std::fma((float) s, t[p[0]] * act_d(a, k, b), acc[i][l]);
204            }
205        }
206        for (int i = 0; i < n; ++i) {
207            const float* A = acc[i];
208            y[i][r - r0] = ((A[0] + A[4]) + (A[2] + A[6])) + ((A[1] + A[5]) + (A[3] + A[7]));
209        }
210    }
211}
212
213// ---- which tiers this CPU runs
214struct Cpu {
215    bool avx2 = false, vnni256 = false, avx512 = false, vnni512 = false, vbmi = false, bmi2 = false;
216};
217Cpu detect() {
218    Cpu c;
219#if defined(MX_X86)
220    unsigned r[4] = {0, 0, 0, 0};
221    auto cpuid = [&](unsigned leaf, unsigned sub) {
222#if defined(_MSC_VER)
223        int x[4];
224        __cpuidex(x, (int) leaf, (int) sub);
225        for (int i = 0; i < 4; ++i) r[i] = (unsigned) x[i];
226#else
227        __cpuid_count(leaf, sub, r[0], r[1], r[2], r[3]);
228#endif
229    };
230    cpuid(0, 0);
231    const unsigned max_leaf = r[0];
232    if (max_leaf < 7) return c;
233    cpuid(1, 0);
234    const bool fma = (r[2] >> 12) & 1u, osxsave = (r[2] >> 27) & 1u, avx = (r[2] >> 28) & 1u;
235    if (!fma || !osxsave || !avx) return c;
236#if defined(_MSC_VER)
237    const unsigned long long xcr0 = _xgetbv(0);
238#else
239    unsigned lo = 0, hi = 0;
240    __asm__ volatile("xgetbv" : "=a"(lo), "=d"(hi) : "c"(0));
241    const unsigned long long xcr0 = ((unsigned long long) hi << 32) | lo;
242#endif
243    if ((xcr0 & 0x6) != 0x6) return c;   // the OS saves the YMM state
244    cpuid(7, 0);
245    const unsigned b7 = r[1], c7 = r[2];
246    c.avx2 = (b7 >> 5) & 1u;
247    const bool zmm_os = (xcr0 & 0xE6) == 0xE6;
248    c.avx512 = c.avx2 && zmm_os && ((b7 >> 16) & 1u) && ((b7 >> 30) & 1u);   // F, BW
249    c.vnni512 = c.avx512 && ((c7 >> 11) & 1u);
250    c.vbmi = c.avx512 && ((c7 >> 1) & 1u);   // AVX-512 VBMI
251    c.bmi2 = (b7 >> 8) & 1u;
252    cpuid(7, 1);
253    c.vnni256 = c.avx2 && ((r[0] >> 4) & 1u);   // AVX-VNNI
254#endif
255    return c;
256}
257const Cpu& cpu() {
258    static const Cpu c = detect();
259    return c;
260}
261
262// The tier for this CPU, measured: every vector tier it runs times the same small warm job (64 rows of a 5120-wide
263// matrix, in L2, against 1, 2 and 4 activations - the compute a row takes, which is where the tiers differ; streaming
264// from RAM they all reach the memory's speed) in interleaved rounds, the best round of each counting.  The choice never
265// changes an answer (the tiers give the same bits), only the speed.  DS4_MX_TIER=<name> picks one by hand.
266std::string g_tier_report;
267int measure_tier(const std::vector<int>& cand);
268int pick_tier() {
269    if (const char* f = std::getenv("DS4_MX_TIER"))
270        for (int t = 0; t < kMxTiers; ++t)
271            if (std::string(f) == mx_tier_name(t) && mx_tier_ok(t)) {
272                g_tier_report = std::string("DS4_MX_TIER=") + f;
273                return t;
274            }
275    std::vector<int> cand;
276    for (int t = 1; t < kMxTiers; ++t)
277        if (mx_tier_ok(t)) cand.push_back(t);
278    if (cand.empty()) return kMxScalar;
279    if (cand.size() == 1) return cand[0];
280    return measure_tier(cand);
281}
282int measure_tier(const std::vector<int>& cand) {
283    constexpr int K = 5120, R = 64, NT = 4;
284    const size_t rb = (size_t) K / kBlock * kBytes;
285    std::vector<uint8_t> w(rb * R), act(mx_act_bytes(K) * NT);
286    uint32_t s = 0x9E3779B9u;
287    for (size_t i = 0; i < w.size(); ++i) {
288        s = s * 1664525u + 1013904223u;
289        w[i] = (uint8_t) (s >> 24);
290    }
291    for (size_t b = 0; b < w.size() / kBytes; ++b) w[b * kBytes] = (uint8_t) (118 + b % 6);
292    std::vector<float> x(K);
293    for (int i = 0; i < NT; ++i) {
294        for (int j = 0; j < K; ++j) {
295            s = s * 1664525u + 1013904223u;
296            x[(size_t) j] = (float) ((int) (s >> 16) - 32768) / 32768.0f;
297        }
298        quant_scalar(x.data(), 0, K / kBlock, act.data() + (size_t) i * mx_act_bytes(K), K);
299    }
300    const void* ap[NT];
301    for (int i = 0; i < NT; ++i) ap[i] = act.data() + (size_t) i * mx_act_bytes(K);
302    float y[NT][R];
303    float* yp[NT] = {y[0], y[1], y[2], y[3]};
304    std::vector<double> best(cand.size(), 1e30);
305    for (int round = 0; round < 6; ++round)
306        for (size_t c = 0; c < cand.size(); ++c) {
307            const auto t0 = std::chrono::steady_clock::now();
308            for (int rep = 0; rep < 8; ++rep)
309                for (int n : {1, 2, 4}) mx_rows_tier(cand[c], w.data(), rb, K, 0, R, ap, n, yp, 0);
310            const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
311            if (round > 0) best[c] = std::min(best[c], us);   // (round 0: the clock and the caches warm)
312        }
313    size_t bi = 0;
314    for (size_t c = 1; c < cand.size(); ++c)
315        if (best[c] < best[bi]) bi = c;
316    char buf[64];
317    for (size_t c = 0; c < cand.size(); ++c) {
318        std::snprintf(buf, sizeof buf, "%s%s %.0f us", c ? ", " : "", mx_tier_name(cand[c]), best[c]);
319        g_tier_report += buf;
320    }
321    return cand[bi];
322}
323int prefetch_bytes() {
324    const char* f = std::getenv("DS4_MX_PF");
325    return f != nullptr ? std::max(0, std::atoi(f)) : 0;
326}
327
328}  // namespace
329
330void q8_round(const float* x, int k, float* out) {
331    for (int b = 0; b < k / kBlock; ++b) {
332        const float* xb = x + b * kBlock;
333        float am = 0.0f;
334        for (int j = 0; j < kBlock; ++j) am = std::max(am, std::fabs(xb[j]));
335        const float sc = am / 127.0f;
336        for (int j = 0; j < kBlock; ++j)
337            out[b * kBlock + j] = am > 0.0f ? std::nearbyint(xb[j] / sc) * sc : 0.0f;
338    }
339}
340
341void mx_cpu_rows(const uint8_t* w, size_t rb, int k, int r0, int r1, const float* const* x, int n, float* const* y) {
342#if defined(MX_X86)
343    static const bool avx2 = strata::dsv41k::cpu::exl3_cpu_tier() >= 1;
344    if (avx2) return rows_avx2(w, rb, k, r0, r1, x, n, y);
345#endif
346    rows_scalar(w, rb, k, r0, r1, x, n, y);
347}
348
349// ---- the int8 path
350bool mx_tier_ok(int t) {
351    switch (t) {
352        case kMxScalar: return true;
353        case kMxAvx2: return cpu().avx2;
354#if defined(MX_AVXVNNI)
355        case kMxAvxVnni: return cpu().vnni256;
356#endif
357        case kMxAvx512: return cpu().avx512;
358        case kMxAvx512Vnni: return cpu().vnni512;
359        default: return false;
360    }
361}
362const char* mx_tier_name(int t) {
363    switch (t) {
364        case kMxScalar: return "scalar";
365        case kMxAvx2: return "avx2";
366        case kMxAvxVnni: return "avxvnni";
367        case kMxAvx512: return "avx512";
368        case kMxAvx512Vnni: return "avx512vnni";
369        default: return "?";
370    }
371}
372int mx_tier() {
373    static const int t = pick_tier();
374    return t;
375}
376const char* mx_tier_report() {
377    (void) mx_tier();
378    return g_tier_report.c_str();
379}
380
381void mx_quant_blocks(const float* x, int b0, int b1, void* act, int k) {
382#if defined(MX_X86)
383    if (cpu().avx2 && k % 256 == 0) return mx_avx2::quant(x, b0, b1, (uint8_t*) act, k);
384#endif
385    quant_scalar(x, b0, b1, (uint8_t*) act, k);
386}
387void mx_quant_blocks_scalar(const float* x, int b0, int b1, void* act, int k) {
388    quant_scalar(x, b0, b1, (uint8_t*) act, k);
389}
390int mx_act_value(const void* act, int b, int j) { return act_q((const uint8_t*) act, b, j); }
391float mx_act_scale(const void* act, int k, int b) { return act_d((const uint8_t*) act, k, b); }
392
393void mx_rows_tier(int t, const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, int n,
394                  float* const* y, int pf) {
395    if (k % 256 != 0 || !mx_tier_ok(t)) t = kMxScalar;   // (the vector tiers take a group of 8 blocks a step)
396    const float* tb = e8().v;
397#if defined(MX_X86)
398    switch (t) {
399        case kMxAvx2: return mx_avx2::rows(w, rb, k, r0, r1, act, n, y, tb, pf);
400#if defined(MX_AVXVNNI)
401        case kMxAvxVnni: return mx_avxvnni::rows(w, rb, k, r0, r1, act, n, y, tb, pf);
402#endif
403        case kMxAvx512: return mx_avx512::rows(w, rb, k, r0, r1, act, n, y, tb, pf);
404        case kMxAvx512Vnni: return mx_avx512vnni::rows(w, rb, k, r0, r1, act, n, y, tb, pf);
405        default: break;
406    }
407#endif
408    (void) tb, (void) pf;
409    for (int i0 = 0; i0 < n; i0 += kMxCpuMaxN)
410        rows_q_scalar(w, rb, k, r0, r1, act + i0, std::min(kMxCpuMaxN, n - i0), y + i0);
411}
412
413void mx_rows(const uint8_t* w, size_t rb, int k, int r0, int r1, const void* const* act, int n, float* const* y) {
414    static const int pf = prefetch_bytes();
415    mx_rows_tier(mx_tier(), w, rb, k, r0, r1, act, n, y, pf);
416}
417
418}  // namespace strata::ds4::gguf