okami.mom/strata

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

Niko1221Strata: Qwen3.8-Flash-Next on a 12-24 GB NVIDIA GPU + 64 GB RAM, one-click install01529aaa8

main
8.2 KiB184 linesraw
1// src/kernels/cpu/expert_parity.cpp - P2.S3's test for the CPU expert path.
2//
3// WHAT IS BEING CHECKED, and the two tolerances are different questions:
4//
5//   1. VNNI vs the scalar oracle with `quant_acts = true`.  Both sides consume the SAME INT8 activation
6//      values, so the only difference is FP32 evaluation ORDER.  This is the check that proves the KERNEL -
7//      the VNNI unpack, the 32-element chunk split, the scalar correction term - and P2.S3 asks for 3e-3.
8//   2. VNNI vs the oracle with `quant_acts = false`.  Now the oracle uses exact FP32 activations, so the gap
9//      IS the activation contract (`docs/activation-contract.md`).  It is REPORTED, not asserted tightly,
10//      because it is a property of the model's quantisation and not of this code.
11//
12// The activation contract is asserted OBSERVABLE between the two: if rounding the activation to Q8_1 made no
13// difference, then one of the two paths is not doing what it claims and check 1 would be vacuous.
14//
15// A SELF-CONSISTENT TEST CANNOT CATCH A WRONG FILE OFFSET.  Both sides read the same blob, so pointing at the
16// wrong expert would still agree perfectly.  What is checked instead is structural: the blob must decode to
17// finite, non-zero scales, and the blob at a DIFFERENT layer must be different data - which is what a wrong
18// stride would break.
19#include "strata/kernels/cpu/expert.hpp"
20
21#include <cmath>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25#include <random>
26#include <string>
27#include <vector>
28
29namespace cpu = strata::kernels::cpu;
30
31namespace {
32
33/// Normalised L1 difference, with the reference magnitude returned for reporting.
34double rel_l1(const float* a, const float* b, int n, double* mag_out = nullptr) {
35    double d = 0, mag = 0;
36    for (int i = 0; i < n; ++i) {
37        d += std::fabs((double) a[i] - (double) b[i]);
38        mag += std::fabs((double) a[i]);
39    }
40    if (mag_out) *mag_out = mag / n;
41    return d / (mag > 1e-30 ? mag : 1e-30);
42}
43
44bool read_blob(const char* path, long long index, std::vector<uint8_t>& out) {
45    out.assign(cpu::BLOB, 0);
46    std::FILE* f = std::fopen(path, "rb");
47    if (!f) return false;
48#if defined(_MSC_VER)
49    if (_fseeki64(f, (long long) index * (long long) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; }
50#else
51    if (fseeko(f, (off_t) index * (off_t) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; }
52#endif
53    const size_t got = std::fread(out.data(), 1, out.size(), f);
54    std::fclose(f);
55    return got == out.size();
56}
57
58/// The fp16 scale at a byte offset, decoded by the SAME rule the kernel uses.  Used only for the structural
59/// sanity check, so it is deliberately a second, independent transcription of the three lines in question.
60float f16_at(const std::vector<uint8_t>& b, size_t off) {
61    uint16_t h;
62    std::memcpy(&h, b.data() + off, 2);
63    const uint32_t sign = (uint32_t) (h >> 15) & 1u;
64    uint32_t exp = (h >> 10) & 0x1Fu, man = h & 0x3FFu, f;
65    if (exp == 0) {
66        if (man == 0) f = sign << 31;
67        else { exp = 127 - 15 + 1; while (!(man & 0x400u)) { man <<= 1; --exp; } man &= 0x3FFu;
68               f = (sign << 31) | (exp << 23) | (man << 13); }
69    } else if (exp == 31) {
70        f = (sign << 31) | 0x7F800000u | (man << 13);
71    } else {
72        f = (sign << 31) | ((exp - 15 + 127) << 23) | (man << 13);
73    }
74    float o;
75    std::memcpy(&o, &f, 4);
76    return o;
77}
78
79}  // namespace
80
81int main(int argc, char** argv) {
82    bool selftest = false;
83    const char* path = "pack/full/experts.bin";
84    long long layer = 0, expert = 0;
85    for (int i = 1; i < argc; ++i) {
86        const std::string a = argv[i];
87        if (a == "--selftest") selftest = true;
88        else if (a == "--file" && i + 1 < argc) path = argv[++i];
89        else if (a == "--layer" && i + 1 < argc) layer = std::atoll(argv[++i]);
90        else if (a == "--expert" && i + 1 < argc) expert = std::atoll(argv[++i]);
91        else { std::fprintf(stderr, "usage: expert_parity [--selftest] [--file P] [--layer N] [--expert N]\n");
92               return 2; }
93    }
94
95    int bad = 0;
96
97    // ---- the CPU must be able to run the kernel, and the report must say WHICH feature is missing
98    const cpu::CpuFeatures feat = cpu::cpu_features();
99    std::printf("  %-44s %s\n", "AVX512 F/BW/VL/VNNI/VBMI",
100                feat.usable() ? "all present" : feat.reason());
101    if (!feat.usable()) {
102        std::printf("      the VNNI path cannot run here; only the scalar oracle can be exercised.\n");
103        std::printf("      P2.S3's kernel check is SKIPPED, not passed.\n");
104        std::printf("\nexpert_parity: 0 failures, 1 SKIPPED\n");
105        return 0;
106    }
107
108    // ---- a real blob out of the pack: layer stride is 512 experts
109    const long long idx = layer * 512 + expert;
110    std::vector<uint8_t> blob;
111    if (!read_blob(path, idx, blob)) {
112        std::fprintf(stderr, "cannot read expert %lld (layer %lld) from %s\n", expert, layer, path);
113        return 2;
114    }
115
116    // ---- structural sanity, because the agreement checks below are self-consistent and would pass on the
117    //      wrong blob.  A mis-strided read lands on a different expert's data, which is still plausible Q2_0,
118    //      so the check that has teeth is the DIFFERENCE between layers.
119    {
120        int nonzero = 0;
121        float smin = 1e30f, smax = -1e30f;
122        for (int b = 0; b < cpu::SC_GU; ++b) {
123            const float s = f16_at(blob, cpu::O_GU_SCALES + (size_t) b * 2);
124            if (s != 0.f) ++nonzero;
125            smin = std::fmin(smin, std::fabs(s));
126            smax = std::fmax(smax, std::fabs(s));
127        }
128        const bool ok = nonzero > cpu::SC_GU / 2 && std::isfinite(smin) && std::isfinite(smax) && smax > 0.f;
129        std::printf("  %-44s %s (%d/%d non-zero, |s| in [%.4g, %.4g])\n", "blob decodes to live scales",
130                    ok ? "yes" : "*** NO ***", nonzero, cpu::SC_GU, (double) smin, (double) smax);
131        if (!ok) ++bad;
132    }
133    {
134        std::vector<uint8_t> other;
135        if (read_blob(path, (layer * 512 + expert) + 1, other)) {
136            long long diff = 0;
137            for (size_t i = 0; i < blob.size(); ++i) if (blob[i] != other[i]) ++diff;
138            const double frac = (double) diff / (double) blob.size();
139            const bool ok = frac > 0.1;
140            std::printf("  %-44s %s (%.1f%% of bytes differ)\n", "the next expert is different data",
141                        ok ? "yes" : "*** NO ***", frac * 100);
142            if (!ok) ++bad;
143        }
144    }
145
146    // ---- a realistic activation
147    std::mt19937 rng(4242);
148    std::normal_distribution<float> gauss(0.0f, 1.0f);
149    std::vector<float> x(cpu::H);
150    for (auto& v : x) v = gauss(rng);
151
152    cpu::ExpertScratch ws;
153    std::vector<float> vnni(cpu::H), scalar_q(cpu::H), scalar_fp(cpu::H);
154    cpu::s2_expert_vnni(blob.data(), x.data(), vnni.data(), ws);
155    cpu::s2_expert_scalar(blob.data(), x.data(), scalar_q.data(), true);
156    cpu::s2_expert_scalar(blob.data(), x.data(), scalar_fp.data(), false);
157
158    double mag = 0;
159    const double rel_kernel = rel_l1(scalar_q.data(), vnni.data(), cpu::H, &mag);
160    const double rel_contract = rel_l1(scalar_fp.data(), vnni.data(), cpu::H);
161    const double trap_contract = rel_l1(scalar_fp.data(), scalar_q.data(), cpu::H);
162
163    // ---- the activation contract must be OBSERVABLE, or check 1 is vacuous
164    {
165        const bool visible = trap_contract > 1e-4;
166        std::printf("  %-44s %s (%.4f%% apart)\n", "the Q8_1 activation contract is observable",
167                    visible ? "yes" : "*** NO ***", trap_contract * 100);
168        if (!visible) ++bad;
169    }
170
171    // ---- 1. the kernel, against an oracle fed the SAME activations
172    std::printf("  %-44s rel %.3e   (P2.S3 asks <= 3e-3, mean |ref| %.4f)\n", "VNNI vs scalar (INT8 acts)",
173                rel_kernel, mag);
174    if (!(rel_kernel <= 3e-3)) { std::printf("    *** over P2.S3's 3e-3 ***\n"); ++bad; }
175
176    // ---- 2. the activation contract's own cost, reported rather than asserted
177    std::printf("  %-44s rel %.3e   (the cost of the contract, REPORTED)\n",
178                "VNNI vs scalar (FP32 acts)", rel_contract);
179
180    std::printf("\nexpert_parity: %d failures (layer %lld expert %lld of %s)\n", bad, layer, expert, path);
181    if (bad) return 1;
182    if (selftest) std::printf("expert_parity OK\n");
183    return 0;
184}