okami.mom/strata

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

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

main
7.2 KiB148 linesraw
1// src/kernels/cpu/q8k_quant_parity.cpp - the AVX-2 Q8_K activation quantizer (q8k_quant_avx2, iq_avx2.cpp) against
2// ggml's, byte for byte: the reference (ggml-base's from_float_ref) and what ggml-cpu runs (its from_float), over
3// rows of random, scaled, sparse and degenerate values; then the same through native_quant_act / native_quant_h with
4// an IQ3_S expert's format, which is what the engine calls.  No GPU, no model.
5//
6//     q8k_quant_parity            (STRATA_FORCE_ISA=avx: the AVX-2 copy is skipped, native_quant_* must equal ggml's)
7//     q8k_quant_parity --bench    ns per 2560-value row, ggml-cpu's and the AVX-2 copy
8#include "strata/kernels/cpu/expert_layout.hpp"
9#include "strata/kernels/cpu/iq_avx2.hpp"
10#include "strata/kernels/cpu/iq_avx1.hpp"
11#include "strata/kernels/cpu/native_expert.hpp"
12
13#include "ggml.h"
14#include "ggml-cpu.h"
15
16#include <algorithm>
17#include <chrono>
18#include <cmath>
19#include <cstdint>
20#include <cstdio>
21#include <cstring>
22#include <limits>
23#include <random>
24#include <string>
25#include <vector>
26
27namespace cpu = strata::kernels::cpu;
28
29// ggml-quants.h (ggml-base): the scalar reference, which ggml-cpu's x86 quantize_row_q8_K calls.  Q8_K has no
30// from_float_ref in ggml's type traits, so it is declared here (block_q8_K* in ggml; the bytes are all this reads).
31extern "C" void quantize_row_q8_K_ref(const float* x, void* y, int64_t k);
32
33namespace {
34
35constexpr int kQK = 256;
36
37std::vector<std::vector<float>> cases(int n) {
38    std::mt19937 rng(11);
39    std::normal_distribution<float> nd(0.f, 1.f);
40    std::uniform_real_distribution<float> ud(-100.f, 100.f);
41    std::vector<std::vector<float>> c;
42    auto add = [&](auto fill) {
43        std::vector<float> x((size_t) n);
44        for (int j = 0; j < n; ++j) x[(size_t) j] = fill(j);
45        c.push_back(std::move(x));
46    };
47    add([&](int) { return nd(rng); });
48    add([&](int) { return nd(rng) * 1e-3f; });
49    add([&](int) { return nd(rng) * 1e4f; });
50    add([&](int) { return ud(rng); });
51    add([&](int) { return 0.f; });                                         // every block zero
52    add([&](int j) { return (j / kQK) % 2 ? nd(rng) : 0.f; });             // zero blocks between random ones
53    add([&](int j) { return j % kQK == 77 ? nd(rng) : 0.f; });             // one value per block
54    add([&](int j) {                                                       // the largest magnitude twice, the
55        const int k = j % kQK;                                             // FIRST one's sign wins
56        return k == 3 ? -5.f : k == 100 ? 5.f : nd(rng);
57    });
58    add([&](int j) {
59        const int k = j % kQK;
60        return k == 3 ? 5.f : k == 100 ? -5.f : nd(rng);
61    });
62    add([&](int j) { return j % kQK == 9 ? 3e38f : nd(rng); });            // extremes beside ordinary values
63    add([&](int j) { return j % kQK == 9 ? -3e38f : nd(rng) * 1e30f; });
64    add([&](int) { return nd(rng) * 1e-40f; });                            // denormals
65    add([&](int j) { return (float) ((j % 255) - 127) / 127.f; });         // the grid itself, and its ties
66    add([&](int j) { return ((float) ((j * 37) % 509) - 254.f) / 508.f; });
67    add([&](int j) { return j % kQK == 5 ? std::numeric_limits<float>::quiet_NaN() : nd(rng); });
68    add([&](int j) { return j % kQK == 5 ? std::numeric_limits<float>::infinity() : nd(rng); });
69    return c;
70}
71
72// both outputs prefilled alike: a zero block leaves bsums unwritten in the reference, and so must the copy
73bool same(const char* tag, int n, int ci, ggml_from_float_t a, void (*b)(const float*, void*, int64_t),
74          const std::vector<float>& x, size_t bytes) {
75    std::vector<uint8_t> ya(bytes, 0xAB), yb(bytes, 0xAB);
76    a(x.data(), ya.data(), n);
77    b(x.data(), yb.data(), n);
78    if (std::memcmp(ya.data(), yb.data(), bytes) == 0) return true;
79    size_t at = 0;
80    while (ya[at] == yb[at]) ++at;
81    std::printf("  %s n=%d case %d: MISMATCH at byte %zu of %zu\n", tag, n, ci, at, bytes);
82    return false;
83}
84
85const cpu::NativeFmt* g_fmt = nullptr;
86void via_act(const float* x, void* y, int64_t) { cpu::native_quant_act(*g_fmt, x, y); }
87void via_h(const float* x, void* y, int64_t) { cpu::native_quant_h(*g_fmt, x, y); }
88
89}  // namespace
90
91int main(int argc, char** argv) {
92    const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
93    ggml_cpu_init();
94    const ggml_from_float_t ref = quantize_row_q8_K_ref;
95    const ggml_from_float_t gcpu = ggml_get_type_traits_cpu(GGML_TYPE_Q8_K)->from_float;
96    const bool avx2 = cpu::cpu_avx2_ok();
97    const bool avx1 = !avx2 && cpu::cpu_avx1_ok();   // the older CPUs' copy (checked wherever AVX exists)
98    int failures = 0, checked = 0;
99    for (const int n : {256, 512, 2560, 6144}) {
100        const size_t bytes = ggml_row_size(GGML_TYPE_Q8_K, n);
101        const auto cs = cases(n);
102        for (int ci = 0; ci < (int) cs.size(); ++ci) {
103            failures += !same("ggml-cpu vs reference", n, ci, ref, gcpu, cs[(size_t) ci], bytes);
104            if (avx2) failures += !same("AVX-2 vs reference", n, ci, ref, cpu::q8k_quant_avx2, cs[(size_t) ci], bytes);
105            if (avx1) failures += !same("AVX1 vs reference", n, ci, ref, cpu::q8k_quant_avx1, cs[(size_t) ci], bytes);
106            ++checked;
107        }
108    }
109    // the engine's entry points: an IQ3_S expert (type 21) quantizes both of its activations to Q8_K
110    cpu::NativeFmt f;
111    std::string err;
112    if (!cpu::native_fmt(21, 21, 2560, 512, f, err)) {
113        std::printf("native_fmt: %s\n", err.c_str());
114        return 1;
115    }
116    g_fmt = &f;
117    for (const auto& x : cases(2560))
118        failures += !same("native_quant_act", 2560, 0, ref, via_act, x, ggml_row_size(GGML_TYPE_Q8_K, 2560));
119    for (const auto& x : cases(512))
120        failures += !same("native_quant_h", 512, 0, ref, via_h, x, ggml_row_size(GGML_TYPE_Q8_K, 512));
121    std::printf("q8k_quant_parity: %d rows x 4 sizes, AVX-2 copy %s, AVX1 copy %s: %s\n", checked / 4,
122                avx2 ? "checked" : "skipped (no AVX2, or STRATA_FORCE_ISA)",
123                avx1 ? "checked" : "skipped (AVX2 present, no AVX, or STRATA_FORCE_ISA)", failures ? "FAILED" : "identical");
124    if (bench && (avx2 || avx1)) {
125        std::mt19937 rng(3);
126        std::normal_distribution<float> nd(0.f, 1.f);
127        const int n = 2560, rows = 4096;
128        std::vector<float> x((size_t) n * rows);
129        for (auto& v : x) v = nd(rng);
130        const size_t bytes = ggml_row_size(GGML_TYPE_Q8_K, n);
131        std::vector<uint8_t> y(bytes * rows);
132        auto time = [&](const char* tag, auto fn) {
133            double best = 1e30;
134            for (int rep = 0; rep < 5; ++rep) {
135                const auto t0 = std::chrono::steady_clock::now();
136                for (int r = 0; r < rows; ++r) fn(x.data() + (size_t) r * n, y.data() + bytes * r, n);
137                const double ns = std::chrono::duration<double, std::nano>(std::chrono::steady_clock::now() - t0).count();
138                best = std::min(best, ns / rows);
139            }
140            std::printf("  %-10s %7.0f ns per %d-value row\n", tag, best, n);
141            return best;
142        };
143        const double a = time("ggml-cpu", gcpu);
144        const double b = avx2 ? time("AVX-2", cpu::q8k_quant_avx2) : time("AVX1", cpu::q8k_quant_avx1);
145        std::printf("  %.1fx\n", a / b);
146    }
147    return failures ? 1 : 0;
148}