okami.mom/strata

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

Niko1221Int3 fix (test programs only; four were already broken on MSVC in v0.2.9, gr_v3_screen is new): setenv / unsetenv / __builtin_popcount shims so a Windows build with tests ON compiles0d2ee8def

main
15.9 KiB315 linesraw
1// src/kernels/cpu/native_hadamard_test.cpp - APR port, stage 3: one Hadamard-folded trellis expert (TQ2_T / TQK6 /
2// TQK7, ggml types 144-146) on Strata's CPU path against llama.cpp's own graph for the same weights and input.
3//
4// Strata's path:  native_quant_act (signs, FWHT, Q8_0) -> native_gu_rows (ggml-cpu vec_dot + SwiGLU)
5//                 -> native_quant_h (signs, FWHT, Q8_0) -> native_down_rows
6// The reference:  the ops llama.cpp's build_lora_mm_id builds for a prism.hadamard weight - ggml_mul(x, signs),
7//                 llama_mul_mat_hadamard (reshape to [128, n/128], ggml_mul_mat(rot, .)), ggml_mul_mat(W', .) -
8//                 computed by ggml-cpu from the same checkout (STRATA_GGML_DIR = the agention llama.cpp fork).
9// The rotation itself is computed two different ways (FWHT here, a dense 128x128 matmul there), so the two outputs
10// agree to float rounding plus the odd Q8_0 rounding flip, not bit for bit; the test bounds the relative error.
11//
12//   native_hadamard_test                         synthetic: random W, rotated and quantized here; also checks the
13//                                                folded expert against the UNROTATED float expert (W x) and that
14//                                                skipping the rotation is caught
15//   native_hadamard_test --pack <dir> --gguf <file> [layer expert]...   real experts of a prism.hadamard GGUF
16//                                                (Gyro-S / Gyro-M) through the pack tools/iq_pack.py made of it
17#include "strata/kernels/cpu/hadamard.hpp"
18#include "strata/kernels/cpu/native_expert.hpp"
19#include "strata/kernels/cpu/expert_layout.hpp"
20#include "strata/kernels/cpu/pool.hpp"
21#include "strata/artifact/gguf_reader.hpp"
22
23#include "ggml.h"
24#include "ggml-cpu.h"
25
26#include <cmath>
27#include <cstdio>
28#include <cstdlib>
29#include <cstring>
30#include <algorithm>
31#include <random>
32#include <string>
33#include <vector>
34#if defined(_MSC_VER)   // MSVC has no __builtin_popcount
35#include <intrin.h>
36#define __builtin_popcount(x) __popcnt((unsigned) (x))
37#endif
38
39using namespace strata::kernels::cpu;
40
41namespace {
42
43constexpr int H = 2560, FF = 640, B = 128;
44
45struct Expert {
46    int gu_type = 0, d_type = 0;
47    std::vector<uint8_t> gate, up, down;   // ggml rows: gate/up [FF rows of H], down [H rows of FF]
48    std::vector<float> s_h, s_ff;          // sign vectors (empty: identity)
49};
50
51double rel(const std::vector<float>& a, const std::vector<float>& b) {
52    double num = 0, den = 0;
53    for (size_t i = 0; i < a.size(); ++i) {
54        num += (double) (a[i] - b[i]) * (a[i] - b[i]);
55        den += (double) b[i] * b[i];
56    }
57    return std::sqrt(num / (den > 0 ? den : 1));
58}
59
60float silu(float g) { return g / (1.f + std::exp(-g)); }
61
62// Strata's CPU path for one token; `loaded` = the layer's NativeFmt as expert_layout_load made it from a pack
63std::vector<float> strata_expert(const Expert& e, const std::vector<float>& x, bool rotate,
64                                 const NativeFmt* loaded = nullptr) {
65    NativeFmt f;
66    std::string err;
67    if (!native_fmt(e.gu_type, e.d_type, H, FF, f, err)) { std::fprintf(stderr, "native_fmt: %s\n", err.c_str()); std::exit(1); }
68    if (rotate && loaded) {
69        f = *loaded;
70    } else if (rotate) {
71        f.had_block = B;
72        f.had_gu = f.had_d = true;
73        f.gu_signs = e.s_h.empty() ? nullptr : e.s_h.data();
74        f.d_signs = e.s_ff.empty() ? nullptr : e.s_ff.data();
75    }
76    std::vector<uint8_t> blob(f.bytes);
77    std::memcpy(blob.data(), e.gate.data(), e.gate.size());
78    std::memcpy(blob.data() + f.up_off, e.up.data(), e.up.size());
79    std::memcpy(blob.data() + f.down_off, e.down.data(), e.down.size());
80    std::vector<uint8_t> act(kNativeActBytes), hq(kNativeHBytes);
81    std::vector<float> ff(FF), out(H);
82    native_quant_act(f, x.data(), act.data());
83    const void* a[1] = {act.data()};
84    float* ffp[1] = {ff.data()};
85    native_gu_rows(f, blob.data(), a, 1, ffp, 0, FF);
86    native_quant_h(f, ff.data(), hq.data());
87    const void* hp[1] = {hq.data()};
88    float* op[1] = {out.data()};
89    native_down_rows(f, blob.data(), hp, 1, op, 0, H);
90    return out;
91}
92
93// llama.cpp's graph for the same expert (the fork's build_lora_mm + llama_mul_mat_hadamard), one token
94std::vector<float> llama_expert(const Expert& e, const std::vector<float>& x) {
95    ggml_init_params ip = {(size_t) 256 << 20, nullptr, false};
96    ggml_context* ctx = ggml_init(ip);
97    // the normalized Sylvester-Walsh-Hadamard matrix exactly as llama_model_base builds prism.hadamard.128
98    ggml_tensor* rot = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, B, B);
99    float* R = (float*) rot->data;
100    const float scale = 1.0f / sqrtf((float) B);
101    for (uint32_t r = 0; r < (uint32_t) B; ++r)
102        for (uint32_t c = 0; c < (uint32_t) B; ++c) {
103            uint32_t p = r & c;
104            p ^= p >> 16; p ^= p >> 8; p ^= p >> 4; p ^= p >> 2; p ^= p >> 1;
105            R[r * B + c] = (p & 1) ? -scale : scale;
106        }
107    auto hadamard = [&](ggml_tensor* cur, const std::vector<float>& signs) {
108        if (!signs.empty()) {
109            ggml_tensor* s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, (int64_t) signs.size());
110            std::memcpy(s->data, signs.data(), signs.size() * sizeof(float));
111            cur = ggml_mul(ctx, cur, s);
112        }
113        ggml_tensor* res = ggml_reshape_2d(ctx, cur, B, ggml_nelements(cur) / B);
114        res = ggml_mul_mat(ctx, rot, res);
115        return ggml_reshape_4d(ctx, res, cur->ne[0], cur->ne[1], cur->ne[2], cur->ne[3]);
116    };
117    ggml_tensor* wg = ggml_new_tensor_2d(ctx, (ggml_type) e.gu_type, H, FF);
118    ggml_tensor* wu = ggml_new_tensor_2d(ctx, (ggml_type) e.gu_type, H, FF);
119    ggml_tensor* wd = ggml_new_tensor_2d(ctx, (ggml_type) e.d_type, FF, H);
120    std::memcpy(wg->data, e.gate.data(), e.gate.size());
121    std::memcpy(wu->data, e.up.data(), e.up.size());
122    std::memcpy(wd->data, e.down.data(), e.down.size());
123    ggml_tensor* xt = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, H);
124    std::memcpy(xt->data, x.data(), H * sizeof(float));
125    ggml_tensor* xr = hadamard(xt, e.s_h);
126    ggml_tensor* g = ggml_mul_mat(ctx, wg, xr);
127    ggml_tensor* u = ggml_mul_mat(ctx, wu, xr);
128    ggml_tensor* h = ggml_mul(ctx, ggml_silu(ctx, g), u);
129    ggml_tensor* out = ggml_mul_mat(ctx, wd, hadamard(h, e.s_ff));
130    ggml_cgraph* gf = ggml_new_graph(ctx);
131    ggml_build_forward_expand(gf, out);
132    ggml_graph_compute_with_ctx(ctx, gf, 4);
133    std::vector<float> y(H);
134    std::memcpy(y.data(), out->data, H * sizeof(float));
135    ggml_free(ctx);
136    return y;
137}
138
139// W' = W diag(s) H^T per 128-column block (what the APR encoder folds), then quantized with ggml
140std::vector<uint8_t> fold_and_quantize(const std::vector<float>& w, int rows, int cols, const std::vector<float>& s,
141                                       int type, std::vector<float>& folded) {
142    folded.assign(w.begin(), w.end());
143    for (int r = 0; r < rows; ++r) hadamard_rotate(folded.data() + (size_t) r * cols, cols, B, s.data());
144    // (H symmetric and orthonormal: row-wise H (s * w_r) is exactly the fold W diag(s) H^T)
145    std::vector<uint8_t> q(ggml_row_size((ggml_type) type, cols) * rows);
146    ggml_quantize_chunk((ggml_type) type, folded.data(), q.data(), 0, rows, cols, nullptr);
147    return q;
148}
149
150int synthetic(int gu_type, int d_type) {
151    std::mt19937 rng(1234 + gu_type * 7 + d_type);
152    std::normal_distribution<float> nd(0.f, 1.f);
153    std::uniform_int_distribution<int> coin(0, 1);
154    Expert e;
155    e.gu_type = gu_type;
156    e.d_type = d_type;
157    std::vector<float> wg((size_t) FF * H), wu((size_t) FF * H), wd((size_t) H * FF), x(H);
158    for (auto& v : wg) v = nd(rng) * 0.02f;
159    for (auto& v : wu) v = nd(rng) * 0.02f;
160    for (auto& v : wd) v = nd(rng) * 0.02f;
161    for (auto& v : x) v = nd(rng);
162    x[17] = 40.f;   // a massive channel, as the real residual stream has: the case the rotation exists for
163    e.s_h.resize(H);
164    e.s_ff.resize(FF);
165    for (auto& v : e.s_h) v = coin(rng) ? 1.f : -1.f;
166    for (auto& v : e.s_ff) v = coin(rng) ? 1.f : -1.f;
167    std::vector<float> fg, fu, fd;
168    e.gate = fold_and_quantize(wg, FF, H, e.s_h, gu_type, fg);
169    e.up = fold_and_quantize(wu, FF, H, e.s_h, gu_type, fu);
170    e.down = fold_and_quantize(wd, H, FF, e.s_ff, d_type, fd);
171
172    // the unrotated float expert W x: what the folded, quantized expert must approximate
173    std::vector<float> h(FF), ref(H);
174    for (int r = 0; r < FF; ++r) {
175        double g = 0, u = 0;
176        for (int c = 0; c < H; ++c) { g += (double) wg[(size_t) r * H + c] * x[c]; u += (double) wu[(size_t) r * H + c] * x[c]; }
177        h[r] = silu((float) g) * (float) u;
178    }
179    for (int r = 0; r < H; ++r) {
180        double o = 0;
181        for (int c = 0; c < FF; ++c) o += (double) wd[(size_t) r * FF + c] * h[c];
182        ref[r] = (float) o;
183    }
184    const auto ours = strata_expert(e, x, true);
185    const auto llama = llama_expert(e, x);
186    const auto unrot = strata_expert(e, x, false);
187    const double e_ll = rel(ours, llama), e_ref = rel(ours, ref), e_llref = rel(llama, ref), e_un = rel(unrot, ref);
188    std::printf("synthetic %s/%s: strata vs llama.cpp graph %.2e | vs unrotated float expert: strata %.4f, llama.cpp "
189                "%.4f | strata WITHOUT the rotation %.4f\n", ggml_type_name((ggml_type) gu_type),
190                ggml_type_name((ggml_type) d_type), e_ll, e_ref, e_llref, e_un);
191    // strata == llama.cpp to rounding, and both approximate W x equally well.  With Q8_0 weights the quantization
192    // error is ~1%, so the fold's convention itself is checked: the rotated path must reproduce the unrotated float
193    // expert and the unrotated path must not.  (The trellis types' own error at 1.6-2.1 bpw on Gaussian weights,
194    // compounded through SwiGLU, is large with this test's placeholder ggml encoder; there only agreement counts.)
195    const bool hi = gu_type == 8 && d_type == 8;
196    const bool ok = e_ll < 2e-3 && std::fabs(e_ref - e_llref) < 0.01 && (!hi || (e_ref < 0.03 && e_un > 0.8));
197    std::printf("  %s\n", ok ? "ok" : "FAILED");
198    return ok ? 0 : 1;
199}
200
201// A real expert, the pack's loader path: expert_layout_load(<pack>) reads native_experts.txt v5 + hadamard.txt (from
202// tools/iq_pack.py), and the layer's NativeFmt is what the engine's CPU pool would use.  (The signs come from the
203// pack: strata::GgufFile keeps only the first 64 items of a metadata array, so it cannot read sign_values.)
204int real(const char* pack, const char* path, int layer, int expert) {
205    std::string err;
206    if (!expert_layout_load(pack, 48, 512, err)) { std::fprintf(stderr, "expert_layout_load: %s\n", err.c_str()); return 1; }
207    const ExpertLayout& lay = expert_layout();
208    const HadamardSpec& hs = hadamard_spec();
209    if (!lay.native || !hs.any() || lay.version != 5) { std::fprintf(stderr, "%s: not a v5 (Hadamard) native pack\n", pack); return 1; }
210    const NativeFmt& lf = lay.fmt[(size_t) layer];
211    if (lf.had_block != B || !lf.had_gu || !lf.had_d) { std::fprintf(stderr, "layer %d is not folded in the pack\n", layer); return 1; }
212    strata::GgufFile g(path);
213    Expert e;
214    if (const float* sh = hadamard_signs(H)) e.s_h.assign(sh, sh + H);
215    if (const float* sf = hadamard_signs(FF)) e.s_ff.assign(sf, sf + FF);
216    auto slice = [&](const char* role, std::vector<uint8_t>& dst, int& type) {
217        const std::string name = "blk." + std::to_string(layer) + ".ffn_" + role + "_exps.weight";
218        const strata::TensorInfo* t = g.find(name);
219        if (!t || t->shape.size() != 3) { std::fprintf(stderr, "missing %s\n", name.c_str()); std::exit(1); }
220        type = (int) t->type;
221        const size_t per = ggml_row_size((ggml_type) type, (int64_t) t->shape[0]) * t->shape[1];
222        const uint8_t* p = g.tensor_data(*t) + per * (size_t) expert;
223        dst.assign(p, p + per);
224    };
225    int dt = 0, ut = 0;
226    slice("gate", e.gate, e.gu_type);
227    slice("up", e.up, ut);
228    slice("down", e.down, dt);
229    e.d_type = dt;
230    if (e.gu_type != lf.gu_type || e.d_type != lf.d_type) { std::fprintf(stderr, "the pack and the GGUF disagree\n"); return 1; }
231    std::mt19937 rng(99);
232    std::normal_distribution<float> nd(0.f, 1.f);
233    std::vector<float> x(H);
234    for (auto& v : x) v = nd(rng);
235    x[17] = 40.f;
236    const auto ours = strata_expert(e, x, true, &lf);
237    const auto llama = llama_expert(e, x);
238    const auto unrot = strata_expert(e, x, false);
239    const double e_ll = rel(ours, llama), e_un = rel(unrot, llama);
240    std::printf("%s layer %d expert %d (%s/%s, signs %s): strata vs llama.cpp graph %.2e | without the rotation %.3f\n",
241                path, layer, expert, ggml_type_name((ggml_type) e.gu_type), ggml_type_name((ggml_type) e.d_type),
242                e.s_h.empty() ? "identity" : "explicit", e_ll, e_un);
243    bool ok = e_ll < 2e-3 && e_un > 0.3;
244    std::printf("  %s\n", ok ? "ok" : "FAILED");
245
246    // the engine's CPU entry point: ExpertPool::run_split_multi_native with the pack's NativeFmt, three tokens
247    // routed to this expert (x quantized by native_quant_act, as expert_source.cpp does for the doorbell copy)
248    {
249        constexpr int NT = 3;
250        ExpertPool pool(4, false, false);
251        std::vector<uint8_t> blob(lf.bytes);
252        std::memcpy(blob.data(), e.gate.data(), e.gate.size());
253        std::memcpy(blob.data() + lf.up_off, e.up.data(), e.up.size());
254        std::memcpy(blob.data() + lf.down_off, e.down.data(), e.down.size());
255        std::vector<std::vector<float>> xs(NT, std::vector<float>(H)), outs(NT, std::vector<float>(H));
256        std::vector<std::vector<uint8_t>> acts(NT, std::vector<uint8_t>(kNativeActBytes));
257        ExpertJobMulti job;
258        job.blob = blob.data();
259        job.nt = NT;
260        for (int t = 0; t < NT; ++t) {
261            for (auto& v : xs[t]) v = nd(rng);
262            xs[t][(size_t) (101 * t + 5)] = 30.f;
263            native_quant_act(lf, xs[t].data(), acts[t].data());
264            job.nact[t] = acts[t].data();
265            job.out[t] = outs[t].data();
266        }
267        pool.run_split_multi_native(lf, &job, 1);
268        double worst = 0;
269        for (int t = 0; t < NT; ++t) worst = std::max(worst, rel(outs[t], llama_expert(e, xs[t])));
270        const bool pok = worst < 2e-3;
271        std::printf("  ExpertPool::run_split_multi_native, %d tokens: worst vs llama.cpp graph %.2e  %s\n", NT, worst,
272                    pok ? "ok" : "FAILED");
273        ok = ok && pok;
274    }
275    return ok ? 0 : 1;
276}
277
278// the FWHT against the dense matrix llama.cpp builds, on one block
279int fwht_check() {
280    std::mt19937 rng(7);
281    std::normal_distribution<float> nd(0.f, 1.f);
282    std::vector<float> x(B), y(B), s(B);
283    for (auto& v : x) v = nd(rng);
284    for (int i = 0; i < B; ++i) s[i] = (i * 37 % 5) < 2 ? -1.f : 1.f;
285    y = x;
286    hadamard_rotate(y.data(), B, B, s.data());
287    double worst = 0;
288    for (int r = 0; r < B; ++r) {
289        double acc = 0;
290        for (int c = 0; c < B; ++c) acc += ((__builtin_popcount(r & c) & 1) ? -1.0 : 1.0) * s[c] * x[c];
291        worst = std::max(worst, std::fabs(acc / std::sqrt((double) B) - y[r]));
292    }
293    std::printf("FWHT vs dense normalized Sylvester matrix: max abs diff %.2e  %s\n", worst, worst < 1e-5 ? "ok" : "FAILED");
294    return worst < 1e-5 ? 0 : 1;
295}
296
297}  // namespace
298
299int main(int argc, char** argv) {
300    if (!native_experts_available()) { std::fprintf(stderr, "built without native experts\n"); return 1; }
301    int rc = fwht_check();
302    if (argc >= 5 && std::strcmp(argv[1], "--pack") == 0 && std::strcmp(argv[3], "--gguf") == 0) {
303        for (int i = 5; i + 1 < argc || i == 5; i += 2) {   // [layer expert]...
304            const int layer = argc > i ? std::atoi(argv[i]) : 0, expert = argc > i + 1 ? std::atoi(argv[i + 1]) : 0;
305            rc |= real(argv[2], argv[4], layer, expert);
306        }
307        return rc;
308    }
309    // ggml type ids of the agention fork: 144 TQ2_T, 145 TQK6, 146 TQK7
310    if (GGML_TYPE_COUNT <= 146) { std::fprintf(stderr, "this ggml has no trellis types (build with STRATA_GGML_DIR = the agention fork): skipped\n"); return 77; }   // 77: ctest SKIP_RETURN_CODE (#3358)
311    rc |= synthetic(8, 8);       // Q8_0: the fold's convention, against the unrotated float expert
312    rc |= synthetic(145, 146);   // Gyro-S
313    rc |= synthetic(144, 144);   // Gyro-M
314    return rc;
315}