okami.mom/strata

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

Niko1221Merge f-container 11e0176bb into the batch 16 candidate (test files and a Python tool: ggml_cpu_init in native_expert_parity, pool tests on a 2-node host, sm_89 keys in check_cuda_spills.py)af6226a3c

main
59.9 KiB1017 linesraw
1// src/kernels/native_expert_parity.cpp - plan v0.3 P6: one native expert three ways.
2//
3//     build/native_expert_parity <shard.gguf> [layer ...]     real rows (a split model's shards are found by name)
4//     build/native_expert_parity --synthetic GU/DOWN ...      random weights quantized by ggml (e.g. q4_K/q5_1)
5//     build/native_expert_parity --synthetic [--bench] GU/DOWN ...   --bench adds a decode micro-number per pair
6//     build/native_expert_parity --q5_1-min                   the Q5_1 min term on crafted activations
7//     (the CPU-only checks of the trellis kernels, AVX2 / AVX-512 / scalar, are in tq_cpu_parity)
8//
9// (a) float reference: ggml's own dequantizer (`to_float`) and a float SwiGLU expert, (b) the CPU path
10// (ggml-cpu vec_dot with its quantized activations), (c) the GPU path (`native_expert_grouped`, q8_1
11// activations).  (b) and (c) each differ from (a) by their activation rounding (a few 1e-3 relative) and, for the
12// trellis types on the GPU, by its int8 codebook (tq_lut_i8, see iq_kernels.cu "Numerics"); both must stay within
13// relative L1 error 3e-2 of (a).  (c) runs twice, with the kernels that decode a weight part once for all entries and
14// with the per-entry ones: those two are bitwise equal to each other.
15// (d) the GPU dequantizers of the prompt path and the embedding against `to_float` (Q8_0: bit for bit).
16// The synthetic mode and (d) follow eddoursul/Strata 8029fa9.
17#include "strata/artifact/gguf_reader.hpp"
18#include "strata/kernels/cpu/native_expert.hpp"
19#include "strata/kernels/cpu/expert.hpp"
20#include "strata/kernels/cpu/iq_avx512.hpp"
21#include "strata/kernels/cpu/iq_avx2.hpp"
22#include "strata/kernels/cpu/kq_avx2.hpp"
23#include "strata/kernels/cpu/expert_layout.hpp"
24#include "strata/kernels/cpu/hadamard.hpp"
25#include "strata/kernels/cpu/tq_cpu.hpp"
26#include "ggml-cpu.h"
27#include "strata/kernels/iq_kernels.hpp"
28#include "strata/kernels/ngram.hpp"
29#include "strata/kernels/native_mmvq.hpp"
30#include "strata/core/native_dense.hpp"
31#include "strata/core/expert_source.hpp"
32
33#include <fstream>
34#include <set>
35#include <sstream>
36
37#include "ggml.h"
38
39#include <cuda_runtime.h>
40
41#include <algorithm>
42#include <cctype>
43#include <chrono>
44#include <cmath>
45#include <cstdio>
46#include <cstdlib>
47#include <cstring>
48#include <random>
49#include <string>
50#include <vector>
51
52namespace cpu = strata::kernels::cpu;
53
54static double rel(const std::vector<float>& a, const std::vector<float>& b) {
55    double n = 0, d = 0;
56    for (size_t i = 0; i < a.size(); ++i) { n += std::fabs((double) a[i] - b[i]); d += std::fabs((double) b[i]); }
57    return n / (d + 1e-30);
58}
59
60
61namespace {
62constexpr int NT = 3, E = 7;
63int64_t H = 2560, FF = 640;   // Q4KQ_PARITY_EMBD / Q4KQ_PARITY_FF override them in main (Q4-KQ: expert widths 512 and 1024)
64
65// The three ways and the dequantizers for one expert blob; returns the number of failed checks.
66int check_blob(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, int seed, const std::string& label,
67               cudaStream_t s) {
68    int failures = 0;
69    // (a) the float reference
70    const auto* tg = ggml_get_type_traits((ggml_type) f.gu_type);
71    const auto* td = ggml_get_type_traits((ggml_type) f.d_type);
72    std::vector<float> G((size_t) FF * H), U((size_t) FF * H), D((size_t) H * FF);
73    for (int64_t r = 0; r < FF; ++r) {
74        tg->to_float(blob.data() + r * f.gu_row, G.data() + r * H, H);
75        tg->to_float(blob.data() + f.up_off + r * f.gu_row, U.data() + r * H, H);
76    }
77    for (int64_t r = 0; r < H; ++r) td->to_float(blob.data() + f.down_off + r * f.d_row, D.data() + r * FF, FF);
78    if (f.tail_off) {   // the blob's scales, as the engine applies them (gate and up as read, down on its output)
79        float tail[4];
80        std::memcpy(tail, blob.data() + f.tail_off, sizeof tail);
81        for (auto& v : G) v *= tail[0];
82        for (auto& v : U) v *= tail[1];
83        for (auto& v : D) v *= tail[2];
84    }
85    std::mt19937 rng(11 + seed);
86    std::normal_distribution<float> nd(0.f, 1.f);
87    std::vector<float> x((size_t) NT * H);
88    for (auto& v : x) v = nd(rng);
89    std::vector<float> ref((size_t) NT * H), got_c((size_t) NT * H), got_g((size_t) NT * H);
90    // APR (--hadamard): the folded expert's reference takes H (s * x) and H (s * h), as llama.cpp's graph does
91    std::vector<float> xr(x);
92    if (f.had_gu) for (int k = 0; k < NT; ++k) cpu::hadamard_rotate(xr.data() + k * H, (int) H, f.had_block, f.gu_signs);
93    for (int k = 0; k < NT; ++k) {
94        std::vector<float> h(FF);
95        for (int64_t r = 0; r < FF; ++r) {
96            double g = 0, u = 0;
97            for (int64_t i = 0; i < H; ++i) { g += (double) G[r * H + i] * xr[k * H + i]; u += (double) U[r * H + i] * xr[k * H + i]; }
98            h[r] = (float) (g / (1.0 + std::exp(-g)) * u);
99        }
100        if (f.had_d) cpu::hadamard_rotate(h.data(), (int) FF, f.had_block, f.d_signs);
101        for (int64_t r = 0; r < H; ++r) {
102            double o = 0;
103            for (int64_t i = 0; i < FF; ++i) o += (double) D[r * FF + i] * h[i];
104            ref[k * H + r] = (float) o;
105        }
106    }
107    // (b) the CPU
108    {
109        std::vector<std::vector<uint8_t>> act(NT, std::vector<uint8_t>(cpu::kNativeActBytes));
110        std::vector<std::vector<uint8_t>> hq(NT, std::vector<uint8_t>(cpu::kNativeHBytes));
111        std::vector<std::vector<float>> ff(NT, std::vector<float>(FF));
112        const void* a[NT];
113        float* ffp[NT];
114        const void* hp[NT];
115        float* op[NT];
116        for (int k = 0; k < NT; ++k) {
117            cpu::native_quant_act(f, x.data() + k * H, act[k].data());
118            a[k] = act[k].data();
119            ffp[k] = ff[k].data();
120        }
121        if ((f.gu_type == 18 || f.gu_type == 21 || f.gu_type == 22) && cpu::cpu_avx2_ok() && !cpu::cpu_avx512_ok()) {
122            const auto dot = ggml_get_type_traits_cpu((ggml_type) f.gu_type)->vec_dot;
123            size_t differ = 0;
124            std::vector<float> exact((size_t) FF);
125            for (int k = 0; k < NT; ++k) {
126                cpu::iq256_gu_rows_exact_one(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a[k],
127                                              exact.data(), 0, (int) FF);
128                for (int r = 0; r < FF; ++r) {
129                    float g = 0.f, u = 0.f;
130                    dot((int) H, &g, 0, blob.data() + (size_t) r * f.gu_row, 0, a[k], 0, 1);
131                    dot((int) H, &u, 0, blob.data() + f.up_off + (size_t) r * f.gu_row, 0, a[k], 0, 1);
132                    const float want = (g / (1.f + std::exp(-g))) * u;
133                    differ += std::memcmp(&want, &exact[(size_t) r], sizeof(float)) != 0;
134                }
135            }
136            std::printf("%s exact singleton: %zu of %lld real gate/up rows differ from ggml\n",
137                        label.c_str(), differ, (long long) (NT * FF));
138            if (differ) ++failures;
139        }
140        cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF);
141        // either multi-token kernel: IQ4_XS has an AVX-2 one and no AVX-512 one, so the gate cannot be
142        // iq512_supported alone - that would leave the format untested on every CPU.
143        if (cpu::iq512_supported(f.gu_type) || cpu::iq256_supported(f.gu_type)) {
144            // ggml's own vec_dot, same Q8_K activations: the reference for both multi-token kernels
145            // (float-order differences only)
146            const auto* tc = ggml_get_type_traits_cpu((ggml_type) f.gu_type);
147            std::vector<float> gref((size_t) NT * FF);
148            for (int k = 0; k < NT; ++k)
149                for (int64_t r = 0; r < FF; ++r)
150                    tc->vec_dot((int) H, &gref[k * FF + r], 0, blob.data() + r * f.gu_row, 0, a[k], 0, 1);
151            double usg = 0.0;
152            {   // ggml single-token throughput, the weights cache-resident (compute bound)
153                const int it = 50;
154                auto t0 = std::chrono::steady_clock::now();
155                for (int i = 0; i < it; ++i)
156                    for (int64_t r = 0; r < FF; ++r) {
157                        float gg, uu;
158                        tc->vec_dot((int) H, &gg, 0, blob.data() + r * f.gu_row, 0, a[0], 0, 1);
159                        tc->vec_dot((int) H, &uu, 0, blob.data() + f.up_off + r * f.gu_row, 0, a[0], 0, 1);
160                    }
161                auto t1 = std::chrono::steady_clock::now();
162                usg = std::chrono::duration<double, std::micro>(t1 - t0).count() / it;
163            }
164            // one multi-token kernel: parity against ggml's vec_dot, then one-token and NT-token throughput
165            auto check = [&](const char* tag, bool is512) {
166                std::vector<float> g((size_t) NT * FF);
167                float* gp[NT];
168                for (int k = 0; k < NT; ++k) gp[k] = g.data() + k * FF;
169                (is512 ? cpu::iq512_rows : cpu::iq256_rows)(f.gu_type, blob.data(), f.gu_row, (int) H, a, NT, gp, 0, (int) FF);
170                const double rg = rel(g, gref);
171                std::printf("          %s %s gate rows vs ggml vec_dot: rel %.2e\n",
172                            ggml_type_name((ggml_type) f.gu_type), tag, rg);
173                if (rg > 1e-5) {   // ggml's own vec_dot is the reference: above 1e-5 it is a real mismatch,
174                    std::printf("          %s %s gate rows MISMATCH (rel %.2e > 1e-5)\n",
175                                ggml_type_name((ggml_type) f.gu_type), tag, rg);   // not rounding (measured 3e-8)
176                    ++failures;
177                }
178                float* f1[1] = {ffp[0]};
179                const int it = 50;
180                const auto gu = is512 ? cpu::iq512_gu_rows : cpu::iq256_gu_rows;
181                auto t0 = std::chrono::steady_clock::now();
182                for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, 1, f1, 0, (int) FF);
183                auto t1 = std::chrono::steady_clock::now();
184                for (int i = 0; i < it; ++i) gu(f.gu_type, blob.data(), f.gu_row, f.up_off, (int) H, a, NT, ffp, 0, (int) FF);
185                auto t2 = std::chrono::steady_clock::now();
186                const double us1 = std::chrono::duration<double, std::micro>(t1 - t0).count() / it;
187                const double usn = std::chrono::duration<double, std::micro>(t2 - t1).count() / it;
188                std::printf("          gate+up one token one thread: %s %.0f us (%.2f GB/s), ggml %.0f us (%.2f GB/s)\n",
189                            tag, us1, 2.0 * f.up_off / us1 / 1e3, usg, 2.0 * f.up_off / usg / 1e3);
190                std::printf("          gate+up %d tokens one thread: %s %.0f us vs ggml %d x %.0f us\n", NT, tag, usn, NT, usg);
191            };
192            // guarded: the binary runs on AVX-2 CPUs too, and IQ4_XS has no AVX-512 kernel (an empty switch)
193            if (cpu::cpu_vnni_ok() && cpu::iq512_supported(f.gu_type)) check("avx512", true);
194            if (cpu::cpu_avx2_ok() && cpu::iq256_supported(f.gu_type)) check("avx2", false);   // no AVX2: ggml-cpu only
195        }
196        for (int k = 0; k < NT; ++k) {
197            cpu::native_quant_h(f, ff[k].data(), hq[k].data());
198            hp[k] = hq[k].data();
199            op[k] = got_c.data() + k * H;
200        }
201        cpu::native_down_rows(f, blob.data(), hp, NT, op, 0, (int) H);
202        {   // #152: a token's rows must not depend on how many tokens share the call - each token alone (nt = 1)
203            // against its row of the NT-token call above, bit for bit, gate/up and down
204            size_t gu_diff = 0, dn_diff = 0;
205            std::vector<float> one_ff(FF), one_out(H);
206            // the NT-token gate/up rows again: the throughput loops above overwrote ff with other kernels' rows
207            for (int k = 0; k < NT; ++k) ffp[k] = ff[k].data();
208            cpu::native_gu_rows(f, blob.data(), a, NT, ffp, 0, (int) FF);
209            for (int k = 0; k < NT; ++k) {
210                const void* a1[1] = {a[k]};
211                float* f1[1] = {one_ff.data()};
212                cpu::native_gu_rows(f, blob.data(), a1, 1, f1, 0, (int) FF);
213                for (int64_t r = 0; r < FF; ++r) gu_diff += std::memcmp(&one_ff[r], &ff[k][r], 4) != 0;
214                const void* h1[1] = {hp[k]};
215                float* o1[1] = {one_out.data()};
216                cpu::native_down_rows(f, blob.data(), h1, 1, o1, 0, (int) H);
217                for (int64_t r = 0; r < H; ++r) dn_diff += std::memcmp(&one_out[r], &got_c[k * H + r], 4) != 0;
218            }
219            std::printf("          width invariance (1 vs %d tokens): gate/up %zu, down %zu rows differ\n", NT,
220                        gu_diff, dn_diff);
221            if (gu_diff || dn_diff) ++failures;
222        }
223        // the trellis types (tq_cpu.hpp, which native_gu_rows / native_down_rows above used): every ISA this CPU has
224        // against the scalar kernel BIT FOR BIT, and against ggml-cpu's vec_dot (float summation order only)
225        for (int role = 0; role < 2; ++role) {
226            const int type = role == 0 ? f.gu_type : f.d_type;
227            if (!cpu::tq_supported(type)) continue;
228            const int n = role == 0 ? (int) H : (int) FF, rows = role == 0 ? (int) FF : (int) H;
229            const size_t rb = role == 0 ? f.gu_row : f.d_row;
230            const uint8_t* w = blob.data() + (role == 0 ? 0 : f.down_off);
231            const void* const* acts = role == 0 ? a : hp;
232            std::vector<float> ref((size_t) NT * rows), got((size_t) NT * rows);
233            float* rp[NT];
234            float* gp[NT];
235            for (int k = 0; k < NT; ++k) { rp[k] = ref.data() + (size_t) k * rows; gp[k] = got.data() + (size_t) k * rows; }
236            cpu::tq_rows(cpu::TqIsa::scalar, type, w, rb, n, acts, NT, rp, 0, rows);
237            const auto* tc = ggml_get_type_traits_cpu((ggml_type) type);
238            double num = 0, den = 0;
239            for (int k = 0; k < NT; ++k)
240                for (int r = 0; r < rows; ++r) {
241                    float v = 0;
242                    tc->vec_dot(n, &v, 0, w + (size_t) r * rb, 0, acts[k], 0, 1);
243                    num += std::pow((double) v - ref[(size_t) k * rows + r], 2);
244                    den += (double) v * v;
245                }
246            const double rg = std::sqrt(num / (den + 1e-30));
247            std::printf("          %s %s rows: scalar kernel vs ggml vec_dot rel %.2e", ggml_type_name((ggml_type) type),
248                        role == 0 ? "gate" : "down", rg);
249            if (rg > 1e-5) ++failures;
250            for (cpu::TqIsa isa : {cpu::TqIsa::avx2, cpu::TqIsa::avx512}) {
251                if (!cpu::tq_isa_ok(isa)) continue;
252                cpu::tq_rows(isa, type, w, rb, n, acts, NT, gp, 0, rows);
253                const bool same = std::memcmp(got.data(), ref.data(), got.size() * sizeof(float)) == 0;
254                std::printf(" | %s %s", cpu::tq_isa_name(isa), same ? "bitwise equal" : "DIFFERENT");
255                if (!same) ++failures;
256            }
257            {   // time: the scalar kernel against the best SIMD one this CPU has, same rows and tokens
258                const int it = 30;
259                const auto t0 = std::chrono::steady_clock::now();
260                for (int k = 0; k < it; ++k) cpu::tq_rows(cpu::TqIsa::scalar, type, w, rb, n, acts, NT, rp, 0, rows);
261                const auto t1 = std::chrono::steady_clock::now();
262                const cpu::TqIsa best = cpu::tq_isa();
263                for (int k = 0; k < it; ++k) cpu::tq_rows(best, type, w, rb, n, acts, NT, gp, 0, rows);
264                const auto t2 = std::chrono::steady_clock::now();
265                const double us0 = std::chrono::duration<double, std::micro>(t1 - t0).count() / it;
266                const double us1 = std::chrono::duration<double, std::micro>(t2 - t1).count() / it;
267                std::printf(" | %s %.0f us, scalar %.0f us (%.2fx)", cpu::tq_isa_name(best), us1, us0,
268                            us1 > 0 ? us0 / us1 : 0.0);
269            }
270            std::printf("\n");
271        }
272        // UD-Q4_K_XL's formats: the multi-token AVX2 kernels (kq_avx2.cpp) against ggml-cpu's vec_dot per token,
273        // BIT FOR BIT, for 1..8 tokens; then the time of 4 tokens (a verify window) both ways
274        for (int role = 0; role < 2; ++role) {
275            const int type = role == 0 ? f.gu_type : f.d_type;
276            if (!cpu::cpu_avx2_ok() || !cpu::kq256_supported(type) || (role == 0 && type != 12)) continue;
277            const int n = role == 0 ? (int) H : (int) FF, rows = role == 0 ? (int) FF : (int) H;
278            const size_t rb = role == 0 ? f.gu_row : f.d_row;
279            const uint8_t* w = blob.data() + (role == 0 ? 0 : f.down_off);
280            const auto* tc = ggml_get_type_traits_cpu((ggml_type) type);
281            const ggml_type at = tc->vec_dot_type;
282            std::vector<std::vector<uint8_t>> acts(8, std::vector<uint8_t>(ggml_row_size(at, n)));
283            std::mt19937 arng(77 + seed);
284            std::normal_distribution<float> and_(0.f, 1.f);
285            std::vector<float> xs((size_t) n);
286            const void* ap[8];
287            for (int t = 0; t < 8; ++t) {
288                for (auto& v : xs) v = and_(arng);
289                ggml_get_type_traits_cpu(at)->from_float(xs.data(), acts[t].data(), n);
290                ap[t] = acts[t].data();
291            }
292            std::vector<float> ref((size_t) 8 * rows), got((size_t) 8 * rows);
293            for (int t = 0; t < 8; ++t)
294                for (int r = 0; r < rows; ++r) tc->vec_dot(n, &ref[(size_t) t * rows + r], 0, w + (size_t) r * rb, 0, ap[t], 0, 1);
295            size_t differ = 0;
296            for (int nt = 1; nt <= 8; ++nt) {
297                float* op[8];
298                for (int t = 0; t < nt; ++t) op[t] = got.data() + (size_t) t * rows;
299                cpu::kq256_rows(type, w, rb, n, ap, nt, op, 0, rows);
300                for (int t = 0; t < nt; ++t)
301                    differ += std::memcmp(op[t], ref.data() + (size_t) t * rows, (size_t) rows * 4) != 0;
302            }
303            const int it = 30;
304            float* op4[4] = {got.data(), got.data() + rows, got.data() + 2 * rows, got.data() + 3 * rows};
305            auto t0 = std::chrono::steady_clock::now();
306            for (int i = 0; i < it; ++i) cpu::kq256_rows(type, w, rb, n, ap, 4, op4, 0, rows);
307            auto t1 = std::chrono::steady_clock::now();
308            for (int i = 0; i < it; ++i)
309                for (int r = 0; r < rows; ++r)
310                    for (int t = 0; t < 4; ++t) tc->vec_dot(n, op4[t] + r, 0, w + (size_t) r * rb, 0, ap[t], 0, 1);
311            auto t2 = std::chrono::steady_clock::now();
312            const double us_k = std::chrono::duration<double, std::micro>(t1 - t0).count() / it;
313            const double us_g = std::chrono::duration<double, std::micro>(t2 - t1).count() / it;
314            std::printf("          %s %s rows, AVX2 multi-token vs ggml vec_dot: %zu of 36 token-sets differ in any bit; "
315                        "4 tokens one thread %.0f us vs ggml %.0f us (%.2fx)\n", ggml_type_name((ggml_type) type),
316                        role == 0 ? "gate" : "down", differ, us_k, us_g, us_g / us_k);
317            if (differ) ++failures;
318        }
319        if (cpu::q2_native_kernels(f.d_type)) {
320            // (b2) the GGUF-layout Q2_0 kernel the pool uses for Q2_0 down projections - the AVX-512 one
321            // where the CPU has it, the AVX-2 one (q2_avx2.cpp) where it does not.  Calling the AVX-512
322            // kernel unconditionally faults on a Zen 2/3 CPU.
323            std::vector<cpu::ActQ> a2(NT);
324            const cpu::ActQ* ap[NT];
325            std::vector<float> alt((size_t) NT * H);
326            float* altp[NT];
327            for (int k = 0; k < NT; ++k) {
328                cpu::act_quant_any(ff[k].data(), (int) FF, a2[k]);   // gated: AVX-512 or AVX-2 per CPU
329                ap[k] = &a2[k];
330                altp[k] = alt.data() + k * H;
331            }
332            cpu::q2_rows_any(blob.data() + f.down_off, f.d_row, (int) (FF / 64), ap, NT, altp, 0, (int) H);
333            std::printf("          q2_0 %s down vs ggml down: rel %.2e\n",
334                        cpu::cpu_vnni_ok() ? "AVX-512" : "AVX-2", rel(alt, got_c));
335        }
336        if (f.d_type == 20 && cpu::cpu_avx2_ok()) {
337            // (b3) the IQ4_NL multi-token AVX-2 kernel the pool now uses for IQ4_NL down projections,
338            // against ggml-cpu's single-token vec_dot on the SAME Q8_0 activations (h), plus timing.
339            std::vector<float> alt((size_t) NT * H), refd((size_t) NT * H);
340            float* altp[NT];
341            for (int k = 0; k < NT; ++k) altp[k] = alt.data() + k * H;
342            cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H);
343            const auto* tdc = ggml_get_type_traits_cpu((ggml_type) f.d_type);
344            for (int k = 0; k < NT; ++k)
345                for (int64_t r = 0; r < H; ++r)
346                    tdc->vec_dot((int) FF, refd.data() + k * H + r, 0,
347                                 blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1);
348            const double rdn = rel(alt, refd);
349            std::printf("          iq4_nl AVX-2 multi-token down vs ggml down: rel %.2e\n", rdn);
350            if (rdn > 1e-5) {   // measured 1e-7; same reasoning as the gate/up rows above
351                std::printf("          iq4_nl down MISMATCH (rel %.2e > 1e-5)\n", rdn);
352                ++failures;
353            }
354            const int it = 50;
355            const auto t0 = std::chrono::steady_clock::now();
356            for (int i = 0; i < it; ++i)
357                cpu::iq4nl256_down_rows(blob.data() + f.down_off, f.d_row, (int) FF, hp, NT, altp, 0, (int) H);
358            const auto t1 = std::chrono::steady_clock::now();
359            for (int i = 0; i < it; ++i)
360                for (int k = 0; k < NT; ++k)
361                    for (int64_t r = 0; r < H; ++r)
362                        tdc->vec_dot((int) FF, refd.data() + k * H + r, 0,
363                                    blob.data() + f.down_off + (size_t) r * f.d_row, 0, hp[k], 0, 1);
364            const auto t2 = std::chrono::steady_clock::now();
365            const double usn = std::chrono::duration<double, std::micro>(t1 - t0).count() / it;
366            const double usg = std::chrono::duration<double, std::micro>(t2 - t1).count() / it;
367            std::printf("          down %d tokens one thread: avx2 %.0f us (%.2f GB/s) vs ggml %.0f us (%.2f GB/s)\n",
368                        NT, usn, (double) (f.bytes - f.down_off) / usn / 1e3, usg,
369                        (double) (f.bytes - f.down_off) / usg / 1e3);
370        }
371    }
372    // (c) the GPU: one group holding the NT entries
373    {
374        auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, H, FF);
375        if (f.had_d) { L.had_block = f.had_block; L.d_signs = strata::kernels::hadamard_device_signs(f.d_signs, (int) FF); }
376        void *dblob, *dx, *dxq, *dscr;
377        float* dout;
378        unsigned long long* dptr;
379        int32_t *dstart, *dn, *ddst, *dtok;
380        cudaMalloc(&dblob, blob.size());
381        cudaMalloc(&dx, x.size() * 4);
382        cudaMalloc(&dxq, (size_t) NT * H / 32 * 36);
383        cudaMalloc(&dscr, strata::kernels::native_expert_scratch_bytes(NT, FF));
384        cudaMalloc((void**) &dout, (size_t) NT * H * 4);
385        cudaMalloc((void**) &dptr, 8);
386        cudaMalloc((void**) &dstart, 8);
387        cudaMalloc((void**) &dn, 4);
388        cudaMalloc((void**) &ddst, NT * 4);
389        cudaMalloc((void**) &dtok, NT * 4);
390        cudaMemcpy(dblob, blob.data(), blob.size(), cudaMemcpyHostToDevice);
391        cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice);
392        const unsigned long long p = (unsigned long long) dblob;
393        const int32_t st[2] = {0, NT}, one = 1, idx[NT] = {0, 1, 2};
394        cudaMemcpy(dptr, &p, 8, cudaMemcpyHostToDevice);
395        cudaMemcpy(dstart, st, 8, cudaMemcpyHostToDevice);
396        cudaMemcpy(dn, &one, 4, cudaMemcpyHostToDevice);
397        cudaMemcpy(ddst, idx, NT * 4, cudaMemcpyHostToDevice);
398        cudaMemcpy(dtok, idx, NT * 4, cudaMemcpyHostToDevice);
399        if (f.had_gu) {   // APR: the GPU rotation of x (in place here), then its floats against the CPU's
400            strata::kernels::hadamard_rows((const float*) dx, (float*) dx, NT, H, f.had_block,
401                                           strata::kernels::hadamard_device_signs(f.gu_signs, (int) H), s);
402            std::vector<float> gx(x.size());
403            cudaStreamSynchronize(s);
404            cudaMemcpy(gx.data(), dx, gx.size() * 4, cudaMemcpyDeviceToHost);
405            const bool same = std::memcmp(gx.data(), xr.data(), gx.size() * 4) == 0;
406            std::printf("          gpu hadamard_rows vs cpu hadamard_rotate: %s (rel %.2e)\n",
407                        same ? "bitwise equal" : "differ", rel(gx, xr));
408            if (!(rel(gx, xr) < 1e-6)) ++failures;
409            // the f16 form (prompt path) on the unrotated x: within fp16 rounding of the float rotation
410            std::vector<uint16_t> xh(x.size()), xh_out(x.size());
411            for (size_t i = 0; i < x.size(); ++i) xh[i] = ggml_fp32_to_fp16(x[i]);
412            uint16_t* dxh = nullptr;
413            cudaMalloc((void**) &dxh, xh.size() * 2);
414            cudaMemcpy(dxh, xh.data(), xh.size() * 2, cudaMemcpyHostToDevice);
415            strata::kernels::hadamard_rows_f16(dxh, NT, H, f.had_block,
416                                               strata::kernels::hadamard_device_signs(f.gu_signs, (int) H), s);
417            cudaStreamSynchronize(s);
418            cudaMemcpy(xh_out.data(), dxh, xh.size() * 2, cudaMemcpyDeviceToHost);
419            cudaFree(dxh);
420            std::vector<float> xf(x.size());
421            for (size_t i = 0; i < xf.size(); ++i) xf[i] = ggml_fp16_to_fp32(xh_out[i]);
422            std::printf("          gpu hadamard_rows_f16 vs cpu float rotation: rel %.2e\n", rel(xf, xr));
423            if (!(rel(xf, xr) < 2e-3)) ++failures;
424        }
425        strata::kernels::quantize_q8_1_rows((const float*) dx, NT, H, dxq, s);
426        strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s);
427        cudaStreamSynchronize(s);
428        cudaMemcpy(got_g.data(), dout, got_g.size() * 4, cudaMemcpyDeviceToHost);
429        {   // round 0214: the launches before the group stride (v1) against the same float reference: which of the two is right when they differ
430            std::vector<float> v1_g(got_g.size());
431            strata::kernels::native_grouped_set_v1(true);
432            cudaMemset(dout, 0xFF, got_g.size() * 4);
433            strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s);
434            strata::kernels::native_grouped_set_v1(false);
435            cudaStreamSynchronize(s);
436            cudaMemcpy(v1_g.data(), dout, v1_g.size() * 4, cudaMemcpyDeviceToHost);
437            size_t nd = 0;
438            for (size_t i = 0; i < v1_g.size(); ++i) nd += std::memcmp(&v1_g[i], &got_g[i], 4) != 0;
439            std::printf("          v1 launches vs float reference: rel %.3e; new launches: rel %.3e; v1 vs new: %zu of %zu floats differ in any bit (rel %.2e)\n",
440                        rel(v1_g, ref), rel(got_g, ref), nd, v1_g.size(), rel(v1_g, got_g));
441        }
442        {   // the kernels that decode a weight part once for the NT entries, bitwise vs the per-entry ones (#242;
443            // the formats without a decode-once split take the per-entry kernels either way)
444            std::vector<float> old_g(got_g.size());
445            const bool was = strata::kernels::iq_old_kernels();
446            strata::kernels::iq_set_old_kernels(!was);
447            strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, 1, NT, dxq, dscr, dout, s);
448            strata::kernels::iq_set_old_kernels(was);
449            cudaStreamSynchronize(s);
450            cudaMemcpy(old_g.data(), dout, old_g.size() * 4, cudaMemcpyDeviceToHost);
451            const bool same = std::memcmp(old_g.data(), got_g.data(), got_g.size() * 4) == 0;
452            std::printf("          gpu decode-once vs per-entry kernels: %s\n", same ? "bitwise equal" : "MISMATCH");
453            if (!same) ++failures;
454        }
455        {   // (d) the GPU dequantizers (prompt path: iq_dequant_f32/_f16; embedding: iq_embed_rows) against to_float
456            float* dq = nullptr;
457            uint16_t* dh = nullptr;
458            int32_t* dtk = nullptr;
459            cudaMalloc((void**) &dq, (size_t) FF * H * 4);
460            cudaMalloc((void**) &dh, (size_t) FF * H * 2);
461            cudaMalloc((void**) &dtk, (size_t) FF * 4);
462            std::vector<float> got_dq((size_t) FF * H);
463            std::vector<uint16_t> got_h((size_t) FF * H);
464            std::vector<int32_t> tk((size_t) FF);
465            for (int64_t r = 0; r < FF; ++r) tk[(size_t) r] = (int32_t) (FF - 1 - r);   // rows in reverse order
466            cudaMemcpy(dtk, tk.data(), tk.size() * 4, cudaMemcpyHostToDevice);
467            double dq_err = 0.0;
468            size_t differ = 0, h_differ = 0, h_shown = 0;
469            long h_maxulp = 0;
470            const struct { const uint8_t* src; int type; const std::vector<float>* want; } mats[3] = {
471                {(const uint8_t*) dblob, f.gu_type, &G}, {(const uint8_t*) dblob + f.up_off, f.gu_type, &U},
472                {(const uint8_t*) dblob + f.down_off, f.d_type, &D}};
473            for (const auto& m : mats) {
474                strata::kernels::iq_dequant_f32(m.type, m.src, FF * H, dq, s);
475                strata::kernels::iq_dequant_f16(m.type, m.src, FF * H, dh, s);
476                cudaStreamSynchronize(s);
477                cudaMemcpy(got_dq.data(), dq, got_dq.size() * 4, cudaMemcpyDeviceToHost);
478                cudaMemcpy(got_h.data(), dh, got_h.size() * 2, cudaMemcpyDeviceToHost);
479                dq_err = (std::max)(dq_err, rel(got_dq, *m.want));
480                for (size_t i = 0; i < got_dq.size(); ++i) {
481                    differ += std::memcmp(&got_dq[i], &(*m.want)[i], 4) != 0;
482                    if (got_h[i] != ggml_fp32_to_fp16(got_dq[i]) && !((got_h[i] & 0x7fff) == 0 && got_dq[i] == 0.0f)) {   // (+0 for -0 is no difference)
483                        ++h_differ;
484                        h_maxulp = (std::max)(h_maxulp, (long) std::labs((long) got_h[i] - (long) ggml_fp32_to_fp16(got_dq[i])));
485                        if (h_shown++ < 3) std::printf("          fp16 dequant differs: i=%zu f32 %.9g half %.9g (bits %04x) fp16(f32) bits %04x\n", i, got_dq[i], (double) ggml_fp16_to_fp32(got_h[i]), got_h[i], ggml_fp32_to_fp16(got_dq[i]));
486                    }
487                }
488            }
489            // the gate matrix as an embedding table of FF rows of H values
490            strata::kernels::iq_embed_rows(f.gu_type, dblob, f.gu_row, dtk, FF, H, dq, s);
491            cudaStreamSynchronize(s);
492            cudaMemcpy(got_dq.data(), dq, got_dq.size() * 4, cudaMemcpyDeviceToHost);
493            size_t emb_differ = 0;
494            for (int64_t r = 0; r < FF; ++r)
495                emb_differ += std::memcmp(got_dq.data() + r * H, G.data() + (FF - 1 - r) * H, (size_t) H * 4) != 0;
496            cudaFree(dq); cudaFree(dh); cudaFree(dtk);
497            std::printf("          GPU dequant vs ggml to_float: rel %.2e, %zu of %lld values differ in any bit; fp16 of "
498                        "it: %zu differ (max %ld ulp); embedding rows: %zu of %lld differ\n", dq_err, differ, (long long) (3 * FF * H),
499                        h_differ, h_maxulp, emb_differ, (long long) FF);
500            // exact where there is one product (Q8_0), a rounding at most elsewhere (fused multiply-adds)
501            const bool exact = f.gu_type == 8 && f.d_type == 8;
502            if (!(dq_err < 1e-6) || h_differ || (exact && (differ || emb_differ))) ++failures;
503        }
504        cudaFree(dblob); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr);
505        cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok);
506    }
507    const double ec = rel(got_c, ref), eg = rel(got_g, ref), ecg = rel(got_c, got_g);
508    // Q5_0 down used to sit at 2.1e-2 .. 3.1e-2 (the offset from the original activation sum); with the quantized sum it is as accurate as the rest
509    const double gpu_limit = f.d_type == 6 ? 1.8e-2 : 3e-2;
510    const bool ok = ec < 3e-2 && eg < gpu_limit && std::isfinite(ec) && std::isfinite(eg);
511    std::printf("%-9s %-8s/%-7s blob %8zu  cpu rel %.2e  gpu rel %.2e  cpu-gpu %.2e  %s\n", label.c_str(),
512                ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), f.bytes, ec, eg, ecg,
513                ok ? "ok" : "FAIL");
514    return failures + (ok ? 0 : 1);
515}
516
517// Decode micro-number (--bench): the verify/decode shape, a top-10 routing of one token per expert.  A pool of 64
518// copies of one blob (about 180 MB at IQ2_XS/Q2_0, past the last-level cache) is walked ten experts at a time, so
519// every call reads cold weights.  Prints microseconds per native_expert_grouped call and the weight GB/s it implies.
520void bench_decode(const cpu::NativeFmt& f, const std::vector<uint8_t>& blob, const std::string& label, cudaStream_t s) {
521    constexpr int POOL = 64, TOP = 10, ITERS = 200;
522    auto L = strata::kernels::native_expert_layout(f.gu_type, f.d_type, H, FF);
523    uint8_t* dpool = nullptr;
524    if (cudaMalloc((void**) &dpool, (size_t) POOL * blob.size()) != cudaSuccess) { std::printf("%s: bench: no memory\n", label.c_str()); return; }
525    for (int i = 0; i < POOL; ++i) cudaMemcpy(dpool + (size_t) i * blob.size(), blob.data(), blob.size(), cudaMemcpyHostToDevice);
526    std::mt19937 rng(3);
527    std::normal_distribution<float> nd(0.f, 1.f);
528    std::vector<float> x((size_t) TOP * H);
529    for (auto& v : x) v = nd(rng);
530    float *dx, *dout;
531    void *dxq, *dscr;
532    unsigned long long* dptr;
533    int32_t *dstart, *dn, *ddst, *dtok;
534    cudaMalloc((void**) &dx, x.size() * 4);
535    cudaMalloc(&dxq, (size_t) TOP * H / 32 * 36);
536    cudaMalloc(&dscr, strata::kernels::native_expert_scratch_bytes(TOP, FF));
537    cudaMalloc((void**) &dout, (size_t) TOP * H * 4);
538    cudaMalloc((void**) &dptr, TOP * 8);
539    cudaMalloc((void**) &dstart, (TOP + 1) * 4);
540    cudaMalloc((void**) &dn, 4);
541    cudaMalloc((void**) &ddst, TOP * 4);
542    cudaMalloc((void**) &dtok, TOP * 4);
543    cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice);
544    int32_t st[TOP + 1], idx[TOP], n = TOP;
545    for (int i = 0; i <= TOP; ++i) st[i] = i;
546    for (int i = 0; i < TOP; ++i) idx[i] = i;
547    cudaMemcpy(dstart, st, sizeof st, cudaMemcpyHostToDevice);
548    cudaMemcpy(dn, &n, 4, cudaMemcpyHostToDevice);
549    cudaMemcpy(ddst, idx, sizeof idx, cudaMemcpyHostToDevice);
550    cudaMemcpy(dtok, idx, sizeof idx, cudaMemcpyHostToDevice);
551    strata::kernels::quantize_q8_1_rows(dx, TOP, H, dxq, s);
552    std::vector<std::vector<unsigned long long>> sets;   // the pointer sets, one per pool position
553    for (int k = 0; k < POOL; ++k) {
554        std::vector<unsigned long long> v(TOP);
555        for (int e = 0; e < TOP; ++e) v[e] = (unsigned long long) (dpool + (size_t) ((k * TOP + e) % POOL) * blob.size());
556        sets.push_back(v);
557    }
558    cudaEvent_t e0, e1;
559    cudaEventCreate(&e0);
560    cudaEventCreate(&e1);
561    std::vector<double> us;
562    for (int rep = 0; rep < 7; ++rep) {
563        for (int i = 0; i < 20; ++i) {   // warm up
564            cudaMemcpyAsync(dptr, sets[i % POOL].data(), TOP * 8, cudaMemcpyHostToDevice, s);
565            strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, TOP, TOP, dxq, dscr, dout, s);
566        }
567        cudaStreamSynchronize(s);
568        float ms = 0.f;
569        double tot = 0;
570        for (int i = 0; i < ITERS; ++i) {   // each call timed on its own so the pointer upload stays out of it
571            cudaMemcpyAsync(dptr, sets[(i * 7) % POOL].data(), TOP * 8, cudaMemcpyHostToDevice, s);
572            cudaEventRecord(e0, s);
573            strata::kernels::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, TOP, TOP, dxq, dscr, dout, s);
574            cudaEventRecord(e1, s);
575            cudaEventSynchronize(e1);
576            cudaEventElapsedTime(&ms, e0, e1);
577            tot += ms;
578        }
579        us.push_back(tot / ITERS * 1e3);
580    }
581    std::sort(us.begin(), us.end());
582    const double med = us[us.size() / 2];
583    std::printf("BENCH %-8s/%-7s decode top-%d x1 token: median %.1f us per call (min %.1f, max %.1f), %.0f GB/s of expert weights\n",
584                ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), TOP, med, us.front(), us.back(),
585                (double) TOP * blob.size() / med / 1e3);
586    cudaFree(dpool); cudaFree(dx); cudaFree(dxq); cudaFree(dscr); cudaFree(dout); cudaFree(dptr);
587    cudaFree(dstart); cudaFree(dn); cudaFree(ddst); cudaFree(dtok);
588    cudaEventDestroy(e0); cudaEventDestroy(e1);
589}
590
591int type_of(std::string name) {
592    for (auto& c : name) c = (char) std::tolower((unsigned char) c);
593    // The trellis types sit above GGML_TYPE_COUNT on an upstream ggml (the overlay adds them to ggml-cuda, not to the
594    // type table), so ggml_type_name cannot resolve them: name them here, as the engine's own type ids do.
595    static const struct { const char* n; int t; } trellis[] = {{"tq2_t", 144}, {"tqk6", 145}, {"tqk7", 146},
596                                                              {"tqp5", 147}, {"tqp6", 148}, {"tqp7", 149}};
597    for (const auto& e : trellis) if (name == e.n) return e.t;
598    for (int t = 0; t < GGML_TYPE_COUNT; ++t) {
599        const char* n = ggml_type_name((ggml_type) t);
600        if (n == nullptr) continue;
601        std::string m(n);
602        for (auto& c : m) c = (char) std::tolower((unsigned char) c);
603        if (m == name) return t;
604    }
605    return -1;
606}
607
608// Random weights (rows of different magnitudes) quantized by ggml into the blob layout.
609std::vector<uint8_t> synthetic_blob(const cpu::NativeFmt& f, int seed) {
610    std::vector<uint8_t> blob(f.bytes);
611    std::mt19937 rng(seed);
612    std::normal_distribution<float> nd(0.f, 1.f);
613    auto quant = [&](int type, int64_t rows, int64_t cols, uint8_t* dst) {
614        std::vector<float> w((size_t) (rows * cols));
615        for (int64_t r = 0; r < rows; ++r) {
616            const float scale = 0.02f * (0.5f + (float) (r % 7) / 7.0f);
617            for (int64_t c = 0; c < cols; ++c) w[(size_t) (r * cols + c)] = scale * nd(rng);
618        }
619        const std::vector<float> imatrix((size_t) cols, 1.0f);
620        ggml_quantize_chunk((ggml_type) type, w.data(), dst, 0, rows, cols,
621                            ggml_quantize_requires_imatrix((ggml_type) type) ? imatrix.data() : nullptr);
622    };
623    quant(f.gu_type, FF, H, blob.data());
624    quant(f.gu_type, FF, H, blob.data() + f.up_off);
625    quant(f.d_type, H, FF, blob.data() + f.down_off);
626    if (f.tail_off) {   // NVFP4's {s_gate, s_up, s_down, 0}: non-unit for an NVFP4 projection, 1.0 for another format
627        const bool g4 = f.gu_type == 40, d4 = f.d_type == 40;
628        const float tail[4] = {g4 ? 0.75f : 1.f, g4 ? 1.25f : 1.f, d4 ? 0.5f : 1.f, 0.f};
629        std::memcpy(blob.data() + f.tail_off, tail, sizeof tail);
630    }
631    return blob;
632}
633
634// The Q5_1 min term.  Activations x = d * (q + 0.45) round to q, so each q8_1 block's sum of the ORIGINAL values
635// (`ds.y`, what llama.cpp CUDA multiplies the min by) exceeds d * sum(q) by 0.45 * 32 * d.  The GPU dot must take
636// the quantized sum, as ggml-cpu's vec_dot does: equal to ggml-cpu on the same blocks with s = d * sum(q), and far
637// from the ds.y variant.  Weights with large mins make the difference visible.
638int check_q5_1_min(cudaStream_t s) {
639    constexpr int n = 640, rows = 64;
640    ggml_cpu_init();   // the fp16 tables vec_dot uses (the other modes get this through native_fmt)
641    std::mt19937 rng(5);
642    std::uniform_int_distribution<int> qd(-100, 100);
643    std::normal_distribution<float> nd(0.f, 1.f);
644    std::vector<float> w((size_t) rows * n), x(n);
645    for (auto& v : w) v = 0.3f + 0.05f * nd(rng);        // positive weights: a large min per block
646    const float d = 0.01f;
647    for (auto& v : x) v = d * ((float) qd(rng) + 0.45f);
648    const size_t row_bytes = ggml_row_size(GGML_TYPE_Q5_1, n);
649    std::vector<uint8_t> wq((size_t) rows * row_bytes);
650    ggml_quantize_chunk(GGML_TYPE_Q5_1, w.data(), wq.data(), 0, rows, n, nullptr);
651    // the GPU: its own q8_1 quantizer, then iq_mmvq on Q5_1
652    void *dw, *dx, *dxq;
653    float* dy;
654    cudaMalloc(&dw, wq.size());
655    cudaMalloc(&dx, n * 4);
656    cudaMalloc(&dxq, (size_t) n / 32 * 36);
657    cudaMalloc((void**) &dy, rows * 4);
658    cudaMemcpy(dw, wq.data(), wq.size(), cudaMemcpyHostToDevice);
659    cudaMemcpy(dx, x.data(), n * 4, cudaMemcpyHostToDevice);
660    strata::kernels::quantize_q8_1_rows((const float*) dx, 1, n, dxq, s);
661    strata::kernels::iq_mmvq(GGML_TYPE_Q5_1, dw, dxq, dy, n, rows, 1, s);
662    cudaStreamSynchronize(s);
663    std::vector<float> gpu(rows);
664    std::vector<uint8_t> xq((size_t) n / 32 * 36);
665    cudaMemcpy(gpu.data(), dy, rows * 4, cudaMemcpyDeviceToHost);
666    cudaMemcpy(xq.data(), dxq, xq.size(), cudaMemcpyDeviceToHost);
667    cudaFree(dw); cudaFree(dx); cudaFree(dxq); cudaFree(dy);
668    // ggml-cpu on the GPU's own blocks: once with s = d * sum(q) (the quantized sum), once with s = ds.y as stored
669    struct Q81 { ggml_fp16_t d, s; int8_t qs[32]; };   // ggml's block_q8_1: {d, s} halves, 32 codes
670    static_assert(sizeof(Q81) == 36, "block_q8_1 layout");
671    auto* blocks = (Q81*) xq.data();
672    std::vector<Q81> qsum(blocks, blocks + n / 32);
673    double shift = 0.0;
674    for (auto& b : qsum) {
675        int sq = 0;
676        for (int i = 0; i < 32; ++i) sq += b.qs[i];
677        const float dd = ggml_fp16_to_fp32(b.d);
678        shift = (std::max)(shift, (double) std::fabs(ggml_fp16_to_fp32(b.s) - dd * sq));
679        b.s = ggml_fp32_to_fp16(dd * (float) sq);
680    }
681    const auto* tc = ggml_get_type_traits_cpu(GGML_TYPE_Q5_1);
682    std::vector<float> want(rows), stored(rows);
683    for (int r = 0; r < rows; ++r) {
684        const uint8_t* row = wq.data() + (size_t) r * row_bytes;
685        tc->vec_dot(n, &want[r], 0, row, 0, qsum.data(), 0, 1);
686        tc->vec_dot(n, &stored[r], 0, row, 0, blocks, 0, 1);
687    }
688    const double e_q = rel(gpu, want), e_s = rel(gpu, stored);
689    // the quantized sum goes through fp16 in ggml-cpu's block (s is a half), so 1e-3 rather than bitwise
690    const bool ok = e_q < 1e-3 && e_s > 10 * e_q && shift > 0.0;
691    std::printf("q5_1 min   row 0: GPU %.6g, ggml-cpu (quantized sum) %.6g, (stored sum) %.6g\n", gpu[0], want[0],
692                stored[0]);
693    std::printf("q5_1 min   GPU vs ggml-cpu with s = d*sum(q): rel %.2e; vs s = sum(x) (llama.cpp CUDA's): rel %.2e "
694                "(largest per-block sum shift %.3g)  %s\n", e_q, e_s, shift, ok ? "ok" : "FAIL");
695    return ok ? 0 : 1;
696}
697// #290: the BF16 token embedding (--embd-gguf) - iq_embed_rows and iq_dequant_f32 on a random BF16 table against
698// the exact widening (bits << 16), every bit; rows gathered out of order, with repeats
699int check_bf16_embd(cudaStream_t s) {
700    constexpr int kBf16 = 30;
701    const int64_t H = 2560, V = 61, NT = 97;
702    int failures = 0;
703    if (!strata::kernels::embed_type_supported(kBf16) || strata::kernels::iq_supported(kBf16) ||
704        strata::kernels::iq_row_bytes(kBf16, H) != (size_t) H * 2) {
705        std::printf("bf16 embedding: type support / row bytes wrong\n");
706        return 1;
707    }
708    std::mt19937 rng(290);
709    std::vector<uint16_t> table((size_t) (V * H));
710    for (auto& v : table) {   // any bit pattern but NaN (a NaN's payload is not what the test is about)
711        do v = (uint16_t) (rng() & 0xffff); while ((v & 0x7f80) == 0x7f80 && (v & 0x7f));
712    }
713    std::vector<int32_t> tok((size_t) NT);
714    for (auto& t : tok) t = (int32_t) (rng() % V);
715    void* dt = nullptr;
716    int32_t* dtok = nullptr;
717    float* dout = nullptr;
718    cudaMalloc(&dt, table.size() * 2);
719    cudaMalloc((void**) &dtok, tok.size() * 4);
720    const int64_t out_rows = NT > V ? NT : V;   // the gathered rows (NT) and the whole table (V) share the buffer
721    cudaMalloc((void**) &dout, (size_t) (out_rows * H) * 4);
722    cudaMemcpy(dt, table.data(), table.size() * 2, cudaMemcpyHostToDevice);
723    cudaMemcpy(dtok, tok.data(), tok.size() * 4, cudaMemcpyHostToDevice);
724    auto widen = [](uint16_t b) { const uint32_t u = (uint32_t) b << 16; float f; std::memcpy(&f, &u, 4); return f; };
725    std::vector<float> got((size_t) (out_rows * H));
726    strata::kernels::iq_embed_rows(kBf16, dt, (size_t) H * 2, dtok, NT, H, dout, s);
727    cudaStreamSynchronize(s);
728    cudaMemcpy(got.data(), dout, (size_t) (NT * H) * 4, cudaMemcpyDeviceToHost);
729    size_t rows_differ = 0;
730    for (int64_t r = 0; r < NT; ++r)
731        for (int64_t d = 0; d < H; ++d) {
732            const float want = widen(table[(size_t) (tok[(size_t) r] * H + d)]);
733            if (std::memcmp(&got[(size_t) (r * H + d)], &want, 4) != 0) { ++rows_differ; break; }
734        }
735    strata::kernels::iq_dequant_f32(kBf16, dt, V * H, dout, s);
736    cudaStreamSynchronize(s);
737    cudaMemcpy(got.data(), dout, table.size() * 4, cudaMemcpyDeviceToHost);
738    size_t values_differ = 0;
739    for (size_t i = 0; i < table.size(); ++i) {
740        const float want = widen(table[i]);
741        values_differ += std::memcmp(&got[i], &want, 4) != 0;
742    }
743    cudaFree(dt); cudaFree(dtok); cudaFree(dout);
744    std::printf("bf16 embedding: %lld gathered rows, %zu differ; dequant of %lld values, %zu differ in any bit\n",
745                (long long) NT, rows_differ, (long long) (V * H), values_differ);
746    if (rows_differ || values_differ) ++failures;
747    return failures;
748}
749
750// APR: a GGUF's token_embd as the engine gathers it (iq_embed_rows, any embed_type_supported type: Gyro-S's Q6_K),
751// `n` random rows against ggml's to_float, bit for bit; then iq_dequant_f32 of one row
752int check_gguf_embd(const char* path, int n, cudaStream_t s) {
753    const strata::GgufModel model(strata::gguf_split_paths(path));
754    size_t at = 0;
755    const strata::TensorInfo* t = model.find("token_embd.weight", &at);
756    if (!t || t->shape.size() != 2 || t->shape[0] != (uint64_t) H) { std::printf("%s: no token_embd [2560, V]\n", path); return 1; }
757    const int type = (int) t->type;
758    const int64_t V = (int64_t) t->shape[1];
759    if (!strata::kernels::embed_type_supported(type)) { std::printf("token_embd type %d: no GPU dequantizer\n", type); return 1; }
760    const size_t rb = strata::kernels::iq_row_bytes(type, H);
761    if (rb != ggml_row_size((ggml_type) type, H)) { std::printf("row bytes %zu != ggml %zu\n", rb, ggml_row_size((ggml_type) type, H)); return 1; }
762    const uint8_t* table = model.shard(at).tensor_data(*t);
763    std::mt19937 rng(17);
764    std::vector<int32_t> tok((size_t) n);
765    for (auto& v : tok) v = (int32_t) (rng() % (uint64_t) V);
766    tok[0] = 0; tok[(size_t) n - 1] = (int32_t) (V - 1);
767    // the rows the test reads, packed contiguously as a small table (the engine maps the whole one)
768    std::vector<uint8_t> small((size_t) n * rb);
769    for (int i = 0; i < n; ++i) std::memcpy(small.data() + (size_t) i * rb, table + (size_t) tok[(size_t) i] * rb, rb);
770    std::vector<int32_t> idx((size_t) n);
771    for (int i = 0; i < n; ++i) idx[(size_t) i] = n - 1 - i;     // gathered in reverse
772    void* dt = nullptr; int32_t* dtok = nullptr; float* dout = nullptr;
773    cudaMalloc(&dt, small.size());
774    cudaMalloc((void**) &dtok, (size_t) n * 4);
775    cudaMalloc((void**) &dout, (size_t) n * H * 4);
776    cudaMemcpy(dt, small.data(), small.size(), cudaMemcpyHostToDevice);
777    cudaMemcpy(dtok, idx.data(), (size_t) n * 4, cudaMemcpyHostToDevice);
778    strata::kernels::iq_embed_rows(type, dt, rb, dtok, n, H, dout, s);
779    cudaStreamSynchronize(s);
780    std::vector<float> got((size_t) n * H), want((size_t) H);
781    cudaMemcpy(got.data(), dout, got.size() * 4, cudaMemcpyDeviceToHost);
782    const auto* tr = ggml_get_type_traits((ggml_type) type);
783    size_t rows_differ = 0, values_differ = 0;
784    for (int i = 0; i < n; ++i) {
785        tr->to_float(small.data() + (size_t) idx[(size_t) i] * rb, want.data(), H);
786        const size_t d = (size_t) std::count_if(want.begin(), want.end(), [&, k = (size_t) 0](const float& w) mutable {
787            return std::memcmp(&w, &got[(size_t) i * H + k++], 4) != 0; });
788        values_differ += d;
789        rows_differ += d != 0;
790    }
791    strata::kernels::iq_dequant_f32(type, dt, H, dout, s);
792    cudaStreamSynchronize(s);
793    cudaMemcpy(got.data(), dout, (size_t) H * 4, cudaMemcpyDeviceToHost);
794    tr->to_float(small.data(), want.data(), H);
795    const bool one = std::memcmp(got.data(), want.data(), (size_t) H * 4) == 0;
796    cudaFree(dt); cudaFree(dtok); cudaFree(dout);
797    std::printf("%s token_embd (%s, %lld rows): %d random rows gathered on the GPU, %zu rows / %zu values differ from "
798                "ggml to_float; iq_dequant_f32 row: %s\n", path, ggml_type_name((ggml_type) type), (long long) V, n,
799                rows_differ, values_differ, one ? "bitwise equal" : "DIFFERS");
800    return (rows_differ || !one) ? 1 : 0;
801}
802
803// APR: a GGUF's PLE table through PleTable (the engine's reader; mapped and direct SSD I/O), `n` random rows of 16
804// heads against ggml's to_float of the same bytes, bit for bit (Gyro-M's Q8_0 table; IQ4_NL for the others)
805int check_gguf_ple(const char* path, int n) {
806    const strata::GgufModel model(strata::gguf_split_paths(path));
807    size_t at = 0;
808    const strata::TensorInfo* t = model.find("per_layer_token_embd.weight", &at);
809    if (!t) { std::printf("%s: no per_layer_token_embd.weight\n", path); return 1; }
810    const std::string shard = model.shard(at).path();
811    const uint8_t* table = model.shard(at).tensor_data(*t);
812    const int type = (int) t->type;
813    const size_t rb = ggml_row_size((ggml_type) type, 160);
814    const uint64_t rows = t->shape[1];
815    const auto* tr = ggml_get_type_traits((ggml_type) type);
816    std::mt19937 rng(23);
817    std::vector<uint32_t> r16((size_t) n * 16);
818    for (auto& v : r16) v = (uint32_t) (rng() % rows);
819    r16[0] = 0; r16.back() = (uint32_t) (rows - 1);
820    int failures = 0;
821    for (const auto mode : {strata::kernels::PleIo::Mmap, strata::kernels::PleIo::Direct}) {
822        strata::kernels::PleTable ple;
823        strata::kernels::PleIoOptions io;
824        io.mode = mode;
825        std::string err;
826        if (!ple.open(shard, err, io)) { std::printf("PleTable open (%s): %s\n", mode == strata::kernels::PleIo::Direct ? "direct" : "mmap", err.c_str()); ++failures; continue; }
827        std::vector<float> got(r16.size() * 160), want(160);
828        if (!ple.gather_batch(r16.data(), (size_t) n, got.data(), err)) { std::printf("gather_batch: %s\n", err.c_str()); ++failures; continue; }
829        size_t rows_differ = 0;
830        for (size_t i = 0; i < r16.size(); ++i) {
831            tr->to_float(table + (size_t) r16[i] * rb, want.data(), 160);
832            rows_differ += std::memcmp(want.data(), got.data() + i * 160, 160 * 4) != 0;
833        }
834        std::printf("%s PLE table (%s via PleTable as %s, %s I/O): %zu random rows, %zu differ from ggml to_float\n",
835                    path, ggml_type_name((ggml_type) type), ple.format(),
836                    mode == strata::kernels::PleIo::Direct ? "direct" : "mmap", r16.size(), rows_differ);
837        if (rows_differ) ++failures;
838    }
839    return failures;
840}
841
842// APR: the engine's start-up checks for a pack made from a published GGUF, without a GPU allocation: the expert
843// table (native_experts.txt v5 + hadamard.txt), GPU expert kernels for every layer's formats, the GGUF expert
844// offsets (check_experts_gguf), every quantized tensor the index serves from the GGUF has a native kernel (NativeDense
845// projections, the head) or dequantizer (the embedding), and the PLE table opens with the engine's reader.
846int check_load(const char* pack, const char* gguf) {
847    int failures = 0;
848    std::string err;
849    auto fail = [&](const std::string& m) { std::printf("  FAIL %s\n", m.c_str()); ++failures; };
850    if (!cpu::expert_layout_load(pack, 48, 512, err)) { fail("expert_layout_load: " + err); return failures; }
851    const auto& lay = cpu::expert_layout();
852    const auto& hs = cpu::hadamard_spec();
853    int folded = 0;
854    for (int64_t l = 0; l < (int64_t) lay.fmt.size(); ++l) {
855        const auto& f = lay.fmt[(size_t) l];
856        folded += f.had_gu && f.had_d;
857        if (!strata::kernels::native_expert_supported(f.gu_type, f.d_type, f.n_embd, f.n_ff))
858            fail("layer " + std::to_string(l) + ": no GPU expert kernels for " + std::to_string(f.gu_type) + "/" +
859                 std::to_string(f.d_type));
860    }
861    std::printf("  experts: native_experts.txt v%d, %zu layers (%s/%s ...), %.2f GiB; hadamard block %d, %d layers folded\n",
862                lay.version, lay.fmt.size(), ggml_type_name((ggml_type) lay.fmt[0].gu_type),
863                ggml_type_name((ggml_type) lay.fmt[0].d_type), lay.total / 1073741824.0, hs.block, folded);
864    if (!strata::core::check_experts_gguf(gguf, lay, err)) fail("check_experts_gguf: " + err);
865    else std::printf("  check_experts_gguf: ok\n");
866    const std::vector<std::string> shards = strata::gguf_split_paths(gguf);
867    std::set<std::string> served;
868    if (!strata::core::NativeDense::served_names(shards, true, served, err)) fail("served_names: " + err);
869    const strata::GgufModel model(shards);
870    std::ifstream idx(std::string(pack) + "/index.txt");
871    std::string line;
872    int from_gguf = 0, ok_rows = 0;
873    while (std::getline(idx, line)) {
874        if (line.empty() || line[0] == '#') continue;
875        std::istringstream ss(line);
876        std::string name, file, kind;
877        ss >> name >> file >> kind;
878        if (kind != "0") continue;                   // a dense.bin row
879        ++from_gguf;
880        size_t at = 0;
881        const strata::TensorInfo* t = model.find(name, &at);
882        if (!t) { fail(name + ": not in the GGUF"); continue; }
883        bool ok = served.count(name) > 0;
884        if (name == "token_embd.weight") ok = strata::kernels::embed_type_supported((int) t->type);
885        if (name == "output.weight") ok = strata::kernels::native_mmvq_supported((int) t->type);
886        if (!ok) fail(name + " (" + t->type_name() + "): served from the GGUF but no kernel takes it");
887        else ++ok_rows;
888    }
889    std::printf("  index: %d tensors served from the GGUF, %d with a kernel (incl. token_embd %s, output %s)\n",
890                from_gguf, ok_rows, model.find("token_embd.weight")->type_name(), model.find("output.weight")->type_name());
891    size_t pat = 0;
892    if (model.find("per_layer_token_embd.weight", &pat)) {
893        strata::kernels::PleTable ple;
894        strata::kernels::PleIoOptions io;   // the engine's default: direct SSD reads
895        if (!ple.open(model.shard(pat).path(), err, io)) fail("PleTable: " + err);
896        else std::printf("  PLE table: %s, %llu rows, direct I/O: ok\n", ple.format(), (unsigned long long) ple.rows());
897    }
898    return failures;
899}
900
901}  // namespace
902
903int main(int argc, char** argv) {
904    setvbuf(stdout, nullptr, _IONBF, 0);   // keep the trail on a crash
905    // ggml-cpu's dots read the fp16 -> fp32 table that ggml_cpu_init() fills, and until it runs every vec_dot returns 0.
906    // The CPU pool no longer calls it (STRATA_OWN_CPU_QUANT, the default), so this test, whose reference is ggml's own
907    // vec_dot, starts it itself; without it all the CPU legs below compare against zeros.
908    ggml_cpu_init();
909    if (const char* e = std::getenv("Q4KQ_PARITY_EMBD")) H = std::atoll(e);
910    if (const char* e = std::getenv("Q4KQ_PARITY_FF")) FF = std::atoll(e);
911    if (argc < 2) {
912        std::fprintf(stderr, "usage: native_expert_parity <shard.gguf> [layer ...]\n"
913                             "       native_expert_parity --synthetic GU/DOWN ...   (ggml type names, e.g. q4_K/q5_1)\n"
914                             "       native_expert_parity --synthetic-hadamard GU/DOWN ...   (the same, Hadamard-folded: APR)\n"
915                             "       native_expert_parity --q5_1-min\n"
916                             "       native_expert_parity --bf16-embd\n"
917                             "       native_expert_parity --load-check <pack> <model.gguf>  (start-up checks, no GPU load)\n"
918                             "       native_expert_parity --gguf-embd <model.gguf> [rows]   (token_embd rows vs to_float)\n"
919                             "       native_expert_parity --gguf-ple <model.gguf> [tokens]  (PLE rows via PleTable vs to_float)\n");
920        return 2;
921    }
922    // #152's width check tests the opt-in rule (the multi-token kernels from one token on)
923    if (std::getenv("STRATA_IQ_MT_MIN") == nullptr) {
924#ifdef _WIN32
925        _putenv_s("STRATA_IQ_MT_MIN", "1");
926#else
927        setenv("STRATA_IQ_MT_MIN", "1", 1);
928#endif
929    }
930    int failures = 0;
931    cudaStream_t s;
932    cudaStreamCreate(&s);
933    const std::string mode = argv[1];
934    if (mode == "--load-check" && argc >= 4) {
935        std::printf("load check: pack %s, GGUF %s\n", argv[2], argv[3]);
936        failures += check_load(argv[2], argv[3]);
937    } else if (mode == "--gguf-embd" && argc >= 3) {
938        failures += check_gguf_embd(argv[2], argc > 3 ? std::atoi(argv[3]) : 300, s);
939    } else if (mode == "--gguf-ple" && argc >= 3) {
940        failures += check_gguf_ple(argv[2], argc > 3 ? std::atoi(argv[3]) : 20);
941    } else if (mode == "--q5_1-min") {
942        failures += check_q5_1_min(s);
943    } else if (mode == "--bf16-embd") {
944        failures += check_bf16_embd(s);
945    } else if (mode == "--synthetic" || mode == "--synthetic-hadamard") {
946        // --synthetic-hadamard: the same with the layer Hadamard-folded (APR, prism.hadamard): random signs, block 128
947        const bool had = mode == "--synthetic-hadamard";
948        static std::vector<float> sx((size_t) H), sh((size_t) FF);
949        std::mt19937 srng(5);
950        for (auto& v : sx) v = (srng() & 1) ? 1.f : -1.f;
951        for (auto& v : sh) v = (srng() & 1) ? 1.f : -1.f;
952        bool bench = false;   // --bench: a decode micro-number per pair, after its checks
953        for (int i = 2; i < argc; ++i) bench = bench || std::string(argv[i]) == "--bench";
954        for (int i = 2; i < argc; ++i) {
955            const std::string arg = argv[i];
956            if (arg == "--bench") continue;
957            const size_t slash = arg.find('/');
958            const int gu = slash == std::string::npos ? -1 : type_of(arg.substr(0, slash));
959            const int dn = slash == std::string::npos ? -1 : type_of(arg.substr(slash + 1));
960            cpu::NativeFmt f;
961            std::string err;
962            // The synthetic check quantizes the blob with ggml and compares against ggml's to_float.  An upstream
963            // ggml (the MMQ overlay) has no traits for the trellis types (they sit above GGML_TYPE_COUNT), so the
964            // check needs a ggml that carries them (a build with -DSTRATA_GGML_DIR=<the agention llama.cpp>): skip it
965            // here with a message instead of reading past the type table.
966            if (gu >= (int) GGML_TYPE_COUNT || dn >= (int) GGML_TYPE_COUNT) {   // (ggml_type_name of an id past the table is not a null pointer: it reads past it)
967                std::printf("%s: skipped (this ggml has no trellis type traits: the check needs STRATA_GGML_DIR=<a "
968                            "llama.cpp with the trellis types>)\n", arg.c_str());
969                continue;
970            }
971            if (gu < 0 || dn < 0 || !cpu::native_fmt(gu, dn, H, FF, f, err) ||
972                !strata::kernels::native_expert_supported(gu, dn, H, FF)) {
973                std::printf("%s: %s\n", arg.c_str(), err.empty() ? "not a pair the GPU expert kernels take" : err.c_str());
974                ++failures;
975                continue;
976            }
977            if (had) {
978                f.had_block = 128;
979                f.had_gu = f.had_d = true;
980                f.gu_signs = sx.data();
981                f.d_signs = sh.data();
982            }
983            const std::vector<uint8_t> blob = synthetic_blob(f, i);
984            failures += check_blob(f, blob, i, had ? "hadamard" : "synthetic", s);
985            if (bench) bench_decode(f, blob, arg, s);
986        }
987    } else {
988        const strata::GgufModel model(strata::gguf_split_paths(argv[1]));
989        std::vector<int> layers;
990        for (int i = 2; i < argc; ++i) layers.push_back(std::atoi(argv[i]));
991        if (layers.empty()) layers = {0, 1, 2, 3, 20, 47};
992        for (int l : layers) {
993            const strata::TensorInfo* t[3] = {};
994            const uint8_t* data[3] = {};
995            const char* roles[3] = {"gate", "up", "down"};
996            for (int r = 0; r < 3; ++r) {   // each role from the shard that holds it
997                size_t at = 0;
998                t[r] = model.find("blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight", &at);
999                if (t[r]) data[r] = model.shard(at).tensor_data(*t[r]);
1000            }
1001            if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; }
1002            cpu::NativeFmt f;
1003            std::string err;
1004            if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) {
1005                std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue;
1006            }
1007            std::vector<uint8_t> blob(f.bytes);
1008            std::memcpy(blob.data(), data[0] + (size_t) E * f.up_off, f.up_off);
1009            std::memcpy(blob.data() + f.up_off, data[1] + (size_t) E * f.up_off, f.up_off);
1010            std::memcpy(blob.data() + f.down_off, data[2] + (size_t) E * (f.bytes - f.down_off),
1011                        f.bytes - f.down_off);
1012            failures += check_blob(f, blob, l, "layer " + std::to_string(l), s);
1013        }
1014    }
1015    std::printf("native_expert_parity: %d failures\n", failures);
1016    return failures ? 1 : 0;
1017}