okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
10.2 KiB229 linesraw
1// src/kernels/cpu/tqp_cpu_test.cpp - the trellis CPU rows (tq_cpu.hpp) on synthetic blocks, with no ggml and no model:
2//
3//   * the pair-trellis types TQP5 / TQP6 / TQP7 (ggml 147-149, Gyro-L): the scalar kernel against a reference written
4//     here from the format definition (state t = the 16 stream bits that start at bit (63 - t) * K, LSB first,
5//     circular over 64 * K bits; the step's two weights are the first pair of the state's codebook entry), summed in
6//     double; then every ISA this CPU has (AVX2, AVX-512 takes the AVX2 pair kernel) bit for bit equal to the scalar
7//     kernel, for groups of 1..8 tokens, one row range or two, and for the fused gate/up rows;
8//   * the older trellis types (144-146): AVX2 / AVX-512 bit for bit equal to the scalar kernel (the pair types were
9//     added next to them: this shows they still agree), and their block sizes and K unchanged;
10//   * the type predicates (tq_supported, tq_kbits, tq_block_bytes) for every id 0..299: the answers the code gave
11//     before the pair types, plus 147-149.
12//
13// Random stream bytes are valid codes (any 15-bit state indexes the codebook).  CPU only.  Exit 0 = pass.
14#include "strata/kernels/cpu/tq_cpu.hpp"
15
16#include "tq_states.hpp"
17
18#include <cmath>
19#include <cstdint>
20#include <cstdio>
21#include <cstring>
22#include <random>
23#include <vector>
24
25using namespace strata::kernels::cpu;
26
27namespace {
28
29int g_fail = 0;
30
31void fail(const char* what, int a = 0, int b = 0) {
32    std::printf("  FAIL: %s %d %d\n", what, a, b);
33    ++g_fail;
34}
35
36// ---- the type predicates as they were before the pair types (the old formulas, copied)
37bool old_supported(int t) {
38    return t == 144 || t == 145 || t == 146 || t == kTqTypeK5X || t == kTqTypeK4X || t == kTqTypeK5T || t == kTqTypeK4T;
39}
40int old_kbits(int t) {
41    return t == 144 ? 8 : t == 145 ? 6 : t == 146 ? 7 : (t == kTqTypeK5X || t == kTqTypeK5T) ? 5 : (t == kTqTypeK4X || t == kTqTypeK4T) ? 4 : 0;
42}
43
44void check_predicates() {
45    for (int t = 0; t < 300; ++t) {
46        const bool pair = t >= 147 && t <= 149;
47        if (tq_supported(t) != (old_supported(t) || pair)) fail("tq_supported", t);
48        const int want_k = pair ? (t == 147 ? 5 : t == 148 ? 6 : 7) : old_kbits(t);
49        if (tq_kbits(t) != want_k) fail("tq_kbits", t, tq_kbits(t));
50        const size_t want_b = pair ? (size_t) (2 + 8 * want_k) : (size_t) (2 + 4 * want_k);
51        if (tq_block_bytes(t) != want_b) fail("tq_block_bytes", t, (int) tq_block_bytes(t));
52    }
53    if (tq_block_bytes(144) != 34 || tq_block_bytes(145) != 26 || tq_block_bytes(146) != 30) fail("sizes of 144-146");
54    if (tq_block_bytes(147) != 42 || tq_block_bytes(148) != 50 || tq_block_bytes(149) != 58) fail("sizes of 147-149");
55    std::printf("predicates (ids 0..299): %s\n", g_fail ? "FAIL" : "ok");
56}
57
58// ---- synthetic data
59uint16_t random_half(std::mt19937& rng) {
60    std::uniform_int_distribution<int> ex(2, 8), man(0, 1023), sgn(0, 3);
61    return (uint16_t) ((sgn(rng) == 0 ? 0x8000 : 0) | (ex(rng) << 10) | man(rng));   // 2^-13 .. 2^-6
62}
63
64std::vector<uint8_t> random_rows(int type, int rows, int n, std::mt19937& rng, size_t& row_bytes) {
65    const size_t bs = tq_block_bytes(type);
66    row_bytes = bs * (size_t) (n / 128);
67    std::vector<uint8_t> w(row_bytes * (size_t) rows);
68    std::uniform_int_distribution<int> byte(0, 255);
69    for (auto& b : w) b = (uint8_t) byte(rng);
70    for (size_t o = 0; o < w.size(); o += bs) {
71        const uint16_t h = random_half(rng);
72        std::memcpy(&w[o], &h, 2);
73    }
74    return w;
75}
76
77// n values as Q8_0 blocks (fp16 d, 32 x int8): 34 bytes per 32 values
78std::vector<uint8_t> random_q8_0(int n, std::mt19937& rng, std::vector<float>& d, std::vector<int>& q) {
79    std::vector<uint8_t> a((size_t) (n / 32) * 34);
80    std::uniform_int_distribution<int> val(-127, 127), ex(8, 13), man(0, 1023);
81    d.assign((size_t) n / 32, 0.f);
82    q.assign((size_t) n, 0);
83    for (int b = 0; b < n / 32; ++b) {
84        const uint16_t h = (uint16_t) ((ex(rng) << 10) | man(rng));
85        std::memcpy(&a[(size_t) b * 34], &h, 2);
86        d[(size_t) b] = strata::kernels::cpu::tq_detail::tq_half_to_float(h);
87        for (int j = 0; j < 32; ++j) {
88            const int v = val(rng);
89            q[(size_t) b * 32 + j] = v;
90            a[(size_t) b * 34 + 2 + j] = (uint8_t) (int8_t) v;
91        }
92    }
93    return a;
94}
95
96// ---- the reference for the pair types, from the format definition (bit by bit, not the window code of the kernels)
97uint32_t ref_state(const uint8_t* qs, int K, int t) {
98    const int nbits = 64 * K;
99    uint32_t s = 0;
100    for (int b = 0; b < 16; ++b) {
101        const int pos = ((63 - t) * K + b) % nbits;
102        s |= (uint32_t) ((qs[pos >> 3] >> (pos & 7)) & 1) << b;
103    }
104    return s & 0x7FFFu;
105}
106
107// w . a in double; `bound` = the sum of the absolute terms (the scale of the float rounding allowed)
108double ref_dot(int type, const uint8_t* row, int n, const std::vector<float>& d, const std::vector<int>& q, double& bound) {
109    const int K = tq_kbits(type);
110    const int16_t* tab = tq_state_table();
111    const size_t bs = tq_block_bytes(type);
112    double sum = 0, abs_sum = 0;
113    for (int i = 0; i < n / 128; ++i) {
114        const uint8_t* blk = row + (size_t) i * bs;
115        uint16_t hd;
116        std::memcpy(&hd, blk, 2);
117        const double dw = strata::kernels::cpu::tq_detail::tq_half_to_float(hd);
118        uint32_t st[64];
119        for (int t = 0; t < 64; ++t) st[t] = ref_state(blk + 2, K, t);
120        for (int k = 0; k < 4; ++k) {
121            long long s = 0, sa = 0;
122            for (int j = 0; j < 32; ++j) {
123                const int v = 32 * k + j;                    // weight v of the block: step v / 2, element v & 1 of the first pair
124                const int w16 = tab[4 * st[v >> 1] + (v & 1)];
125                s += (long long) w16 * q[(size_t) 128 * i + v];
126                sa += (long long) std::abs(w16) * std::abs(q[(size_t) 128 * i + v]);
127            }
128            const double sc = dw * d[(size_t) 4 * i + k];
129            sum += sc * (double) s;
130            abs_sum += std::fabs(sc) * (double) sa;
131        }
132    }
133    bound = abs_sum / 8192.0;
134    return sum / 8192.0;
135}
136
137bool same_bits(const float* a, const float* b, size_t n) { return std::memcmp(a, b, n * sizeof(float)) == 0; }
138
139constexpr int NT = kTqMaxTokens;
140
141struct Case {
142    int type, rows, n;
143    std::vector<uint8_t> w;
144    size_t rb = 0;
145    std::vector<std::vector<uint8_t>> act;
146    std::vector<std::vector<float>> d;
147    std::vector<std::vector<int>> q;
148    const void* ap[NT];
149    Case(int type_, int rows_, int n_, uint32_t seed) : type(type_), rows(rows_), n(n_) {
150        std::mt19937 rng(seed);
151        w = random_rows(type, rows, n, rng, rb);
152        act.resize(NT); d.resize(NT); q.resize(NT);
153        for (int t = 0; t < NT; ++t) {
154            act[t] = random_q8_0(n, rng, d[t], q[t]);
155            ap[t] = act[t].data();
156        }
157    }
158    void run(TqIsa isa, int nt, const void* const* a, std::vector<float>& o) const {
159        o.assign((size_t) nt * rows, 0.f);
160        float* op[NT];
161        for (int t = 0; t < nt; ++t) op[t] = o.data() + (size_t) t * rows;
162        tq_rows(isa, type, w.data(), rb, n, a, nt, op, 0, rows / 3);       // two row ranges, as the pool splits them
163        tq_rows(isa, type, w.data(), rb, n, a, nt, op, rows / 3, rows);
164    }
165};
166
167void check_type(int type, bool reference) {
168    Case c(type, 37, 1280, 1000u + (uint32_t) type);
169    std::vector<float> ref, got;
170    c.run(TqIsa::scalar, NT, c.ap, ref);
171    int bad = 0;
172    if (reference) {   // the pair types: the scalar kernel against the definition
173        double worst = 0;
174        for (int t = 0; t < NT; ++t)
175            for (int r = 0; r < c.rows; ++r) {
176                double bound = 0;
177                const double want = ref_dot(type, c.w.data() + (size_t) r * c.rb, c.n, c.d[t], c.q[t], bound);
178                const double err = std::fabs((double) ref[(size_t) t * c.rows + r] - want);
179                worst = std::fmax(worst, bound > 0 ? err / bound : err);
180                if (err > 2e-5 * bound + 1e-30) ++bad;
181            }
182        std::printf("type %d scalar vs the definition (double): %d of %d outside 2e-5 of the term sum, worst %.2e\n", type, bad,
183                    NT * c.rows, worst);
184        if (bad) fail("scalar kernel differs from the definition", type);
185    }
186    for (TqIsa isa : {TqIsa::avx2, TqIsa::avx512}) {
187        if (!tq_isa_ok(isa)) { std::printf("type %d %-6s not on this CPU: skipped\n", type, tq_isa_name(isa)); continue; }
188        bool ok = true;
189        for (int nt = 1; nt <= NT; ++nt)
190            for (int t0 = 0; t0 + nt <= NT; t0 += nt) {
191                c.run(isa, nt, c.ap + t0, got);
192                ok = ok && same_bits(got.data(), ref.data() + (size_t) t0 * c.rows, (size_t) nt * c.rows);
193            }
194        std::printf("type %d %-6s groups of 1..%d tokens vs the scalar kernel: %s\n", type, tq_isa_name(isa), NT,
195                    ok ? "bitwise equal" : "DIFFERENT");
196        if (!ok) fail("ISA differs from scalar", type);
197    }
198    // the fused gate/up rows: gate rows at the blob, up rows after them
199    {
200        std::vector<uint8_t> blob = c.w;
201        std::mt19937 rng(77u + (uint32_t) type);
202        size_t rb2 = 0;
203        const auto up = random_rows(type, c.rows, c.n, rng, rb2);
204        blob.insert(blob.end(), up.begin(), up.end());
205        const size_t up_off = c.w.size();
206        std::vector<float> ff0((size_t) NT * c.rows), ff1((size_t) NT * c.rows);
207        float* p0[NT]; float* p1[NT];
208        for (int t = 0; t < NT; ++t) { p0[t] = ff0.data() + (size_t) t * c.rows; p1[t] = ff1.data() + (size_t) t * c.rows; }
209        tq_gu_rows(TqIsa::scalar, type, blob.data(), c.rb, up_off, c.n, c.ap, NT, p0, 0, c.rows);
210        bool ok = true;
211        for (TqIsa isa : {TqIsa::avx2, TqIsa::avx512}) {
212            if (!tq_isa_ok(isa)) continue;
213            tq_gu_rows(isa, type, blob.data(), c.rb, up_off, c.n, c.ap, NT, p1, 0, c.rows);
214            ok = ok && same_bits(ff0.data(), ff1.data(), ff0.size());
215        }
216        std::printf("type %d gate/up rows, every ISA vs scalar: %s\n", type, ok ? "bitwise equal" : "DIFFERENT");
217        if (!ok) fail("gate/up rows differ", type);
218    }
219}
220
221}  // namespace
222
223int main() {
224    check_predicates();
225    for (int type : {147, 148, 149}) check_type(type, true);
226    for (int type : {144, 145, 146}) check_type(type, false);
227    std::printf("tqp_cpu_test: %d failures\n", g_fail);
228    return g_fail ? 1 : 0;
229}