okami.mom/strata

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

Niko1221Merge f-own-2a (7c09c4a75) into f-own-int: the Strata quant layer and the x86 CPU rows9c143c403

main
9.2 KiB228 linesraw
1// src/quant/selfcheck.cpp - the layer's start-up self-checks (see selfcheck.hpp for what they do and do not prove).
2#include "strata/quant/selfcheck.hpp"
3
4#include <cstdio>
5#include <cstring>
6#include <mutex>
7#include <vector>
8
9#include "internal.hpp"
10#include "registry.hpp"
11
12namespace strata::quant {
13namespace {
14
15struct Rng {
16    uint64_t s;
17    explicit Rng(uint64_t seed) : s(seed * 0x9E3779B97F4A7C15ull + 0x1234567ull) {}
18    uint32_t next() {   // xorshift64*
19        s ^= s >> 12;
20        s ^= s << 25;
21        s ^= s >> 27;
22        return (uint32_t) ((s * 0x2545F4914F6CDD1Dull) >> 32);
23    }
24};
25
26constexpr uint16_t kH1 = 0x3C00, kH05 = 0x3800;   // fp16 1.0 and 0.5
27
28template <typename B>
29B* blk(std::vector<uint8_t>& row, size_t i) { return reinterpret_cast<B*>(row.data()) + i; }
30
31// A random weight row of n elements whose scales are powers of two, so every float operation of every contract is exact.
32std::vector<uint8_t> make_weights(Type t, int n, Rng& r) {
33    const TypeInfo* ti = type_info(t);
34    const size_t nb = (size_t) (n / ti->blck);
35    std::vector<uint8_t> row(nb * ti->bytes);
36    for (uint8_t& b : row) b = (uint8_t) r.next();
37    for (size_t i = 0; i < nb; ++i) {
38        switch (t) {
39            case Type::Q2_0: blk<block_q2_0>(row, i)->d = kH1; break;
40            case Type::Q4_0: blk<block_q4_0>(row, i)->d = kH1; break;
41            case Type::Q4_1: blk<block_q4_1>(row, i)->d = kH1, blk<block_q4_1>(row, i)->m = kH05; break;
42            case Type::Q5_0: blk<block_q5_0>(row, i)->d = kH1; break;
43            case Type::Q5_1: blk<block_q5_1>(row, i)->d = kH1, blk<block_q5_1>(row, i)->m = kH05; break;
44            case Type::Q8_0: blk<block_q8_0>(row, i)->d = kH05; break;
45            case Type::IQ4_NL: blk<block_iq4_nl>(row, i)->d = kH1; break;
46            case Type::MXFP4: blk<block_mxfp4>(row, i)->e = 127; break;
47            case Type::NVFP4: for (int j = 0; j < 4; ++j) blk<block_nvfp4>(row, i)->d[j] = 0x38; break;
48            case Type::Q2_K: blk<block_q2_K>(row, i)->d = kH1, blk<block_q2_K>(row, i)->dmin = kH05; break;
49            case Type::Q3_K: blk<block_q3_K>(row, i)->d = kH1; break;
50            case Type::Q4_K: blk<block_q4_K>(row, i)->d = kH1, blk<block_q4_K>(row, i)->dmin = kH05; break;
51            case Type::Q5_K: blk<block_q5_K>(row, i)->d = kH1, blk<block_q5_K>(row, i)->dmin = kH05; break;
52            case Type::Q6_K: blk<block_q6_K>(row, i)->d = kH1; break;
53            case Type::IQ2_XXS: blk<block_iq2_xxs>(row, i)->d = kH1; break;
54            case Type::IQ2_XS: blk<block_iq2_xs>(row, i)->d = kH1; break;
55            case Type::IQ2_S: blk<block_iq2_s>(row, i)->d = kH1; break;
56            case Type::IQ3_XXS: blk<block_iq3_xxs>(row, i)->d = kH1; break;
57            case Type::IQ3_S: blk<block_iq3_s>(row, i)->d = kH1; break;
58            case Type::IQ1_S: blk<block_iq1_s>(row, i)->d = kH1; break;
59            case Type::IQ4_XS: blk<block_iq4_xs>(row, i)->d = kH1; break;
60            case Type::IQ1_M: {   // the fp16 scale is spread over the top nibbles of the four 16-bit scale words: 0x3C00 = nibbles 0, 0, C, 3
61                uint16_t* sc = reinterpret_cast<uint16_t*>(blk<block_iq1_m>(row, i)->scales);
62                sc[0] = (uint16_t) ((sc[0] & 0x0FFF) | 0x0000);
63                sc[1] = (uint16_t) ((sc[1] & 0x0FFF) | 0x0000);
64                sc[2] = (uint16_t) ((sc[2] & 0x0FFF) | 0xC000);
65                sc[3] = (uint16_t) ((sc[3] & 0x0FFF) | 0x3000);
66                break;
67            }
68            default: break;
69        }
70    }
71    return row;
72}
73
74// A random activation row: values in [-3, 3], scale 1.
75std::vector<uint8_t> make_act(Type act, int n, Rng& r) {
76    const TypeInfo* ti = type_info(act);
77    const size_t nb = (size_t) (n / ti->blck);
78    std::vector<uint8_t> row(nb * ti->bytes);
79    auto q = [&r] { return (int8_t) ((int) (r.next() % 7) - 3); };
80    for (size_t i = 0; i < nb; ++i) {
81        if (act == Type::Q8_0) {
82            block_q8_0* b = blk<block_q8_0>(row, i);
83            b->d = kH1;
84            for (int j = 0; j < QK8_0; ++j) b->qs[j] = q();
85        } else if (act == Type::Q8_1) {
86            block_q8_1* b = blk<block_q8_1>(row, i);
87            int sum = 0;
88            for (int j = 0; j < QK8_1; ++j) sum += b->qs[j] = q();
89            b->d = kH1;
90            b->s = fp32_to_fp16((float) sum);
91        } else {
92            block_q8_K* b = blk<block_q8_K>(row, i);
93            b->d = 1.0f;
94            for (int j = 0; j < QK_K; ++j) b->qs[j] = q();
95            for (int g = 0; g < QK_K / 16; ++g) {
96                int sum = 0;
97                for (int j = 0; j < 16; ++j) sum += b->qs[g * 16 + j];
98                b->bsums[g] = (int16_t) sum;
99            }
100        }
101    }
102    return row;
103}
104
105bool same_float(float a, float b) { return std::memcmp(&a, &b, sizeof a) == 0 || (a == b) || (a != a && b != b); }
106
107bool check_dot(const DotKernel& k, std::string* why) {
108    const TypeInfo* ti = type_info(k.weight);
109    const TypeInfo* ai = type_info(k.act);
110    if (ti == nullptr || ai == nullptr) return false;
111    const int unit = ti->blck > ai->blck ? ti->blck : ai->blck;
112    const int counts[] = {1, 2, 3, 5};
113    Rng r((uint64_t) k.weight * 1000 + 7);
114    for (int c : counts) {
115        const int n = unit * c;
116        for (int rep = 0; rep < 3; ++rep) {
117            const std::vector<uint8_t> w = make_weights(k.weight, n, r);
118            const std::vector<uint8_t> a = make_act(k.act, n, r);
119            float ref = 0.f, got = 0.f;
120            dot_ref(k.weight, n, &ref, w.data(), a.data());
121            k.fn(n, &got, w.data(), a.data());
122            if (!same_float(ref, got)) {
123                if (why) {
124                    char buf[160];
125                    std::snprintf(buf, sizeof buf, "%s: n=%d reference %.9g (%08x) kernel %.9g (%08x)", k.name, n, ref, f32_to_bits(ref), got,
126                                  f32_to_bits(got));
127                    *why = buf;
128                }
129                return false;
130            }
131        }
132    }
133    return true;
134}
135
136bool check_act(const ActKernel& k, std::string* why) {
137    const TypeInfo* ti = type_info(k.act);
138    if (ti == nullptr) return false;
139    const ActKernel* ref = nullptr;
140    const ActTable g = generic_act_table();
141    for (int i = 0; i < g.n; ++i)
142        if (g.v[i].act == k.act) ref = &g.v[i];
143    if (ref == nullptr) return false;
144    Rng r(0xAC7 + (uint64_t) k.act);
145    for (int c : {1, 2, 3, 5}) {
146        const int n = ti->blck * c;
147        std::vector<float> x((size_t) n);
148        for (float& v : x) v = (float) ((int) (r.next() % 20001) - 10000) * (1.0f / 977.0f);   // arbitrary values, ties are improbable
149        std::vector<uint8_t> a((size_t) c * ti->bytes), b((size_t) c * ti->bytes);
150        ref->fn(x.data(), a.data(), n);
151        k.fn(x.data(), b.data(), n);
152        if (std::memcmp(a.data(), b.data(), a.size()) != 0) {
153            if (why) *why = std::string(k.name) + ": the blocks differ from the reference quantizer";
154            return false;
155        }
156    }
157    return true;
158}
159
160// one verdict per (kind, type, arith, isa), computed on first use
161struct Verdicts {
162    std::mutex mu;
163    std::vector<std::pair<uint64_t, bool>> v;
164};
165Verdicts& verdicts() {
166    static Verdicts* x = new Verdicts;
167    return *x;
168}
169uint64_t key(int kind, Type t, Arith a, Isa i) { return ((uint64_t) kind << 32) | ((uint64_t) (int) t << 12) | ((uint64_t) (int) a << 4) | (uint64_t) (int) i; }
170
171}  // namespace
172
173bool selfcheck(const DotKernel& k, std::string* why) { return check_dot(k, why); }
174bool selfcheck(const ActKernel& k, std::string* why) { return check_act(k, why); }
175
176const DotKernel* checked_dot_kernel(Type w, Arith a) noexcept {
177    const DotKernel* v[16];
178    const int n = dot_kernels(w, a, v, 16);
179    for (int i = 0; i < n; ++i) {
180        const DotKernel* k = v[i];
181        if (!isa_ok(k->isa)) continue;
182        Verdicts& vd = verdicts();
183        const uint64_t kk = key(0, w, a, k->isa);
184        bool known = false, ok = false;
185        {
186            std::lock_guard<std::mutex> lk(vd.mu);
187            for (auto& e : vd.v)
188                if (e.first == kk) known = true, ok = e.second;
189        }
190        if (!known) {
191            std::string why;
192            ok = check_dot(*k, &why);
193            if (!ok) std::fprintf(stderr, "strata: quant self-check failed, kernel dropped: %s\n", why.c_str());
194            std::lock_guard<std::mutex> lk(vd.mu);
195            vd.v.emplace_back(kk, ok);
196        }
197        if (ok) return k;
198    }
199    return nullptr;
200}
201
202const ActKernel* checked_act_kernel(Type act, Arith a) noexcept {
203    const Isa top = best_isa();
204    for (int ii = (int) top; ii >= 0; --ii) {
205        const ActKernel* k = act_kernel(act, a, (Isa) ii);
206        if (k == nullptr) return nullptr;
207        Verdicts& vd = verdicts();
208        const uint64_t kk = key(1, act, a, k->isa);
209        bool known = false, ok = false;
210        {
211            std::lock_guard<std::mutex> lk(vd.mu);
212            for (auto& e : vd.v)
213                if (e.first == kk) known = true, ok = e.second;
214        }
215        if (!known) {
216            std::string why;
217            ok = check_act(*k, &why);
218            if (!ok) std::fprintf(stderr, "strata: quant self-check failed, kernel dropped: %s\n", why.c_str());
219            std::lock_guard<std::mutex> lk(vd.mu);
220            vd.v.emplace_back(kk, ok);
221        }
222        if (ok) return k;
223        ii = (int) k->isa;   // continue below the failed kernel's level
224    }
225    return nullptr;
226}
227
228}  // namespace strata::quant