okami.mom/strata

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

Niko1221Merge f-dsv41-rel (0be62ccad) into v0.2.3.1: DeepSeek V4.1-Flash on top of the released 0.2.3 line28ce98bf1

main
28.2 KiB564 linesraw
1// tools/trellis/tqenc_test.cpp - tests of the trellis encoder (tqenc.hpp) against Strata's own CPU decoder
2// (src/kernels/cpu/tq_states.hpp, tq_cpu.cpp: scalar / AVX2 / AVX-512 kernels).  Build and run: tools/trellis/build.sh test.
3//
4//   T1  fp16 conversion (all 65536 halves, random floats vs the hardware where F16C exists)
5//   T2  the encoder's codebook == the decoder's state table (bit for bit, 32768 x 4)
6//   T3  random streams: block_state (bit by bit) == tq_states.hpp; every window obeys the shift-trellis relation,
7//       circularly (so a legal path = the chain relation + the closure state(31) -> state(0)); pack(unpack(s)) == s
8//   T4  the Viterbi pass == a naive DP written from the legality relation (every state, every predecessor), for a fixed
9//       start group (tail-biting), a free start and a rotated start, with importance weights
10//   T5  exhaustive: every symbol value at every stream position round-trips through pack/decode
11//   T6  planted solutions: weights decoded from a random legal stream and scale; exact search at that scale must find
12//       error 0 and bit-identical weights; the approximate search is reported (recovery rate)
13//   T7  encode -> decode: the encoder's reconstruction == the decoder's weights bit for bit (tq_states + state table),
14//       and the CPU kernels' dot products against Q8_0 activations == the dense dot of those weights
15//   T8  specials: zero blocks, tiny / huge / extreme scales, constants, spikes, NaN / Inf, determinism over threads
16//   T9  quality on Gaussian blocks: SQNR against the rate-distortion bound 6.02 * K/4 dB; approximate vs exact search
17#include "tqenc.hpp"
18
19#include "strata/kernels/cpu/tq_cpu.hpp"
20#include "tq_states.hpp"
21
22#include <algorithm>
23#include <chrono>
24#include <cmath>
25#include <cstdio>
26#include <cstdlib>
27#include <cstring>
28#include <random>
29#include <string>
30#include <vector>
31
32#if defined(__F16C__)
33#include <immintrin.h>
34#endif
35
36namespace strata::kernels::cpu {
37bool cpu_avx512_ok() { return __builtin_cpu_supports("avx512f") && __builtin_cpu_supports("avx512bw") && __builtin_cpu_supports("avx512vl") && __builtin_cpu_supports("avx512vbmi") && __builtin_cpu_supports("avx512vnni"); }
38bool cpu_avx2_ok() { return __builtin_cpu_supports("avx2") && __builtin_cpu_supports("fma"); }
39}  // namespace strata::kernels::cpu
40
41using namespace tqenc;
42namespace kc = strata::kernels::cpu;
43
44static int g_fail = 0, g_checks = 0;
45#define CHECK(cond, ...)                                                                          \
46    do {                                                                                          \
47        ++g_checks;                                                                               \
48        if (!(cond)) {                                                                            \
49            ++g_fail;                                                                             \
50            std::printf("  FAIL %s:%d  %s  ", __FILE__, __LINE__, #cond);                         \
51            std::printf(__VA_ARGS__);                                                             \
52            std::printf("\n");                                                                    \
53        }                                                                                         \
54    } while (0)
55
56static const int kTypes[7] = {TQ2_T, TQK6, TQK7, TQK5X, TQK4X, TQK5T, TQK4T};
57static const char* tname(int t) {
58    return t == TQ2_T ? "TQ2_T" : t == TQK6 ? "TQK6" : t == TQK7 ? "TQK7" : t == TQK5X ? "TQK5X" : t == TQK4X ? "TQK4X" : t == TQK5T ? "TQK5T" : "TQK4T";
59}
60
61template <int KB>
62static void states_repo(const uint8_t* qs, uint32_t* st) { kc::tq_detail::tq_states<KB>(qs, st); }
63static void states_repo_k(int K, const uint8_t* qs, uint32_t* st) {
64    switch (K) {
65        case 8: states_repo<8>(qs, st); break;
66        case 7: states_repo<7>(qs, st); break;
67        case 6: states_repo<6>(qs, st); break;
68        case 5: states_repo<5>(qs, st); break;
69        default: states_repo<4>(qs, st); break;
70    }
71}
72
73static std::mt19937_64 rng(12345);
74static float gauss() { static std::normal_distribution<float> n(0.f, 1.f); return n(rng); }
75
76// chain relation between consecutive steps, circularly: returns true when state(t) and state(t') obey the shift trellis
77static bool chain_ok(int type, const uint32_t* st) {
78    const int K = type_kbits(type);
79    for (int t = 0; t < 32; ++t) {
80        if (type == TQ2_T) {   // state(t) = ((state(t-1) & 0x7f) << 8) | byte
81            const int tp = (t + 31) & 31;
82            if ((st[t] >> 8) != (st[tp] & 0x7f)) return false;
83        } else {               // u = 31 - t; state(u+1) low (15-K) bits = state(u) >> K, i.e. step t-1 follows step t
84            const int tp = (t + 31) & 31;
85            if ((st[tp] & ((1u << (15 - K)) - 1u)) != (st[t] >> K)) return false;
86        }
87    }
88    return true;
89}
90
91static void t1() {
92    std::printf("T1 fp16\n");
93    for (uint32_t h = 0; h < 65536; ++h) {
94        const float f = half_to_float((uint16_t) h);
95        if (std::isnan(f)) continue;
96        CHECK(float_to_half(f) == (uint16_t) h || (h == 0x8000 && float_to_half(f) == 0x8000), "half %04x", h);
97    }
98#if defined(__F16C__)
99    int bad = 0;
100    std::uniform_real_distribution<float> u(-1.f, 1.f);
101    for (int i = 0; i < 4000000; ++i) {
102        float f = u(rng) * std::pow(2.f, (float) (int) (rng() % 50) - 30.f);
103        if (i % 7 == 0) f = std::ldexp(u(rng), -25 + (int) (rng() % 6));   // subnormal range and its ties
104        if (i % 11 == 0) f = std::ldexp(u(rng), 14 + (int) (rng() % 3));   // the overflow edge
105        const uint16_t hw = _cvtss_sh(f, _MM_FROUND_TO_NEAREST_INT);
106        bad += float_to_half(f) != hw;
107    }
108    CHECK(bad == 0, "float_to_half vs F16C: %d differ", bad);
109#endif
110}
111
112static void t2() {
113    std::printf("T2 codebook == decoder table\n");
114    for (int type : kTypes) {
115        const int16_t* a = codebook_table(type);
116        const int16_t* b = kc::tq_state_table_for(type);
117        CHECK(std::memcmp(a, b, 32768 * 4 * sizeof(int16_t)) == 0, "%s: encoder and decoder tables differ", tname(type));
118    }
119    // the computed codebook: its own definition, evaluated bit by bit here (not through tq_computed.hpp), is what both use
120    {
121        const int16_t* c = codebook_table(TQK5X);
122        int bad = 0, big = 0;
123        for (uint32_t s = 0; s < 32768; ++s)
124            for (int i = 0; i < 2; ++i) {
125                const uint32_t A[2] = {89226354u, 0x9E3779B1u}, B[2] = {64248484u, 0x7F4A7C15u};
126                const uint32_t r = ((s * A[i] + B[i]) & 0x8FFF8FFFu) ^ 0x3B603B60u;
127                for (int hw = 0; hw < 2; ++hw) {
128                    const uint16_t h = (uint16_t) (hw ? r >> 16 : r & 0xffff);
129                    const float v = half_to_float(h) * 8192.0f;
130                    bad += c[4 * s + 2 * i + hw] != (int16_t) v || v != std::floor(v);
131                    big += std::fabs(v) >= 16384.0f || std::fabs(v) < 1023.0f;
132                }
133            }
134        CHECK(bad == 0, "computed codebook differs from its definition (%d)", bad);
135        CHECK(big == 0, "computed codebook value out of [0.125, 2) (%d)", big);
136        // the distribution: rms and the share of the weights below / above one
137        double ss = 0;
138        for (int i = 0; i < 32768 * 4; ++i) ss += (double) c[i] * c[i];
139        std::printf("  computed codebook: rms %.4f (table: %.4f), all values exact integers at 2^13\n", std::sqrt(ss / (32768.0 * 4)) / 8192.0, 1.072);
140    }
141}
142
143static void t3() {
144    std::printf("T3 states of random streams\n");
145    for (int type : kTypes) {
146        const int K = type_kbits(type), nb = 4 * K;
147        int bad_states = 0, bad_chain = 0, bad_pack = 0;
148        for (int it = 0; it < 20000; ++it) {
149            uint8_t qs[32];
150            for (int i = 0; i < nb; ++i) qs[i] = (uint8_t) rng();
151            uint32_t sr[32];
152            states_repo_k(K, qs, sr);
153            uint32_t sm[32];
154            for (int t = 0; t < 32; ++t) sm[t] = block_state(type, qs, t);
155            bad_states += std::memcmp(sr, sm, sizeof sr) != 0;
156            bad_chain += !chain_ok(type, sm);
157            // pack(unpack): processing order p -> step t
158            uint16_t by_pos[32];
159            for (int p = 0; p < 32; ++p) by_pos[p] = (uint16_t) sm[type == TQ2_T ? p : 31 - p];
160            uint8_t q2[32];
161            debug_pack(type, by_pos, q2);
162            // TQ2_T's bit 7 of each byte is part of the stream but the state uses only 15 bits of two bytes: bit 7 of
163            // qs[t] is in state(t) (bit 7), so it survives; every stream bit is in some state
164            bad_pack += std::memcmp(qs, q2, nb) != 0;
165        }
166        std::printf("  %-6s states vs tq_states.hpp: %d bad, chain relation: %d bad, pack(unpack): %d bad\n", tname(type),
167                    bad_states, bad_chain, bad_pack);
168        CHECK(bad_states == 0 && bad_chain == 0 && bad_pack == 0, "%s", tname(type));
169    }
170}
171
172// naive DP from the legality relation, one pass; same conventions as debug_viterbi
173static float naive(int type, const float (*T)[4], const float (*H)[4], int rot, int fixed_c, uint16_t* st_out) {
174    const int K = type_kbits(type);
175    const bool t2 = type == TQ2_T;
176    const int G = debug_groups(type);
177    std::vector<std::vector<float>> D(32, std::vector<float>(32768, 1e30f));
178    std::vector<std::vector<int>> B(32, std::vector<int>(32768, -1));
179    auto cost = [&](int p, uint32_t s) {
180        const float* c = codebook_state(type, s);
181        float e = 0;
182        for (int j = 0; j < 4; ++j) { const float d = T[p][j] - c[j]; e += H[p][j] * d * d; }
183        return e;
184    };
185    auto legal = [&](uint32_t prev, uint32_t next) {   // next may follow prev
186        return t2 ? (next >> 8) == (prev & 0x7f) : (next & (uint32_t) (G - 1)) == (prev >> K);
187    };
188    for (uint32_t s = 0; s < 32768; ++s) {
189        const bool ok = fixed_c < 0 || (t2 ? (int) (s >> 8) == fixed_c : (int) (s & (G - 1)) == fixed_c);
190        if (ok) D[0][s] = cost(rot & 31, s);
191    }
192    for (int q = 1; q < 32; ++q)
193        for (uint32_t s = 0; s < 32768; ++s) {
194            float best = 1e30f;
195            int arg = -1;
196            // enumerate the predecessors from the relation (all prev with legal(prev, s)): scan the 2^K candidates
197            const int n = 1 << K;
198            for (int y = 0; y < (t2 ? 256 : n); ++y) {
199                const uint32_t prev = t2 ? ((uint32_t) y << 7) | (s >> 8) : (((s & (uint32_t) (G - 1)) << K) | (uint32_t) y);
200                if (!legal(prev, s)) continue;
201                if (D[q - 1][prev] < best) { best = D[q - 1][prev]; arg = (int) prev; }
202            }
203            if (arg >= 0) { D[q][s] = best + cost((rot + q) & 31, s); B[q][s] = arg; }
204        }
205    float best = 1e30f;
206    int bs = -1;
207    for (uint32_t s = 0; s < 32768; ++s) {
208        const bool ok = fixed_c < 0 || (t2 ? (int) (s & 0x7f) == fixed_c : (int) (s >> K) == fixed_c);
209        if (ok && D[31][s] < best) { best = D[31][s]; bs = (int) s; }
210    }
211    if (bs < 0) return 1e30f;
212    int s = bs;
213    for (int q = 31; q >= 0; --q) {
214        st_out[(rot + q) & 31] = (uint16_t) s;
215        if (q > 0) s = B[q][s];
216    }
217    return best;
218}
219
220static void t4() {
221    std::printf("T4 Viterbi vs naive DP\n");
222    for (int type : kTypes) {
223        const int G = debug_groups(type);
224        double worst = 0;
225        int cases = 0;
226        for (int trial = 0; trial < 3; ++trial) {
227            float T[32][4], H[32][4];
228            for (int p = 0; p < 32; ++p)
229                for (int j = 0; j < 4; ++j) {
230                    T[p][j] = gauss() * (trial == 2 ? 2.5f : 1.0f);
231                    H[p][j] = trial == 0 ? 1.f : 0.1f + std::fabs(gauss());
232                }
233            struct Case { int rot, c; };
234            Case cs[3] = {{0, (int) (rng() % G)}, {0, -1}, {13, -1}};
235            for (const Case& cc : cs) {
236                uint16_t sa[32], sb[32];
237                const float a = debug_viterbi(type, T, H, cc.rot, cc.c, sa);
238                const float b = naive(type, T, H, cc.rot, cc.c, sb);
239                const double rel = std::fabs(a - b) / std::max(1e-6f, b);
240                worst = std::max(worst, rel);
241                CHECK(rel < 2e-5, "%s trial %d rot %d c %d: viterbi %.6f naive %.6f", tname(type), trial, cc.rot, cc.c, a, b);
242                // the returned path is legal and its own cost is the reported cost
243                uint32_t sm[32];
244                uint8_t qs[32];
245                debug_pack(type, sa, qs);
246                for (int t = 0; t < 32; ++t) sm[t] = block_state(type, qs, t);
247                bool same = true;
248                for (int p = 0; p < 32; ++p) {
249                    const uint32_t d = sm[type == TQ2_T ? p : 31 - p];
250                    if (cc.rot == 0 || cc.c < 0) {
251                        // a free rotated pass is a legal chain only if the stream closes; compare only closed ones
252                    }
253                    same = same && (cc.c < 0 ? true : d == sa[p]);
254                }
255                if (cc.c >= 0) CHECK(same, "%s tail-biting path does not decode to its own states", tname(type));
256                double sum = 0;
257                for (int q = 0; q < 32; ++q) {
258                    const int p = (cc.rot + q) & 31;
259                    const float* c = codebook_state(type, sa[p]);
260                    for (int j = 0; j < 4; ++j) { const double d = T[p][j] - c[j]; sum += H[p][j] * d * d; }
261                }
262                CHECK(std::fabs(sum - a) < 1e-3 * std::max(1.0, (double) a), "path cost %.6f vs reported %.6f", sum, a);
263                ++cases;
264            }
265        }
266        std::printf("  %-6s %d cases, worst relative cost difference %.2e\n", tname(type), cases, worst);
267    }
268}
269
270static void t5() {
271    std::printf("T5 every symbol value at every position\n");
272    for (int type : kTypes) {
273        const int K = type_kbits(type), nb = 4 * K;
274        long bad = 0, n = 0;
275        if (type == TQ2_T) {
276            for (int pos = 0; pos < 32; ++pos)
277                for (int x = 0; x < 256; ++x) {
278                    uint8_t qs[32];
279                    for (int i = 0; i < nb; ++i) qs[i] = (uint8_t) rng();
280                    qs[pos] = (uint8_t) x;
281                    uint32_t sm[32];
282                    for (int t = 0; t < 32; ++t) sm[t] = block_state(type, qs, t);
283                    uint16_t bp[32];
284                    for (int p = 0; p < 32; ++p) bp[p] = (uint16_t) sm[p];
285                    uint8_t q2[32];
286                    debug_pack(type, bp, q2);
287                    bad += std::memcmp(qs, q2, nb) != 0 || !chain_ok(type, sm);
288                    ++n;
289                }
290        } else {
291            for (int u = 0; u < 32; ++u)
292                for (int x = 0; x < (1 << K); ++x) {
293                    uint8_t qs[32];
294                    for (int i = 0; i < nb; ++i) qs[i] = (uint8_t) rng();
295                    // overwrite symbol u
296                    for (int b = 0; b < K; ++b) {
297                        const int bit = u * K + b;
298                        qs[bit >> 3] = (uint8_t) ((qs[bit >> 3] & ~(1u << (bit & 7))) | (((x >> b) & 1u) << (bit & 7)));
299                    }
300                    uint32_t sm[32];
301                    for (int t = 0; t < 32; ++t) sm[t] = block_state(type, qs, t);
302                    // symbol u is the low K bits of the state of step 31 - u
303                    bad += (int) (sm[31 - u] & ((1u << K) - 1u)) != x;
304                    uint16_t bp[32];
305                    for (int p = 0; p < 32; ++p) bp[p] = (uint16_t) sm[31 - p];
306                    uint8_t q2[32];
307                    debug_pack(type, bp, q2);
308                    bad += std::memcmp(qs, q2, nb) != 0 || !chain_ok(type, sm);
309                    ++n;
310                }
311        }
312        std::printf("  %-6s %ld cases, %ld bad\n", tname(type), n, bad);
313        CHECK(bad == 0, "%s", tname(type));
314    }
315}
316
317static void t6() {
318    std::printf("T6 planted solutions\n");
319    for (int type : kTypes) {
320        const int K = type_kbits(type), nb = 4 * K, bb = block_bytes(type);
321        const int N = (type == TQK4X ? 12 : 30);
322        int exact_ok = 0, approx_ok1 = 0, approx_ok3 = 0;
323        double approx_err_sum = 0, wsum = 0;
324        for (int it = 0; it < N; ++it) {
325            std::vector<uint8_t> blk(bb);
326            const float dsc = std::ldexp(0.5f + (float) (rng() % 1000) / 1000.f, -6 + (int) (rng() % 10));
327            const uint16_t dh = float_to_half(dsc);
328            blk[0] = (uint8_t) (dh & 255);
329            blk[1] = (uint8_t) (dh >> 8);
330            // a legal stream: any bytes are legal (every stream is a closed cycle by construction); for TQ2_T too
331            for (int i = 0; i < nb; ++i) blk[2 + i] = (uint8_t) rng();
332            std::vector<float> w(128);
333            decode_blocks(type, blk.data(), 1, w.data());
334            for (float x : w) wsum += (double) x * x;
335            Params p;
336            p.fixed_scale = dh;
337            std::vector<uint8_t> out(bb);
338            p.exact = 1;
339            BlockResult r = encode_block(type, w.data(), nullptr, out.data(), p);
340            std::vector<float> w2(128);
341            decode_blocks(type, out.data(), 1, w2.data());
342            const bool same = std::memcmp(w.data(), w2.data(), 512) == 0;
343            exact_ok += (r.err == 0.0 && same);
344            CHECK(r.err == 0.0 && same, "%s exact search missed a planted solution (err %g)", tname(type), r.err);
345            p.exact = 0;
346            p.ncand = 1;
347            r = encode_block(type, w.data(), nullptr, out.data(), p);
348            approx_ok1 += r.err == 0.0;
349            approx_err_sum += r.err;
350            p.ncand = 3;
351            r = encode_block(type, w.data(), nullptr, out.data(), p);
352            approx_ok3 += r.err == 0.0;
353        }
354        std::printf("  %-6s exact: %d/%d recovered; approximate (rotation 16): %d/%d (err/energy %.2e); best of 3 rotations: %d/%d\n",
355                    tname(type), exact_ok, N, approx_ok1, N, approx_err_sum / wsum, approx_ok3, N);
356    }
357}
358
359static uint16_t q8_scale(const std::vector<float>& x, int b) {
360    float amax = 0;
361    for (int j = 0; j < 32; ++j) amax = std::max(amax, std::fabs(x[32 * b + j]));
362    return float_to_half(amax / 127.f);
363}
364
365static void t7() {
366    std::printf("T7 encoder reconstruction == decoder, kernels vs dense\n");
367    for (int type : kTypes) {
368        const int K = type_kbits(type), bb = block_bytes(type);
369        const int rows = 24, n = 512, nbr = n / 128;
370        std::vector<float> w((size_t) rows * n);
371        for (int r = 0; r < rows; ++r)
372            for (int i = 0; i < n; ++i) {
373                float v = gauss() * 0.02f * (1.f + (r % 5));
374                if (r == 3) v = (i % 97 == 0) ? 1.5f : 0.001f * gauss();   // spiky row
375                if (r == 4) v = 0.f;                                          // zero row
376                if (r == 5) v *= 300.f;                                       // big
377                w[(size_t) r * n + i] = v;
378            }
379        std::vector<uint8_t> enc((size_t) rows * nbr * bb);
380        int64_t nf = 0, zb = 0;
381        std::vector<double> errs((size_t) rows * nbr);
382        Params p;
383        const double tot = encode_blocks(type, w.data(), nullptr, (int64_t) rows * nbr, enc.data(), p, 8, errs.data(), &nf, &zb);
384        (void) tot;
385        // decoder reference: tq_states.hpp + the state table
386        const int16_t* tab = kc::tq_state_table_for(type);
387        std::vector<float> ref((size_t) rows * n), ours((size_t) rows * n);
388        for (int64_t b = 0; b < (int64_t) rows * nbr; ++b) {
389            const uint8_t* blk = enc.data() + b * bb;
390            const float d = kc::tq_detail::tq_half_to_float(kc::tq_detail::tq_ld16(blk));
391            uint32_t st[32];
392            states_repo_k(K, blk + 2, st);
393            for (int t = 0; t < 32; ++t)
394                for (int j = 0; j < 4; ++j) ref[b * 128 + 4 * t + j] = d * ((float) tab[4 * st[t] + j] * (1.0f / 8192.0f));
395        }
396        decode_blocks(type, enc.data(), (int64_t) rows * nbr, ours.data());
397        CHECK(std::memcmp(ref.data(), ours.data(), ref.size() * 4) == 0, "%s decode != tq_states + state table", tname(type));
398        // the encoder's own error equals the error of the decoded weights
399        double worst = 0;
400        for (int64_t b = 0; b < (int64_t) rows * nbr; ++b) {
401            double e = 0;
402            for (int i = 0; i < 128; ++i) { const double d = (double) w[b * 128 + i] - ref[b * 128 + i]; e += d * d; }
403            worst = std::max(worst, std::fabs(e - errs[b]) / std::max(1e-30, e + errs[b]));
404        }
405        CHECK(worst < 1e-9, "%s encoder error != decoded error (%.3e)", tname(type), worst);
406        // kernels (scalar, AVX2, AVX-512 where present) vs the dense dot with the dequantized Q8_0 activation
407        std::vector<float> x(n);
408        for (auto& v : x) v = gauss();
409        std::vector<uint8_t> q8((size_t) (n / 32) * 34);
410        std::vector<float> xd(n);
411        for (int b = 0; b < n / 32; ++b) {
412            const uint16_t dh = q8_scale(x, b);
413            const float d = half_to_float(dh);
414            q8[34 * b] = (uint8_t) (dh & 255);
415            q8[34 * b + 1] = (uint8_t) (dh >> 8);
416            for (int j = 0; j < 32; ++j) {
417                const int q = d == 0.f ? 0 : (int) std::lround(x[32 * b + j] / d);
418                q8[34 * b + 2 + j] = (uint8_t) (int8_t) std::max(-127, std::min(127, q));
419                xd[32 * b + j] = d * (float) (int8_t) q8[34 * b + 2 + j];
420            }
421        }
422        const void* ap[1] = {q8.data()};
423        for (kc::TqIsa isa : {kc::TqIsa::scalar, kc::TqIsa::avx2, kc::TqIsa::avx512}) {
424            if (!kc::tq_isa_ok(isa)) continue;
425            std::vector<float> out(rows);
426            float* op[1] = {out.data()};
427            kc::tq_rows(isa, type, enc.data(), (size_t) nbr * bb, n, ap, 1, op, 0, rows);
428            double worst_rel = 0;
429            for (int r = 0; r < rows; ++r) {
430                double dsum = 0, mag = 0;
431                for (int i = 0; i < n; ++i) {
432                    dsum += (double) ref[(size_t) r * n + i] * xd[i];
433                    mag += std::fabs((double) ref[(size_t) r * n + i] * xd[i]);
434                }
435                worst_rel = std::max(worst_rel, std::fabs(dsum - out[r]) / (mag + 1e-30));
436            }
437            std::printf("  %-6s %-6s kernel vs dense dot of the decoded weights: worst error %.2e of sum|w a|\n", tname(type),
438                        kc::tq_isa_name(isa), worst_rel);
439            CHECK(worst_rel < 1e-5, "%s %s", tname(type), kc::tq_isa_name(isa));
440        }
441        std::printf("  %-6s decode == tq_states+table: bit-exact, %zu weights; zero blocks %lld\n", tname(type), ref.size(), (long long) zb);
442    }
443}
444
445static void t8() {
446    std::printf("T8 specials\n");
447    for (int type : kTypes) {
448        const int bb = block_bytes(type);
449        std::vector<uint8_t> out(bb), z(bb, 0);
450        std::vector<float> w(128), dec(128);
451        Params p;
452        // zero block
453        std::fill(w.begin(), w.end(), 0.f);
454        BlockResult r = encode_block(type, w.data(), nullptr, out.data(), p);
455        CHECK(r.status == 1 && out == z, "%s zero block must be canonical all-zero bytes", tname(type));
456        w[5] = -0.f;
457        r = encode_block(type, w.data(), nullptr, out.data(), p);
458        CHECK(r.status == 1 && out == z, "%s negative zero", tname(type));
459        decode_blocks(type, out.data(), 1, dec.data());
460        for (float v : dec) CHECK(v == 0.f, "zero block decodes to 0");
461        // scales: from the smallest subnormal weights to beyond fp16
462        const float mags[] = {1e-9f, 3e-8f, 1e-7f, 6e-5f, 1e-3f, 1.f, 100.f, 3000.f, 30000.f, 60000.f, 65000.f, 1e5f, 1e7f};
463        for (float mag : mags) {
464            for (int i = 0; i < 128; ++i) w[i] = mag * gauss();
465            r = encode_block(type, w.data(), nullptr, out.data(), p);
466            const uint16_t dh = (uint16_t) (out[0] | (out[1] << 8));
467            const float d = half_to_float(dh);
468            CHECK(std::isfinite(d) && d >= 0.f, "%s scale %g not finite for magnitude %g", tname(type), d, mag);
469            decode_blocks(type, out.data(), 1, dec.data());
470            double e = 0, en = 0;
471            bool fin = true;
472            for (int i = 0; i < 128; ++i) { fin &= std::isfinite(dec[i]); e += (w[i] - dec[i]) * (double) (w[i] - dec[i]); en += (double) w[i] * w[i]; }
473            CHECK(fin, "decoded nonfinite");
474            std::printf("  %-6s magnitude %-8g d=%-12g rel err %.3f status %d\n", tname(type), mag, d, e / std::max(en, 1e-300), r.status);
475            if (mag >= 1e-3f && mag <= 60000.f) CHECK(e / en < 0.5, "%s error too large at magnitude %g (%.3f)", tname(type), mag, e / en);
476        }
477        // constant, spike, alternating, power of two
478        for (int variant = 0; variant < 4; ++variant) {
479            for (int i = 0; i < 128; ++i)
480                w[i] = variant == 0 ? 0.37f : variant == 1 ? (i == 77 ? 5.f : 0.f) : variant == 2 ? (i & 1 ? 1.f : -1.f) : std::ldexp(1.f, -3);
481            r = encode_block(type, w.data(), nullptr, out.data(), p);
482            decode_blocks(type, out.data(), 1, dec.data());
483            double e = 0, en = 0;
484            for (int i = 0; i < 128; ++i) { e += (w[i] - dec[i]) * (double) (w[i] - dec[i]); en += (double) w[i] * w[i]; }
485            std::printf("  %-6s pattern %d rel err %.4f\n", tname(type), variant, e / en);
486            CHECK(e / en < 0.8, "%s pattern %d", tname(type), variant);
487        }
488        // non-finite input
489        for (int i = 0; i < 128; ++i) w[i] = gauss();
490        w[17] = INFINITY;
491        r = encode_block(type, w.data(), nullptr, out.data(), p);
492        CHECK(r.status == 2 && out == z, "%s inf input", tname(type));
493        w[17] = NAN;
494        r = encode_block(type, w.data(), nullptr, out.data(), p);
495        CHECK(r.status == 2 && out == z, "%s nan input", tname(type));
496    }
497    // determinism over thread counts
498    {
499        const int type = TQK6, nbl = 64, bb = block_bytes(type);
500        std::vector<float> w((size_t) nbl * 128);
501        for (auto& v : w) v = gauss();
502        std::vector<uint8_t> a((size_t) nbl * bb), b(a.size());
503        Params p;
504        encode_blocks(type, w.data(), nullptr, nbl, a.data(), p, 1, nullptr, nullptr, nullptr);
505        encode_blocks(type, w.data(), nullptr, nbl, b.data(), p, 7, nullptr, nullptr, nullptr);
506        CHECK(a == b, "1 thread vs 7 threads differ");
507    }
508}
509
510static void t9() {
511    std::printf("T9 quality on N(0,1) blocks (SQNR in dB; the rate-distortion limit of the K/4 bits per weight is 6.02 * K/4)\n");
512    for (int type : kTypes) {
513        const int K = type_kbits(type), bb = block_bytes(type);
514        const int nbl = (type == TQ2_T || type == TQK7) ? 256 : 384;
515        std::vector<float> w((size_t) nbl * 128);
516        for (auto& v : w) v = gauss();
517        std::vector<uint8_t> out((size_t) nbl * bb);
518        double en = 0;
519        for (float v : w) en += (double) v * v;
520        struct Cfg { const char* name; Params p; int th; };
521        Cfg cfgs[5];
522        cfgs[0] = {"1 pass, scale from rms", Params{0, 1, 0, 1, 0}, 8};
523        cfgs[1] = {"default (rot 16, 3 scale rounds)", Params{}, 8};
524        cfgs[2] = {"3 rotations, 3 scale rounds", Params{3, 3, 0, 1, 0}, 8};
525        cfgs[3] = {"3 rotations, 3 starting scales", Params{3, 3, 0, 3, 0}, 8};
526        int ncfg = 4;
527        for (int i = 0; i < ncfg; ++i) {
528            const auto t0 = std::chrono::steady_clock::now();
529            const double e = encode_blocks(type, w.data(), nullptr, nbl, out.data(), cfgs[i].p, cfgs[i].th, nullptr, nullptr, nullptr);
530            const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
531            const double sq = 10.0 * std::log10(en / e);
532            std::printf("  %-6s %-34s SQNR %.3f dB (limit %.2f, gap %.2f dB)  %.0f weights/s (%d threads)\n", tname(type),
533                        cfgs[i].name, sq, 6.0206 * K / 4.0, 6.0206 * K / 4.0 - sq, (double) nbl * 128 / sec, cfgs[i].th);
534        }
535        // approximate vs exact start group at the default scale rounds on a few blocks
536        {
537            const int nb2 = type == TQK4X ? 2 : 8;
538            Params pe;
539            pe.exact = 1;
540            pe.iters = 0;
541            Params pa;
542            pa.iters = 0;
543            const double ee = encode_blocks(type, w.data(), nullptr, nb2, out.data(), pe, 8, nullptr, nullptr, nullptr);
544            const double ea = encode_blocks(type, w.data(), nullptr, nb2, out.data(), pa, 8, nullptr, nullptr, nullptr);
545            std::printf("  %-6s tail-biting search, %d blocks, one scale: approximate error / exact error = %.4f\n", tname(type), nb2, ea / ee);
546            CHECK(ea >= ee * (1 - 1e-6), "approximate beat exact?");
547        }
548    }
549}
550
551int main(int argc, char** argv) {
552    const bool quick = argc > 1 && std::strcmp(argv[1], "--quick") == 0;
553    t1();
554    t2();
555    t3();
556    t5();
557    t4();
558    t6();
559    t7();
560    t8();
561    if (!quick) t9();
562    std::printf("\n%d checks, %d failures\n", g_checks, g_fail);
563    return g_fail ? 1 : 0;
564}