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
12.2 KiB244 linesraw
1// src/kernels/cpu/pool_determinism.cpp - the CPU expert pool's native rows are deterministic: the same inputs through native_quant_act / native_quant_h /
2// native_gu_rows / native_down_rows (Default and WindowInvariant) give the same bits however many times, in whatever thread count, with whatever row split, and
3// whatever the output and activation buffers held before.
4//
5//   pool_determinism [--reps N] [--seed S] [--type G,D]
6//
7// For every (gate/up, down) format pair the pool accepts (native_fmt) and nt = 1..8 tokens it checks
8//   1. the activation quantizers write every byte they own: a destination pre-filled with 0x00 and one with 0xFF end up equal (an uninitialised byte, such as a
9//      Q8_K block sum of an all-zero block, would show) - bytes beyond act_bytes / h_bytes are never read: a canary after the buffer must stay intact;
10//   2. the rows of a pass are independent of how they are split: the full range against random chunks (what the pool's job split does);
11//   3. T threads (1, 2, 4, 8, 16) each taking a share of the rows at the same time, `reps` times over, equal the single-thread reference bit for bit;
12//   4. the output buffers' previous contents do not matter (pre-filled with a NaN pattern and with zeros).
13// Exit status 0 = nothing differed.  For the buffer checks configure a build with -DCMAKE_CXX_FLAGS="-fsanitize=address,undefined -fno-omit-frame-pointer" or run it under valgrind (the
14// canary and the pre-fill catch the same class without them).
15#include <algorithm>
16#include <atomic>
17#include <cctype>
18#include <cmath>
19#include <map>
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <random>
24#include <string>
25#include <thread>
26#include <vector>
27
28#include "strata/kernels/cpu/native_expert.hpp"
29#include "strata/kernels/cpu/pool_quant.hpp"
30
31namespace kc = strata::kernels::cpu;
32
33namespace {
34constexpr int kH = 2048, kFF = 512;   // whole blocks of every format (256-value super-blocks, 64-value Q2_0 / NVFP4 blocks)
35constexpr int kMaxNt = 8;
36int g_fail = 0;
37long g_checks = 0;
38
39std::map<std::string, int> g_kinds;   // failure kind (the message without its numbers) -> count
40void fail(const std::string& what) {
41    ++g_fail;
42    std::string kind;
43    for (char ch : what)
44        if (!std::isdigit((unsigned char) ch)) kind += ch;
45    if (g_kinds[kind]++ < 3) std::printf("FAIL %s\n", what.c_str());
46}
47
48// fp16 scale at the front of every block where the format has it there; everything else random bytes (the result may be inf / NaN: compared as bits)
49void fill_blob(std::vector<uint8_t>& blob, const kc::NativeFmt& f, std::mt19937_64& rng) {
50    for (size_t i = 0; i < blob.size(); i += 8) {
51        const uint64_t v = rng();
52        std::memcpy(&blob[i], &v, std::min<size_t>(8, blob.size() - i));
53    }
54    auto fix = [&](size_t off, size_t bytes, int type) {
55        const size_t bs = kc::pq::type_size_of(type);
56        if (bs == 0 || type == kc::kNvfp4Type) return;
57        for (size_t o = 0; o + bs <= bytes; o += bs) {
58            const uint16_t h = kc::pq::fp16_bits(0.004f + 0.001f * (float) (rng() % 16));
59            std::memcpy(&blob[off + o], &h, 2);
60        }
61    };
62    fix(0, f.down_off, f.gu_type);
63    fix(f.down_off, f.bytes - f.down_off - (f.tail_off ? 16 : 0), f.d_type);
64    if (f.tail_off) {   // NVFP4's per-expert scales
65        const float tail[4] = {1.f, 1.f, 1.f, 0.f};
66        std::memcpy(&blob[f.tail_off], tail, sizeof tail);
67    }
68}
69
70bool same_bits(const std::vector<float>& a, const std::vector<float>& b) { return a.size() == b.size() && std::memcmp(a.data(), b.data(), a.size() * 4) == 0; }
71
72struct Case {
73    kc::NativeFmt f;
74    std::vector<uint8_t> blob;
75    std::vector<std::vector<float>> x, h;
76};
77
78// quantize `nt` tokens into buffers pre-filled with `fill`, each followed by a canary
79struct Acts {
80    std::vector<std::vector<uint8_t>> a, hq;
81    std::vector<const void*> ap, hp;
82};
83constexpr size_t kCanary = 64;
84void make_acts(const Case& c, int nt, uint8_t fill, Acts& o, int& canary_bad) {
85    o.a.assign(nt, std::vector<uint8_t>(c.f.act_bytes + kCanary, fill));
86    o.hq.assign(nt, std::vector<uint8_t>(c.f.h_bytes + kCanary, fill));
87    for (int t = 0; t < nt; ++t) {
88        std::memset(o.a[t].data() + c.f.act_bytes, 0x5A, kCanary);
89        std::memset(o.hq[t].data() + c.f.h_bytes, 0x5A, kCanary);
90        kc::native_quant_act(c.f, c.x[t].data(), o.a[t].data());
91        kc::native_quant_h(c.f, c.h[t].data(), o.hq[t].data());
92        for (size_t i = 0; i < kCanary; ++i)
93            if (o.a[t][c.f.act_bytes + i] != 0x5A || o.hq[t][c.f.h_bytes + i] != 0x5A) ++canary_bad;
94    }
95    o.ap.resize(nt);
96    o.hp.resize(nt);
97    for (int t = 0; t < nt; ++t) o.ap[t] = o.a[t].data(), o.hp[t] = o.hq[t].data();
98}
99
100// A Q8_K block of all zeros (d == 0) leaves its 16 block sums unwritten - in ggml's quantize_row_q8_K_ref as in the layer's, byte for byte.  The dots multiply them by
101// y.d == 0, so they never reach a result (the row checks below prove it); for the byte comparison of two quantizations they are don't-care.
102void mask_zero_block_sums(uint8_t* p, int act_type, size_t bytes) {
103    if (act_type != 15) return;
104    for (size_t o = 0; o + 292 <= bytes; o += 292) {
105        float d;
106        std::memcpy(&d, p + o, 4);
107        if (d == 0.f) std::memset(p + o + 4 + 256, 0, 32);
108    }
109}
110
111using GuFn = void (*)(const kc::NativeFmt&, const uint8_t*, const void* const*, int, float* const*, int, int);
112using DnFn = void (*)(const kc::NativeFmt&, const uint8_t*, const void* const*, int, float* const*, int, int);
113
114// one pass over rows [0, kFF) (gate/up) and [0, kH) (down) in `chunks` pieces taken by `threads` threads; the outputs are the flat [t][row] arrays
115void run_pass(const Case& c, const Acts& ac, int nt, GuFn gu, DnFn dn, int threads, const std::vector<int>& cuts_gu, const std::vector<int>& cuts_dn, float init,
116              std::vector<float>& ff, std::vector<float>& out) {
117    ff.assign((size_t) nt * kFF, init);
118    out.assign((size_t) nt * kH, init);
119    std::vector<float*> fp(nt), op(nt);
120    for (int t = 0; t < nt; ++t) fp[t] = ff.data() + (size_t) t * kFF, op[t] = out.data() + (size_t) t * kH;
121    std::atomic<int> next_gu{0}, next_dn{0};
122    auto work = [&] {
123        for (;;) {
124            const int i = next_gu.fetch_add(1);
125            if (i + 1 >= (int) cuts_gu.size()) break;
126            gu(c.f, c.blob.data(), ac.ap.data(), nt, fp.data(), cuts_gu[i], cuts_gu[i + 1]);
127        }
128        for (;;) {
129            const int i = next_dn.fetch_add(1);
130            if (i + 1 >= (int) cuts_dn.size()) break;
131            dn(c.f, c.blob.data(), ac.hp.data(), nt, op.data(), cuts_dn[i], cuts_dn[i + 1]);
132        }
133    };
134    if (threads <= 1) {
135        work();
136    } else {
137        std::vector<std::thread> th;
138        for (int i = 0; i < threads; ++i) th.emplace_back(work);
139        for (auto& t : th) t.join();
140    }
141}
142
143std::vector<int> split(int n, int chunks, std::mt19937_64& rng, bool random) {
144    std::vector<int> cuts{0};
145    if (random) {
146        std::vector<int> mid;
147        for (int i = 1; i < chunks; ++i) mid.push_back((int) (rng() % (uint64_t) (n - 1)) + 1);
148        std::sort(mid.begin(), mid.end());
149        for (int m : mid)
150            if (m > cuts.back()) cuts.push_back(m);
151    } else {
152        for (int i = 1; i < chunks; ++i) cuts.push_back(n * i / chunks);
153    }
154    cuts.push_back(n);
155    return cuts;
156}
157
158void test_pair(int gt, int dt, int reps, uint64_t seed) {
159    Case c;
160    std::string err;
161    if (!kc::native_fmt(gt, dt, kH, kFF, c.f, err)) return;   // a pair the pool does not take
162    std::mt19937_64 rng(seed + (uint64_t) gt * 131 + (uint64_t) dt);
163    c.blob.assign(c.f.bytes, 0);
164    fill_blob(c.blob, c.f, rng);
165    c.x.assign(kMaxNt, std::vector<float>(kH));
166    c.h.assign(kMaxNt, std::vector<float>(kFF));
167    std::normal_distribution<float> nd(0.f, 1.f);
168    for (int t = 0; t < kMaxNt; ++t) {
169        for (float& v : c.x[t]) v = nd(rng) * (t % 3 == 0 ? 1.f : 0.05f);
170        for (float& v : c.h[t]) v = nd(rng) * (t % 2 == 0 ? 1.f : 0.3f);
171        if (t == 5) std::fill(c.x[t].begin(), c.x[t].end(), 0.f);   // an all-zero activation: Q8_K's zero blocks
172        if (t == 6) std::fill(c.h[t].begin(), c.h[t].begin() + 300, 0.f);
173    }
174    char tag[64];
175    std::snprintf(tag, sizeof tag, "gu %d down %d", gt, dt);
176    struct Mode {
177        const char* name;
178        GuFn gu;
179        DnFn dn;
180    } modes[] = {{"default", kc::native_gu_rows, kc::native_down_rows}, {"invariant", kc::native_gu_rows_invariant, kc::native_down_rows_invariant}};
181    for (const Mode& m : modes) {
182        for (int nt = 1; nt <= kMaxNt; ++nt) {
183            int canary_bad = 0;
184            Acts a0, a1;
185            make_acts(c, nt, 0x00, a0, canary_bad);
186            make_acts(c, nt, 0xFF, a1, canary_bad);
187            ++g_checks;
188            if (canary_bad) fail(std::string(tag) + " " + m.name + ": a quantizer wrote past act_bytes / h_bytes");
189            for (int t = 0; t < nt; ++t) {
190                std::vector<uint8_t> x0 = a0.a[t], x1 = a1.a[t], y0 = a0.hq[t], y1 = a1.hq[t];   // copies: the originals keep their unwritten bytes for the row passes
191                mask_zero_block_sums(x0.data(), c.f.gu_act, c.f.act_bytes);
192                mask_zero_block_sums(x1.data(), c.f.gu_act, c.f.act_bytes);
193                mask_zero_block_sums(y0.data(), c.f.d_act, c.f.h_bytes);
194                mask_zero_block_sums(y1.data(), c.f.d_act, c.f.h_bytes);
195                ++g_checks;
196                if (std::memcmp(x0.data(), x1.data(), c.f.act_bytes) != 0) fail(std::string(tag) + ": gate/up activation bytes depend on the buffer's previous content (token " + std::to_string(t) + ")");
197                if (std::memcmp(y0.data(), y1.data(), c.f.h_bytes) != 0) fail(std::string(tag) + ": down activation bytes depend on the buffer's previous content (token " + std::to_string(t) + ")");
198            }
199            std::vector<float> ref_ff, ref_out, ff, out;
200            run_pass(c, a0, nt, m.gu, m.dn, 1, {0, kFF}, {0, kH}, 0.f, ref_ff, ref_out);
201            std::vector<float> ff2, out2;
202            run_pass(c, a1, nt, m.gu, m.dn, 1, {0, kFF}, {0, kH}, std::nanf(""), ff2, out2);
203            ++g_checks;
204            if (!same_bits(ref_ff, ff2) || !same_bits(ref_out, out2)) fail(std::string(tag) + " " + m.name + " nt=" + std::to_string(nt) + ": the result depends on the buffers' previous content");
205            for (int rep = 0; rep < reps; ++rep) {
206                const int threads = (int) (std::vector<int>{1, 2, 4, 8, 16})[(size_t) (rep % 5)];
207                const bool rnd = rep % 2 == 0;
208                run_pass(c, rep % 3 ? a0 : a1, nt, m.gu, m.dn, threads, split(kFF, 1 + (int) (rng() % 12), rng, rnd), split(kH, 1 + (int) (rng() % 24), rng, rnd),
209                         rep % 4 == 0 ? std::nanf("") : 0.f, ff, out);
210                ++g_checks;
211                if (!same_bits(ref_ff, ff) || !same_bits(ref_out, out)) {
212                    fail(std::string(tag) + " " + m.name + " nt=" + std::to_string(nt) + " rep " + std::to_string(rep) + " threads " + std::to_string(threads) +
213                         (!same_bits(ref_ff, ff) ? ": gate/up rows differ" : ": down rows differ"));
214                    break;
215                }
216            }
217        }
218    }
219}
220}  // namespace
221
222int main(int argc, char** argv) {
223    int reps = 40;
224    uint64_t seed = 99;
225    int only_g = -1, only_d = -1;
226    for (int i = 1; i < argc; ++i) {
227        if (!std::strcmp(argv[i], "--reps") && i + 1 < argc) reps = std::atoi(argv[++i]);
228        else if (!std::strcmp(argv[i], "--seed") && i + 1 < argc) seed = (uint64_t) std::atoll(argv[++i]);
229        else if (!std::strcmp(argv[i], "--type") && i + 1 < argc) std::sscanf(argv[++i], "%d,%d", &only_g, &only_d);
230    }
231    static const int kGu[] = {2, 3, 6, 7, 8, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 29, 40, 42};
232    static const int kDn[] = {2, 6, 7, 8, 10, 11, 12, 13, 14, 20, 21, 23, 40, 42};
233    int pairs = 0;
234    for (int g : kGu)
235        for (int d : kDn) {
236            if (only_g >= 0 && (g != only_g || d != only_d)) continue;
237            const long before = g_checks;
238            test_pair(g, d, reps, seed);
239            if (g_checks != before) ++pairs;
240        }
241    for (const auto& k : g_kinds) std::printf("  %6d x %s\n", k.second, k.first.c_str());
242    std::printf("pool_determinism: %d format pairs, %ld checks, %d failures -> %s\n", pairs, g_checks, g_fail, g_fail ? "FAIL" : "PASS");
243    return g_fail ? 1 : 0;
244}