okami.mom/strata

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

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

main
46.5 KiB954 linesraw
1// src/kernels/iq_nibble_parity.cpp - STRATA_EXPERT_NIBBLE (strata/core/expert_nibble.hpp): the 4-bit gate/up expert
2// slots against the production kernels and the GGUF blobs, bit for bit.
3//
4//     build/iq_nibble_parity --header                    the host half of expert_nibble.hpp (no GPU)
5//     build/iq_nibble_parity <shard.gguf> [<shard.gguf> ...] [--layers-per-fmt 2] [--layers 1,17] [--ne 512]
6//                            [--plans 8] [--synthetic 64] [--no-ggml] [--negative]
7//     build/iq_nibble_parity --synthetic-only [--synthetic 64] [--plans 8] [--no-ggml]      no model, no shard
8//
9// Each model (any shard of it; its other shards are opened beside it) gives `--layers-per-fmt` layers of each
10// converted format (IQ2_S, IQ3_XXS, IQ3_S; or `--layers`), `--ne` experts each, read from the GGUF tensors into the
11// blob the pack holds (gate rows, up rows, down rows).  Per layer:
12//   (1) nibble::transcode, 64 blobs a batch as the startup fill runs it: 0 items that do not round-trip;
13//   (2) every gate/up byte of a slot is written (8 slots transcoded again into another pre-fill byte);
14//   (3) nibble::hash_slots against nibble::hash_host on every slot read back (and a flipped byte must change it);
15//   (4) the host codec on every item: decode_item then encode_item gives the code back;
16//   (5) ggml's reference dequantizer (to_float) on every GGUF row against the weight the 4-bit slot gives through
17//       dequantize_row_iq2_s / _iq3_xxs / _iq3_s's own expression (code, scale byte, fp16 d): every weight, bit for bit;
18//   (6) nibble::check_gguf (the start-up check: the GGUF blocks rebuilt from every slot against the blob): 0 words
19//       differ; nibble::gather_gguf (the prompt path's MMQ gather) in groups of 16 and of 1..15 from a later first
20//       position: the rebuilt [gate | up] and the down rows byte for byte the blob's, the MMQ tail after the group zero;
21//   (7) native_expert_grouped on the converted slots (native_expert_layout_nib) against the same call on the GGUF
22//       blobs (native_expert_layout): hq and out byte for byte for every entry, and gate / up where the reference
23//       layout writes them - in the card's default layout (a GP100: mode 8, whose gate/up kernel writes hq) and in the
24//       CUDA layout (native_expert_set_mode(0)), each with native_grouped_set_v1 off and on (h too, in mode 0 + v1);
25//       top-10 routing T = 1..6 at 0% and 50% sharing (`--plans` each), one group of T entries (G = 1) per T, plans of
26//       groups with 0..11 entries (more than one GRP_NC pass, empty groups); grid_groups 0 (cap) and 4 (the PCIe
27//       call's stride); the default kernel per format and each skeleton forced (S, P); q8_1 activations random, all
28//       +127, all -127 and alternating +-127 (the sum of x at its extremes, +-4064).
29// `--synthetic N`: per format, N experts whose gate/up blocks are random bytes (every grid index, sign byte and scale
30// nibble the format has; the coverage is counted and must be complete) and whose fp16 d cycle through +-the smallest
31// subnormal, +-65504, +-1, the smallest normal and two ordinary values; checks (1)-(7) on them.
32// `--synthetic-only`: the synthetic experts alone, for every gate/up format x both down types (IQ4_NL, Q2_0), the down rows
33// random bytes with ordinary fp16 scales: checks (1)-(7) with no model file (a GP100 is still needed).
34// `--negative`: the control - one code byte per slot changed after the transcode; (6) and (7) must then report differences.
35// Exit 0 when every check is equal; 1 otherwise; 2 on a usage or setup error.  A build without STRATA_EXPERT_NIBBLE_BUILT
36// (the CUDA build with STRATA_EXPERIMENTAL_SM60) has no 4-bit kernels: --header only.
37#include "strata/artifact/gguf_reader.hpp"
38#include "strata/core/expert_nibble.hpp"
39#include "strata/kernels/cpu/native_expert.hpp"
40#include "strata/kernels/iq_kernels.hpp"
41
42#include "ggml.h"
43
44#include <cuda_runtime.h>
45
46#include <algorithm>
47#include <atomic>
48#include <cstdio>
49#include <cstdlib>
50#include <cstring>
51#include <memory>
52#include <random>
53#include <set>
54#include <string>
55#include <thread>
56#include <vector>
57
58namespace {
59
60namespace nib = strata::core::nibble;
61namespace K = strata::kernels;
62namespace cpu = strata::kernels::cpu;
63
64int fails = 0;
65void expect(bool ok, const char* what) {
66    if (!ok) {
67        std::printf("FAIL %s\n", what);
68        ++fails;
69    }
70}
71
72// Every value the format holds at every one of an item's 32 positions (the other positions cycle through the set),
73// encoded, decoded and compared; and one value outside the set must be refused.
74void round_trip(int fmt, const std::vector<int8_t>& set, int8_t outside) {
75    int8_t g[32], back[32];
76    uint32_t q[4];
77    for (size_t shift = 0; shift < set.size(); ++shift) {
78        for (int i = 0; i < 32; ++i) g[i] = set[(shift + (size_t) i) % set.size()];
79        const bool ok = nib::encode_item(fmt, g, q);
80        nib::decode_item(fmt, q, back);
81        expect(ok && std::memcmp(g, back, 32) == 0, (std::string(nib::fmt_name(fmt)) + " round trip").c_str());
82    }
83    for (int i = 0; i < 32; ++i) g[i] = set[0];
84    g[17] = outside;
85    expect(!nib::encode_item(fmt, g, q), (std::string(nib::fmt_name(fmt)) + " refuses a value outside the set").c_str());
86}
87
88int header_check() {
89    expect(nib::kGuBytes == 1766400 && nib::kScOff == 1638400 && nib::kDOff == 1740800, "layout sizes");
90    expect(nib::code_off(nib::kNFf, 0) == nib::kUpCodesOff, "up rows' codes");
91    expect(nib::slot_bytes_for(921600) % nib::kSlotAlign == 0, "slot alignment");
92    round_trip(nib::kIQ2_S, { 8, 25, 43, -8, -25, -43 }, 9);
93    round_trip(nib::kIQ3_XXS, { 4, 12, 20, 28, 36, 44, 52, 62, -4, -12, -20, -28, -36, -44, -52, -62 }, 5);
94    std::vector<int8_t> s3;
95    for (int v = -15; v <= 15; v += 2) s3.push_back((int8_t) v);
96    round_trip(nib::kIQ3_S, s3, 2);
97    // IQ2_S's nibble is the decode kernel's PRMT selector into {8,25,43,0} {-8,-25,-43,0}
98    {
99        int8_t g[32] = {}, back[32];
100        uint32_t q[4];
101        for (int i = 0; i < 32; ++i) g[i] = (int8_t) (i % 2 ? -25 : 43);
102        nib::encode_item(nib::kIQ2_S, g, q);
103        expect((q[0] & 0xFu) == 2u && (q[0] >> 4 & 0xFu) == 5u, "IQ2_S selector nibbles");
104        nib::decode_item(nib::kIQ2_S, q, back);
105        expect(std::memcmp(g, back, 32) == 0, "IQ2_S selector decode");
106    }
107    expect(nib::gu_skeleton(nib::kIQ2_S) == nib::kSkelP && nib::gu_skeleton(nib::kIQ3_XXS) == nib::kSkelS &&
108               nib::gu_skeleton(nib::kIQ3_S) == nib::kSkelS,
109           "kernel table");
110    {
111        const uint8_t b[6] = { 1, 2, 3, 4, 5, 6 };
112        const uint64_t h = nib::hash_host(b, 6);
113        const uint64_t want = (uint64_t) (0x04030201u ^ 0u) * nib::kHashMul + (uint64_t) (0x00000605u ^ 1u) * nib::kHashMul;
114        expect(h == want, "hash_host");
115    }
116    std::printf("%s (%d failures)\n", fails == 0 ? "header OK" : "header FAILED", fails);
117    return fails == 0 ? 0 : 1;
118}
119
120// ------------------------------------------------------------------------------------------------ the GPU parity
121
122#define CK(x)                                                                                                       \
123    do {                                                                                                            \
124        cudaError_t e_ = (x);                                                                                       \
125        if (e_ != cudaSuccess) {                                                                                    \
126            std::fprintf(stderr, "%s:%d %s: %s\n", __FILE__, __LINE__, #x, cudaGetErrorString(e_));                 \
127            std::exit(2);                                                                                           \
128        }                                                                                                           \
129    } while (0)
130
131struct Q81 {   // block_q8_1: fp16 d, fp16 s (= d * sum), 32 int8
132    uint16_t d, s;
133    int8_t qs[32];
134};
135static_assert(sizeof(Q81) == 36, "block_q8_1");
136
137constexpr int64_t kEmbd = nib::kNEmbd, kFf = nib::kNFf;
138constexpr int kTok = 12;   // activation rows: T <= 6 for routing plans, 12 for the 0..11-entry plans
139
140// One layer: `ne` GGUF blobs (gate rows | up rows | down rows, as the pack and the host arena hold them) on the host
141// and the device, and their converted slots.
142struct Layer {
143    std::string tag;
144    int layer = -1;
145    cpu::NativeFmt f;
146    nib::LayerVram V;
147    K::NativeExpertLayout Lr, Ln;
148    int ne = 0;
149    std::vector<uint8_t> host;   // ne x f.bytes
150    uint8_t* raw = nullptr;      // device copy of `host`
151    uint8_t* slots = nullptr;    // ne x V.slot_bytes (the last one only `hashed` long: nothing past it is readable)
152};
153
154bool layer_fmt(const strata::GgufModel& m, int l, int& gt, int& dt) {
155    const auto* g = m.find("blk." + std::to_string(l) + ".ffn_gate_exps.weight");
156    const auto* d = m.find("blk." + std::to_string(l) + ".ffn_down_exps.weight");
157    if (g == nullptr || d == nullptr) return false;
158    gt = (int) g->type;
159    dt = (int) d->type;
160    return true;
161}
162
163// The blobs of experts [0, ne) of layer l.
164bool read_layer(const strata::GgufModel& m, int l, int ne, Layer& Y) {
165    const char* roles[3] = { "gate", "up", "down" };
166    const strata::TensorInfo* t[3] = {};
167    size_t sh[3] = {};
168    for (int r = 0; r < 3; ++r) t[r] = m.find("blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight", &sh[r]);
169    if (!t[0] || !t[1] || !t[2]) return false;
170    std::string err;
171    if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, kEmbd, kFf, Y.f, err)) {
172        std::printf("layer %d: %s\n", l, err.c_str());
173        return false;
174    }
175    const size_t gu_role = Y.f.up_off, dn_role = Y.f.bytes - Y.f.down_off;
176    Y.layer = l;
177    Y.ne = ne;
178    Y.host.resize((size_t) ne * Y.f.bytes);
179    const uint8_t* G = m.shard(sh[0]).tensor_data(*t[0]);
180    const uint8_t* U = m.shard(sh[1]).tensor_data(*t[1]);
181    const uint8_t* D = m.shard(sh[2]).tensor_data(*t[2]);
182    for (int e = 0; e < ne; ++e) {
183        uint8_t* b = Y.host.data() + (size_t) e * Y.f.bytes;
184        std::memcpy(b, G + (size_t) e * gu_role, gu_role);
185        std::memcpy(b + Y.f.up_off, U + (size_t) e * gu_role, gu_role);
186        std::memcpy(b + Y.f.down_off, D + (size_t) e * dn_role, dn_role);
187    }
188    return true;
189}
190
191// check (6): nibble::check_gguf over every slot (the start-up check), and nibble::gather_gguf (the prompt path's gather)
192// in groups of 16 and from later first positions, against the blobs byte for byte (and the MMQ tail zeroed).
193// `expect_diff`: the negative control (only the report says so: the counts must then be > 0).
194long long gguf_parity(const Layer& Y, const unsigned long long* dp, bool expect_diff) {
195    long long bad_total = 0;
196    const int ne = Y.ne;
197    unsigned long long* dbad = nullptr;
198    CK(cudaMalloc(&dbad, 8));
199    CK(cudaMemset(dbad, 0, 8));
200    for (int e0 = 0; e0 < ne; e0 += 64) {
201        const int rc = nib::check_gguf(Y.V, Y.raw + (size_t) e0 * Y.V.raw_bytes, std::min(64, ne - e0), dp + e0, dbad, nullptr);
202        if (rc != 0) {
203            std::printf("check_gguf: %s\n", cudaGetErrorString((cudaError_t) rc));
204            std::exit(2);
205        }
206    }
207    CK(cudaDeviceSynchronize());
208    unsigned long long cbad = 0;
209    CK(cudaMemcpy(&cbad, dbad, 8, cudaMemcpyDeviceToHost));
210    CK(cudaFree(dbad));
211    // the gathers: MMQ's group buffers (16 experts of [gate | up] and of down, each followed by the 4096-byte tail)
212    const uint64_t gub = (uint64_t) nib::kRows * Y.f.gu_row, db = Y.V.down_bytes, zero = 4096;
213    uint8_t *ggu = nullptr, *gd = nullptr;
214    CK(cudaMalloc(&ggu, 16 * gub + zero));
215    CK(cudaMalloc(&gd, 16 * db + zero));
216    std::vector<uint8_t> hgu(16 * gub + zero), hd(16 * db + zero);
217    std::vector<unsigned long long> hp(ne);
218    CK(cudaMemcpy(hp.data(), dp, (size_t) ne * 8, cudaMemcpyDeviceToHost));
219    long long gbad = 0, groups = 0;
220    for (int e0 = 0; e0 < ne; e0 += 16) {
221        const int first = (e0 / 16) % 4 == 3 ? 1 + (e0 / 64) % 15 : 0;   // every 4th group from a later position
222        const int n = std::min(16, ne - e0);
223        if (first >= n) continue;
224        const uint8_t* sl[16] = {};
225        for (int q = first; q < n; ++q) sl[q] = (const uint8_t*) (uintptr_t) hp[(size_t) (e0 + q)];
226        CK(cudaMemset(ggu, 0xA5, 16 * gub + zero));
227        CK(cudaMemset(gd, 0xA5, 16 * db + zero));
228        const int rc = nib::gather_gguf(Y.V, sl, first, n, ggu, gub, gd, db, zero, nullptr);
229        if (rc != 0) {
230            std::printf("gather_gguf: %s\n", cudaGetErrorString((cudaError_t) rc));
231            std::exit(2);
232        }
233        CK(cudaDeviceSynchronize());
234        CK(cudaMemcpy(hgu.data(), ggu, hgu.size(), cudaMemcpyDeviceToHost));
235        CK(cudaMemcpy(hd.data(), gd, hd.size(), cudaMemcpyDeviceToHost));
236        for (int q = first; q < n; ++q) {
237            const uint8_t* raw = Y.host.data() + (size_t) (e0 + q) * Y.f.bytes;
238            gbad += std::memcmp(hgu.data() + (size_t) q * gub, raw, gub) != 0;
239            gbad += std::memcmp(hd.data() + (size_t) q * db, raw + Y.f.down_off, db) != 0;
240        }
241        for (uint64_t i = 0; i < zero; ++i) gbad += hgu[(size_t) n * gub + i] != 0 || hd[(size_t) n * db + i] != 0 ? 1 : 0;
242        ++groups;
243    }
244    CK(cudaFree(ggu));
245    CK(cudaFree(gd));
246    std::printf("    check_gguf: %llu words differ; gather_gguf (%lld groups, the tail zeroed): %lld matrices or tail bytes differ%s\n",
247                cbad, groups, gbad, expect_diff ? " (NEGATIVE CONTROL: both must be > 0)" : "");
248    bad_total += (long long) cbad + gbad;   // the negative control fails the run, as (7) does: it must
249    return bad_total;
250}
251
252// Plans the layer, uploads the blobs, transcodes them into slots (checks 1-6).
253long long convert(Layer& Y, bool ggml_check) {
254    long long bad_total = 0;
255    nib::Config c;
256    c.on = true;
257    Y.V = nib::plan_layer(Y.layer, Y.f, c);
258    Y.Lr = K::native_expert_layout(Y.f.gu_type, Y.f.d_type, kEmbd, kFf);
259    Y.Ln = K::native_expert_layout_nib(Y.f.gu_type, Y.f.d_type, kEmbd, kFf);
260    if (!Y.V.on || Y.V.slot_bytes != Y.Ln.bytes || Y.V.down_off != Y.Ln.down_off || Y.Lr.bytes != Y.f.bytes) {
261        std::printf("layer %d: plan_layer / native_expert_layout_nib disagree (on %d, slot %llu vs %zu)\n", Y.layer,
262                    (int) Y.V.on, (unsigned long long) Y.V.slot_bytes, Y.Ln.bytes);
263        return 1;
264    }
265    const int ne = Y.ne;
266    const size_t slots_bytes = (size_t) (ne - 1) * Y.V.slot_bytes + Y.V.hashed;
267    CK(cudaMalloc(&Y.raw, Y.host.size()));
268    CK(cudaMemcpy(Y.raw, Y.host.data(), Y.host.size(), cudaMemcpyHostToDevice));
269    CK(cudaMalloc(&Y.slots, slots_bytes));
270    CK(cudaMemset(Y.slots, 0xA5, slots_bytes));
271    std::vector<unsigned long long> hp(ne);
272    for (int e = 0; e < ne; ++e) hp[e] = (unsigned long long) (Y.slots + (size_t) e * Y.V.slot_bytes);
273    unsigned long long *dp = nullptr, *dbad = nullptr, *dhash = nullptr;
274    CK(cudaMalloc(&dp, (size_t) ne * 8));
275    CK(cudaMalloc(&dbad, 8));
276    CK(cudaMalloc(&dhash, (size_t) ne * 8));
277    CK(cudaMemcpy(dp, hp.data(), (size_t) ne * 8, cudaMemcpyHostToDevice));
278    CK(cudaMemset(dbad, 0, 8));
279    // (1) the startup fill's batches: 64 blobs at a time, then the down rows behind the codes
280    for (int e0 = 0; e0 < ne; e0 += 64) {
281        const int n = std::min(64, ne - e0);
282        const int rc = nib::transcode(Y.V, Y.raw + (size_t) e0 * Y.V.raw_bytes, n, dp + e0, dbad, nullptr);
283        if (rc != 0) {
284            std::printf("transcode: %s\n", cudaGetErrorString((cudaError_t) rc));
285            std::exit(2);
286        }
287    }
288    for (int e = 0; e < ne; ++e)
289        CK(cudaMemcpyAsync(Y.slots + (size_t) e * Y.V.slot_bytes + nib::kDownOff,
290                           Y.raw + (size_t) e * Y.V.raw_bytes + Y.V.raw_down_off, Y.V.down_bytes, cudaMemcpyDeviceToDevice));
291    CK(cudaDeviceSynchronize());
292    unsigned long long bad = 0;
293    CK(cudaMemcpy(&bad, dbad, 8, cudaMemcpyDeviceToHost));
294    std::printf("%s layer %2d %-7s / down %-6s: %d experts, blob %zu B, slot %llu B (x%.3f); transcode: %llu of %lld items do not round-trip\n",
295                Y.tag.c_str(), Y.layer, nib::fmt_name(Y.f.gu_type), ggml_type_name((ggml_type) Y.f.d_type), ne, Y.f.bytes,
296                (unsigned long long) Y.V.slot_bytes, (double) Y.V.slot_bytes / (double) Y.f.bytes, bad,
297                (long long) ne * nib::kRows * nib::kItems);
298    bad_total += (long long) bad;
299    bad_total += gguf_parity(Y, dp, false);
300    // (2) every gate/up byte written: the first 8 blobs again into slots pre-filled with 0x5A
301    {
302        const int n8 = std::min(8, ne);
303        uint8_t* alt = nullptr;
304        unsigned long long* ap = nullptr;
305        CK(cudaMalloc(&alt, (size_t) n8 * Y.V.slot_bytes));
306        CK(cudaMemset(alt, 0x5A, (size_t) n8 * Y.V.slot_bytes));
307        std::vector<unsigned long long> ah(n8);
308        for (int e = 0; e < n8; ++e) ah[e] = (unsigned long long) (alt + (size_t) e * Y.V.slot_bytes);
309        CK(cudaMalloc(&ap, (size_t) n8 * 8));
310        CK(cudaMemcpy(ap, ah.data(), (size_t) n8 * 8, cudaMemcpyHostToDevice));
311        CK(cudaMemset(dbad, 0, 8));
312        if (nib::transcode(Y.V, Y.raw, n8, ap, dbad, nullptr) != 0) std::exit(2);
313        CK(cudaDeviceSynchronize());
314        std::vector<uint8_t> a(nib::kGuBytes), b(nib::kGuBytes);
315        long long wbad = 0;
316        for (int e = 0; e < n8; ++e) {
317            CK(cudaMemcpy(a.data(), Y.slots + (size_t) e * Y.V.slot_bytes, nib::kGuBytes, cudaMemcpyDeviceToHost));
318            CK(cudaMemcpy(b.data(), alt + (size_t) e * Y.V.slot_bytes, nib::kGuBytes, cudaMemcpyDeviceToHost));
319            wbad += std::memcmp(a.data(), b.data(), nib::kGuBytes) != 0;
320        }
321        std::printf("    every gate/up byte written (0xA5 vs 0x5A pre-fill, %d slots): %lld differ\n", n8, wbad);
322        bad_total += wbad;
323        CK(cudaFree(alt));
324        CK(cudaFree(ap));
325    }
326    // (3) the device hash of every slot against the host reference over the slot read back
327    const int rc = nib::hash_slots(Y.V, dp, ne, dhash, nullptr);
328    if (rc != 0) {
329        std::printf("hash_slots: %s\n", cudaGetErrorString((cudaError_t) rc));
330        std::exit(2);
331    }
332    std::vector<unsigned long long> hh(ne);
333    CK(cudaMemcpy(hh.data(), dhash, (size_t) ne * 8, cudaMemcpyDeviceToHost));
334    std::vector<uint8_t> sl(slots_bytes);
335    CK(cudaMemcpy(sl.data(), Y.slots, slots_bytes, cudaMemcpyDeviceToHost));
336    std::atomic<long long> hbad{ 0 }, cbad{ 0 }, dnbad{ 0 }, gbad{ 0 };
337    std::atomic<long long> grows{ 0 };
338    std::string first_ggml;
339    std::atomic<int> first_set{ 0 };
340    const ggml_type_traits* tr = ggml_get_type_traits((ggml_type) Y.f.gu_type);
341    const unsigned nth = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
342    std::vector<std::thread> th;
343    for (unsigned ti = 0; ti < nth; ++ti)
344        th.emplace_back([&, ti]() {
345            std::vector<float> ref((size_t) kEmbd), got((size_t) kEmbd);
346            for (int e = (int) ti; e < ne; e += (int) nth) {
347                const uint8_t* s = sl.data() + (size_t) e * Y.V.slot_bytes;
348                const uint8_t* raw = Y.host.data() + (size_t) e * Y.f.bytes;
349                hbad += nib::hash_host(s, Y.V.hashed) != hh[e];
350                if (e == 0) {   // the hash sees every byte: one flipped must change it
351                    std::vector<uint8_t> t2(s, s + Y.V.hashed);
352                    t2[Y.V.hashed - 1] ^= 1;
353                    hbad += nib::hash_host(t2.data(), Y.V.hashed) == hh[e];
354                }
355                dnbad += std::memcmp(s + nib::kDownOff, raw + Y.V.raw_down_off, Y.V.down_bytes) != 0;
356                for (int64_t r = 0; r < nib::kRows; ++r) {
357                    // (4) the host codec
358                    for (int64_t k = 0; k < nib::kItems; ++k) {
359                        uint32_t q[4], q2[4];
360                        int8_t g[32];
361                        std::memcpy(q, s + nib::code_off(r, k), 16);
362                        nib::decode_item(Y.f.gu_type, q, g);
363                        const bool ok = nib::encode_item(Y.f.gu_type, g, q2);
364                        cbad += !ok || std::memcmp(q, q2, 16) != 0;
365                    }
366                    if (!ggml_check) continue;
367                    // (5) ggml's dequantizer of the GGUF row against the slot's weights through its expression
368                    const uint8_t* row = raw + (r < kFf ? (size_t) r * Y.f.gu_row : Y.f.up_off + (size_t) (r - kFf) * Y.f.gu_row);
369                    tr->to_float(row, ref.data(), kEmbd);
370                    for (int64_t k = 0; k < nib::kItems; ++k) {
371                        uint32_t q[4];
372                        std::memcpy(q, s + nib::code_off(r, k), 16);
373                        int8_t gv[32];
374                        nib::decode_item(Y.f.gu_type, q, gv);
375                        const int sc = s[nib::scale_off(r, k)];
376                        ggml_fp16_t dh;
377                        std::memcpy(&dh, s + nib::d_off(r, k / 8), sizeof dh);
378                        const float d = ggml_fp16_to_fp32(dh);
379                        for (int j = 0; j < 32; ++j) {
380                            const float db = Y.f.gu_type == nib::kIQ2_S   ? d * (0.5f + ((j < 16 ? sc : sc >> 4) & 0xf)) * 0.25f
381                                           : Y.f.gu_type == nib::kIQ3_XXS ? d * (0.5f + sc) * 0.5f
382                                                                          : d * sc;
383                            const int a = gv[j] < 0 ? -(int) gv[j] : (int) gv[j];
384                            float v = db * a;
385                            if (gv[j] < 0) v = -v;
386                            got[(size_t) (k * 32 + j)] = v;
387                        }
388                    }
389                    ++grows;
390                    if (std::memcmp(ref.data(), got.data(), ref.size() * sizeof(float)) != 0) {
391                        ++gbad;
392                        if (first_set.exchange(1) == 0) {
393                            size_t cc = 0;
394                            while (cc < ref.size() && std::memcmp(&ref[cc], &got[cc], 4) == 0) ++cc;
395                            char buf[200];
396                            std::snprintf(buf, sizeof buf, "expert %d row %lld column %zu: slot %.9g, GGUF %.9g", e,
397                                          (long long) r, cc, (double) got[cc], (double) ref[cc]);
398                            first_ggml = buf;
399                        }
400                    }
401                }
402            }
403        });
404    for (auto& t : th) t.join();
405    std::printf("    hash_slots vs hash_host: %lld of %d slots differ (+1 flipped-byte check); down rows: %lld of %d slots differ;"
406                " host codec: %lld of %lld items differ\n",
407                hbad.load(), ne, dnbad.load(), ne, cbad.load(), (long long) ne * nib::kRows * nib::kItems);
408    if (ggml_check)
409        std::printf("    ggml to_float of the GGUF rows vs the slot's weights: %lld of %lld rows differ%s%s\n", gbad.load(),
410                    grows.load(), first_ggml.empty() ? "" : "; first: ", first_ggml.c_str());
411    bad_total += hbad + dnbad + cbad + gbad;
412    CK(cudaFree(dp));
413    CK(cudaFree(dbad));
414    CK(cudaFree(dhash));
415    return bad_total;
416}
417
418// ---- plans: synthetic top-10 routing and resident_plan_kernel's grouping (groups by first appearance)
419struct Plan {
420    int ng = 0, ne = 0, ntok = 0, maxn = 0;
421    std::vector<int> gid, start, tok, dst;
422};
423
424void make_routing(std::mt19937& rng, int NE, int T, int share_pct, std::vector<int>& ids) {
425    ids.clear();
426    std::vector<int> prev, cur;
427    for (int t = 0; t < T; ++t) {
428        cur.clear();
429        const bool sh = t > 0 && share_pct > 0;
430        if (sh) {
431            std::vector<int> p = prev;
432            std::shuffle(p.begin(), p.end(), rng);
433            cur.assign(p.begin(), p.begin() + 10 * share_pct / 100);
434        }
435        while ((int) cur.size() < 10) {
436            const int e = (int) (rng() % (unsigned) NE);
437            if (std::find(cur.begin(), cur.end(), e) != cur.end()) continue;
438            if (sh && std::find(prev.begin(), prev.end(), e) != prev.end()) continue;
439            cur.push_back(e);
440        }
441        std::shuffle(cur.begin(), cur.end(), rng);
442        ids.insert(ids.end(), cur.begin(), cur.end());
443        prev = cur;
444    }
445}
446
447Plan build_plan(const std::vector<int>& ids) {
448    const int n = (int) ids.size();
449    Plan p;
450    std::vector<int> first(n), cnt, grp_of(n, -1);
451    for (int j = 0; j < n; ++j) {
452        int f = j;
453        for (int i = 0; i < j; ++i)
454            if (ids[i] == ids[j]) { f = i; break; }
455        first[j] = f;
456    }
457    for (int j = 0; j < n; ++j)
458        if (first[j] == j) {
459            grp_of[j] = p.ng++;
460            p.gid.push_back(ids[j]);
461            cnt.push_back(0);
462        }
463    for (int j = 0; j < n; ++j) cnt[grp_of[first[j]]]++;
464    p.start.assign(p.ng + 1, 0);
465    int acc = 0;
466    for (int g = 0; g < p.ng; ++g) {
467        p.start[g] = acc;
468        acc += cnt[g];
469        p.maxn = std::max(p.maxn, cnt[g]);
470    }
471    p.start[p.ng] = acc;
472    p.tok.assign(n, 0);
473    p.dst.assign(n, 0);
474    std::vector<int> fill(p.ng, 0);
475    for (int j = 0; j < n; ++j) {
476        const int g = grp_of[first[j]];
477        const int at = p.start[g] + fill[g]++;
478        p.tok[at] = j / 10;
479        p.dst[at] = j;
480    }
481    p.ne = n;
482    p.ntok = n / 10;
483    return p;
484}
485
486// one group of T entries (G = 1): an expert every token of the window routes to
487Plan single_group(std::mt19937& rng, int NE, int T) {
488    Plan p;
489    p.ntok = T;
490    p.ng = 1;
491    p.gid.push_back((int) (rng() % (unsigned) NE));
492    p.start = { 0, T };
493    for (int t = 0; t < T; ++t) {
494        p.tok.push_back(t);
495        p.dst.push_back(T - 1 - t);
496    }
497    p.ne = T;
498    p.maxn = T;
499    return p;
500}
501
502// groups of 0..11 entries (more than one GRP_NC pass, empty groups), 12 tokens, distinct tokens within a group,
503// destination rows in any order
504Plan synthetic_plan(std::mt19937& rng, int NE) {
505    Plan p;
506    p.ntok = kTok;
507    std::vector<int> ids(NE);
508    for (int i = 0; i < NE; ++i) ids[i] = i;
509    std::shuffle(ids.begin(), ids.end(), rng);
510    const int sizes[] = { 3, 0, 11, 1, 5, 8, 0, 2, 4, 9, 6, 7, 10, 1 };
511    int acc = 0;
512    for (int g = 0; g < (int) (sizeof sizes / sizeof sizes[0]); ++g) {
513        p.gid.push_back(ids[(size_t) g % ids.size()]);
514        p.start.push_back(acc);
515        std::vector<int> toks(kTok);
516        for (int i = 0; i < kTok; ++i) toks[i] = i;
517        std::shuffle(toks.begin(), toks.end(), rng);
518        std::sort(toks.begin(), toks.begin() + sizes[g]);
519        for (int i = 0; i < sizes[g]; ++i) {
520            p.tok.push_back(toks[i]);
521            p.dst.push_back(acc + i);
522        }
523        acc += sizes[g];
524        p.maxn = std::max(p.maxn, sizes[g]);
525    }
526    p.start.push_back(acc);
527    p.ng = (int) p.gid.size();
528    p.ne = acc;
529    std::vector<int> perm(acc);
530    for (int i = 0; i < acc; ++i) perm[i] = i;
531    std::shuffle(perm.begin(), perm.end(), rng);
532    for (int i = 0; i < acc; ++i) p.dst[i] = perm[i];
533    return p;
534}
535
536std::vector<Q81> make_x(std::mt19937& rng) {
537    std::vector<Q81> x((size_t) kTok * (kEmbd / 32));
538    for (size_t i = 0; i < x.size(); ++i) {
539        Q81& b = x[i];
540        const int tok = (int) (i / (kEmbd / 32));
541        const float d = 0.002f + 0.03f * (float) (rng() % 1000) / 1000.0f;
542        int sum = 0;
543        for (int j = 0; j < 32; ++j) {
544            int q = (int) (rng() % 255) - 127;
545            if (tok == 1) q = 127;   // the sum of x at its extremes (+-4064)
546            if (tok == 2) q = -127;
547            if (tok == 3 && (i % (kEmbd / 32)) < 8) q = (j & 1) ? 127 : -127;
548            b.qs[j] = (int8_t) q;
549            sum += q;
550        }
551        b.d = ggml_fp32_to_fp16(d);
552        b.s = ggml_fp32_to_fp16(d * (float) sum);
553    }
554    return x;
555}
556
557struct Dev {
558    unsigned long long* ptr = nullptr;
559    int32_t *start = nullptr, *ng = nullptr, *tok = nullptr, *dst = nullptr;
560};
561Dev upload(const Plan& p, const Layer& Y, bool conv) {
562    Dev d;
563    std::vector<unsigned long long> hp(std::max(1, p.ng));
564    for (int g = 0; g < p.ng; ++g)
565        hp[g] = conv ? (unsigned long long) (Y.slots + (size_t) p.gid[g] * Y.V.slot_bytes)
566                     : (unsigned long long) (Y.raw + (size_t) p.gid[g] * Y.f.bytes);
567    CK(cudaMalloc(&d.ptr, (size_t) std::max(1, p.ng) * 8));
568    CK(cudaMalloc(&d.start, (size_t) (p.ng + 1) * 4));
569    CK(cudaMalloc(&d.ng, 4));
570    CK(cudaMalloc(&d.tok, (size_t) std::max(1, p.ne) * 4));
571    CK(cudaMalloc(&d.dst, (size_t) std::max(1, p.ne) * 4));
572    CK(cudaMemcpy(d.ptr, hp.data(), hp.size() * 8, cudaMemcpyHostToDevice));
573    CK(cudaMemcpy(d.start, p.start.data(), (size_t) (p.ng + 1) * 4, cudaMemcpyHostToDevice));
574    CK(cudaMemcpy(d.ng, &p.ng, 4, cudaMemcpyHostToDevice));
575    if (p.ne) {
576        CK(cudaMemcpy(d.tok, p.tok.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice));
577        CK(cudaMemcpy(d.dst, p.dst.data(), (size_t) p.ne * 4, cudaMemcpyHostToDevice));
578    }
579    return d;
580}
581void release(Dev& d) {
582    CK(cudaFree(d.ptr));
583    CK(cudaFree(d.start));
584    CK(cudaFree(d.ng));
585    CK(cudaFree(d.tok));
586    CK(cudaFree(d.dst));
587}
588
589struct Outs {
590    std::vector<uint8_t> gate, up, h, hq, out;
591};
592// one native_expert_grouped call; scratch and out pre-filled with `fill` so an unwritten value shows
593Outs run(const Layer& Y, const Plan& p, bool conv, const void* dx, void* scr, float* dout, int64_t gy, int mode,
594         uint8_t fill) {
595    // the window's capacity, as verify sizes it: T x 10 groups and entries (the blocks past the plan's groups idle)
596    const int64_t cap_e = std::max<int64_t>((int64_t) p.ntok * 10, std::max(p.ne, p.ng)), cap_g = cap_e;
597    Dev d = upload(p, Y, conv);
598    CK(cudaMemset(scr, fill, K::native_expert_scratch_bytes(cap_e, kFf)));
599    CK(cudaMemset(dout, fill, (size_t) cap_e * kEmbd * 4));
600    K::native_expert_set_mode(mode, 0);
601    K::native_expert_grouped(conv ? Y.Ln : Y.Lr, d.ptr, d.start, d.ng, d.dst, d.tok, cap_g, cap_e, dx, scr, dout, nullptr, gy);
602    K::native_expert_set_mode(-1, 0);
603    CK(cudaGetLastError());
604    CK(cudaDeviceSynchronize());
605    const size_t f = (size_t) cap_e * kFf * 4, fa = (f + 255) & ~(size_t) 255;
606    Outs o;
607    o.gate.resize((size_t) p.ne * kFf * 4);
608    o.up.resize(o.gate.size());
609    o.h.resize(o.gate.size());
610    o.hq.resize((size_t) p.ne * (kFf / 32) * 36);
611    o.out.resize((size_t) p.ne * kEmbd * 4);
612    const uint8_t* s = (const uint8_t*) scr;
613    if (p.ne) {
614        CK(cudaMemcpy(o.gate.data(), s, o.gate.size(), cudaMemcpyDeviceToHost));
615        CK(cudaMemcpy(o.up.data(), s + fa, o.up.size(), cudaMemcpyDeviceToHost));
616        CK(cudaMemcpy(o.h.data(), s + 2 * fa, o.h.size(), cudaMemcpyDeviceToHost));
617        CK(cudaMemcpy(o.hq.data(), s + 3 * fa, o.hq.size(), cudaMemcpyDeviceToHost));
618        std::vector<uint8_t> all((size_t) cap_e * kEmbd * 4);
619        CK(cudaMemcpy(all.data(), dout, all.size(), cudaMemcpyDeviceToHost));
620        for (int e = 0; e < p.ne; ++e)
621            std::memcpy(o.out.data() + (size_t) e * kEmbd * 4, all.data() + (size_t) p.dst[e] * kEmbd * 4, kEmbd * 4);
622    }
623    release(d);
624    return o;
625}
626
627long long diff_rows(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b, size_t row) {
628    long long n = 0;
629    for (size_t i = 0; i + row <= a.size(); i += row) n += std::memcmp(a.data() + i, b.data() + i, row) != 0;
630    return n;
631}
632
633// check (7): every plan, both grid strides, every kernel choice, both layouts, v1 off / on, against the GGUF blobs
634// through the production kernels
635long long grouped_parity(const Layer& Y, std::mt19937& rng, int plans, const void* dx, void* scr, float* dout) {
636    struct Case {
637        Plan p;
638        int T;
639    };
640    std::vector<Case> cases;
641    for (int T = 1; T <= 6; ++T) {
642        for (int share : { 0, 50 })
643            for (int i = 0; i < plans; ++i) {
644                std::vector<int> ids;
645                make_routing(rng, Y.ne, T, share, ids);
646                cases.push_back({ build_plan(ids), T });
647            }
648        cases.push_back({ single_group(rng, Y.ne, T), T });
649    }
650    for (int i = 0; i < 4; ++i) cases.push_back({ synthetic_plan(rng, Y.ne), kTok });
651    int hist[13] = {};
652    for (const Case& cs : cases)
653        for (int g = 0; g < cs.p.ng; ++g) hist[std::min(12, cs.p.start[g + 1] - cs.p.start[g])]++;
654    struct Var {
655        int v, mode;
656        bool v1;
657        const char* name;
658    };
659    // mode -1: the card's default layout (a GP100: mode 8 - its reference gate/up kernel writes hq, not gate / up);
660    // mode 0: the CUDA layout
661    const Var vars[] = { { -1, -1, false, "default, card" }, { 0, -1, false, "S, card" }, { 1, -1, false, "P, card" },
662                         { -1, -1, true, "default, card, V1" }, { -1, 0, false, "default, mode 0" },
663                         { 0, 0, false, "S, mode 0" }, { 1, 0, false, "P, mode 0" }, { -1, 0, true, "default, mode 0, V1" },
664                         // STRATA_NIB_GU_PROTO (nib_gu_proto.cuh): the staged-once kernel, id 31
665                         { 31, -1, false, "gu-proto 31, card" }, { 31, 0, false, "gu-proto 31, mode 0" },
666                         { 31, 0, true, "gu-proto 31, mode 0, V1" } };
667    constexpr int NV = (int) (sizeof vars / sizeof vars[0]);
668    long long rows[NV] = {}, bad[NV][5] = {}, total = 0;
669    for (const Case& cs : cases)
670        for (int64_t gy : { (int64_t) 0, (int64_t) 4 }) {
671            Outs ref[2][2];   // [mode 0][v1]
672            bool have[2][2] = {};
673            for (int vi = 0; vi < NV; ++vi) {
674                const int m0 = vars[vi].mode == 0 ? 1 : 0, r1 = vars[vi].v1 ? 1 : 0;
675                K::native_grouped_set_v1(vars[vi].v1);
676                if (!have[m0][r1]) {
677                    K::native_expert_nib_set_variant(-1);
678                    ref[m0][r1] = run(Y, cs.p, false, dx, scr, dout, gy, vars[vi].mode, 0xFF);
679                    have[m0][r1] = true;
680                }
681                K::native_expert_nib_set_variant(vars[vi].v);
682                const Outs o = run(Y, cs.p, true, dx, scr, dout, gy, vars[vi].mode, 0x00);
683                rows[vi] += cs.p.ne;
684                // gate / up: written by both arms in the CUDA layout, and by every arm of a striding call (gy 4: mode 0)
685                const bool gu = vars[vi].mode == 0 || gy == 4;
686                if (gu) {
687                    bad[vi][0] += diff_rows(ref[m0][r1].gate, o.gate, kFf * 4);
688                    bad[vi][1] += diff_rows(ref[m0][r1].up, o.up, kFf * 4);
689                }
690                if (vars[vi].v1 && gu) bad[vi][2] += diff_rows(ref[m0][r1].h, o.h, kFf * 4);
691                bad[vi][3] += diff_rows(ref[m0][r1].hq, o.hq, (kFf / 32) * 36);
692                bad[vi][4] += diff_rows(ref[m0][r1].out, o.out, kEmbd * 4);
693            }
694        }
695    K::native_expert_nib_set_variant(-1);
696    K::native_grouped_set_v1(false);
697    std::printf("    plans: %zu (T 1..6 x sharing 0/50%% x %d, G=1 per T, 4 of 0..11 entries); groups by entries:", cases.size(),
698                plans);
699    for (int n = 0; n <= 12; ++n) std::printf(" %d:%d", n, hist[n]);
700    std::printf("\n");
701    for (int vi = 0; vi < NV; ++vi) {
702        const long long b = bad[vi][0] + bad[vi][1] + bad[vi][2] + bad[vi][3] + bad[vi][4];
703        std::printf("    native_expert_grouped %-20s: %6lld entries x 2 strides, rows differing: gate %lld, up %lld, h %s, hq %lld, out %lld\n",
704                    vars[vi].name, rows[vi], bad[vi][0], bad[vi][1],
705                    vars[vi].v1 ? std::to_string(bad[vi][2]).c_str() : "-", bad[vi][3], bad[vi][4]);
706        total += b;
707    }
708    return total;
709}
710
711// --synthetic: random gate/up blocks, d cycling through the fp16 extremes; the coverage of each field is counted
712long long synthesize(Layer& Y, std::mt19937& rng) {
713    static const uint16_t kD[] = { 0x0001, 0x8001, 0x7BFF, 0xFBFF, 0x3C00, 0xBC00, 0x0400, 0x1A00, 0x2400 };
714    const int gt = Y.f.gu_type;
715    const size_t bb = gt == nib::kIQ2_S ? 82 : gt == nib::kIQ3_XXS ? 98 : 110;   // block_iq2_s / iq3_xxs / iq3_s
716    const size_t nblk = (size_t) nib::kRows * nib::kSuper;
717    std::set<int> grid, sign, scale, dset;
718    for (int e = 0; e < Y.ne; ++e) {
719        uint8_t* b = Y.host.data() + (size_t) e * Y.f.bytes;
720        for (size_t i = 0; i < 2 * Y.f.up_off; ++i) b[i] = (uint8_t) rng();
721        for (size_t k = 0; k < nblk; ++k) {
722            uint8_t* blk = b + k * bb;
723            const uint16_t d = kD[((size_t) e * nblk + k) % (sizeof kD / sizeof kD[0])];
724            std::memcpy(blk, &d, 2);
725            dset.insert(d);
726            const uint8_t* qs = blk + 2;
727            for (int ib = 0; ib < 8; ++ib) {
728                if (gt == nib::kIQ2_S) {
729                    const uint8_t* qh = blk + 66;
730                    const uint8_t* sc = blk + 74;
731                    for (int l = 0; l < 4; ++l) {
732                        grid.insert(qs[4 * ib + l] | ((qh[ib] << (8 - 2 * l)) & 0x300));
733                        sign.insert(qs[32 + 4 * ib + l]);
734                    }
735                    scale.insert(sc[ib] & 15);
736                    scale.insert(sc[ib] >> 4);
737                } else if (gt == nib::kIQ3_XXS) {
738                    uint32_t aux;
739                    std::memcpy(&aux, blk + 66 + 4 * ib, 4);
740                    for (int l = 0; l < 8; ++l) grid.insert(qs[8 * ib + l]);
741                    for (int l = 0; l < 4; ++l) sign.insert((int) ((aux >> (7 * l)) & 127));
742                    scale.insert((int) (aux >> 28));
743                } else {
744                    const uint8_t qh = blk[66 + ib];
745                    const uint8_t* sg = blk + 74;
746                    const uint8_t* sc = blk + 106;
747                    for (int l = 0; l < 4; ++l) {
748                        grid.insert(qs[8 * ib + 2 * l] | ((qh << (8 - 2 * l)) & 256));
749                        grid.insert(qs[8 * ib + 2 * l + 1] | ((qh << (7 - 2 * l)) & 256));
750                        sign.insert(sg[4 * ib + l]);
751                    }
752                    scale.insert((sc[ib / 2] >> (4 * (ib & 1))) & 15);
753                }
754            }
755        }
756    }
757    const size_t want_grid = gt == nib::kIQ2_S ? 1024 : gt == nib::kIQ3_XXS ? 256 : 512;
758    const size_t want_sign = gt == nib::kIQ3_XXS ? 128 : 256;
759    const bool ok = grid.size() == want_grid && sign.size() == want_sign && scale.size() == 16 &&
760                    dset.size() == sizeof kD / sizeof kD[0];
761    std::printf("synthetic %-7s: %d experts, coverage: grid indices %zu/%zu, sign %s %zu/%zu, scale nibbles %zu/16, d values %zu/%zu"
762                " (+-min subnormal, +-65504, +-1, min normal, 2 ordinary) %s\n",
763                nib::fmt_name(gt), Y.ne, grid.size(), want_grid, gt == nib::kIQ3_XXS ? "indices" : "bytes", sign.size(),
764                want_sign, scale.size(), dset.size(), sizeof kD / sizeof kD[0], ok ? "complete" : "INCOMPLETE");
765    return ok ? 0 : 1;
766}
767
768std::vector<int> split_ints(const std::string& s) {
769    std::vector<int> v;
770    size_t p = 0;
771    while (p < s.size()) {
772        v.push_back(std::atoi(s.c_str() + p));
773        p = s.find(',', p);
774        if (p == std::string::npos) break;
775        ++p;
776    }
777    return v;
778}
779
780}  // namespace
781
782int main(int argc, char** argv) {
783    setvbuf(stdout, nullptr, _IONBF, 0);
784    if (argc == 2 && std::strcmp(argv[1], "--header") == 0) return header_check();
785    std::vector<std::string> shards;
786    int per_fmt = 2, NE = 512, plans = 8, syn = 64;
787    bool ggml_check = true, negative = false, syn_only = false;
788    std::vector<int> only;
789    for (int i = 1; i < argc; ++i) {
790        const std::string a = argv[i];
791        auto next = [&]() -> const char* {
792            if (i + 1 >= argc) {
793                std::fprintf(stderr, "%s needs a value\n", a.c_str());
794                std::exit(2);
795            }
796            return argv[++i];
797        };
798        if (a == "--layers-per-fmt") per_fmt = std::atoi(next());
799        else if (a == "--layers") only = split_ints(next());
800        else if (a == "--ne") NE = std::atoi(next());
801        else if (a == "--plans") plans = std::atoi(next());
802        else if (a == "--synthetic") syn = std::atoi(next());
803        else if (a == "--no-ggml") ggml_check = false;
804        else if (a == "--negative") negative = true;
805        else if (a == "--synthetic-only") syn_only = true;
806        else if (a.size() > 5 && a.substr(a.size() - 5) == ".gguf") shards.push_back(a);
807        else {
808            std::fprintf(stderr,
809                         "usage: iq_nibble_parity --header\n"
810                         "       iq_nibble_parity <shard.gguf> [<shard.gguf> ...] [--layers-per-fmt 2] [--layers 1,17] [--ne 512]\n"
811                         "                        [--plans 8] [--synthetic 64] [--no-ggml] [--negative]\n"
812                         "       iq_nibble_parity --synthetic-only [--synthetic 64] [--plans 8] [--no-ggml]\n");
813            return 2;
814        }
815    }
816    if ((shards.empty() && !syn_only) || NE < 16 || NE > 512) {
817        std::fprintf(stderr, "iq_nibble_parity: give at least one model shard (.gguf); --ne 16..512\n");
818        return 2;
819    }
820    CK(cudaSetDevice(0));
821    cudaDeviceProp prop{};
822    CK(cudaGetDeviceProperties(&prop, 0));
823    char bus[64] = {};
824    CK(cudaDeviceGetPCIBusId(bus, sizeof bus, 0));
825    std::printf("device 0: %s, bus %s, cc %d.%d, %d SMs\n", prop.name, bus, prop.major, prop.minor, prop.multiProcessorCount);
826    if (prop.major != 6 || prop.minor != 0) {
827        std::fprintf(stderr, "iq_nibble_parity: the 4-bit kernels are the sm_60 build's; this GPU is cc %d.%d (skipped)\n",
828                     prop.major, prop.minor);
829        return 77;
830    }
831    if (!STRATA_EXPERT_NIBBLE_BUILT || nib::prepare(nullptr) != 0) {
832        std::fprintf(stderr, "iq_nibble_parity: no 4-bit kernels in this build, or the GGUF codebooks are not unique\n");
833        return 2;
834    }
835    std::mt19937 rng(20261019);
836    void* scr = nullptr;
837    float* dout = nullptr;
838    void* dx = nullptr;
839    const int64_t capmax = (int64_t) kTok * 10;
840    CK(cudaMalloc(&scr, K::native_expert_scratch_bytes(capmax, kFf)));
841    CK(cudaMalloc((void**) &dout, (size_t) capmax * kEmbd * 4));
842    const std::vector<Q81> hx = make_x(rng);
843    CK(cudaMalloc(&dx, hx.size() * sizeof(Q81)));
844    CK(cudaMemcpy(dx, hx.data(), hx.size() * sizeof(Q81), cudaMemcpyHostToDevice));
845
846    if (syn_only) {   // no model: every gate/up format with each down type, random experts
847        long long total_s = 0;
848        int done = 0;
849        for (const int gt : {nib::kIQ2_S, nib::kIQ3_XXS, nib::kIQ3_S})
850            for (const int dt : {20, 42}) {   // the packs' down types: IQ4_NL, Q2_0
851                Layer S;
852                std::string err;
853                if (!cpu::native_fmt(gt, dt, kEmbd, kFf, S.f, err)) {
854                    std::printf("%s / down type %d: %s\n", nib::fmt_name(gt), dt, err.c_str());
855                    ++total_s;
856                    continue;
857                }
858                S.tag = "syn";
859                S.layer = 0;
860                S.ne = std::max(16, std::min(syn, NE));
861                S.host.resize((size_t) S.ne * S.f.bytes);
862                for (auto& b : S.host) b = (uint8_t) rng();
863                // block_iq4_nl and block_q2_0 are 18 bytes, the fp16 scale first: an ordinary scale in every block of the down rows
864                for (int e = 0; e < S.ne; ++e)
865                    for (size_t o = S.f.down_off; o + 18 <= S.f.bytes; o += 18) {
866                        const uint16_t sc = (uint16_t) ((9u << 10) | (rng() & 0x3FFu));
867                        std::memcpy(S.host.data() + (size_t) e * S.f.bytes + o, &sc, 2);
868                    }
869                long long sb = synthesize(S, rng);
870                sb += convert(S, ggml_check);
871                sb += grouped_parity(S, rng, plans, dx, scr, dout);
872                total_s += sb;
873                ++done;
874                CK(cudaFree(S.raw));
875                CK(cudaFree(S.slots));
876            }
877        std::printf("\n%s: %d synthetic format pairs, %lld differences\n", total_s == 0 && done == 6 ? "PASS" : "FAIL", done, total_s);
878        return total_s == 0 && done == 6 ? 0 : 1;
879    }
880    long long total = 0;
881    int layers_done = 0;
882    std::vector<int> syn_done;
883    for (size_t si = 0; si < shards.size(); ++si) {
884        std::unique_ptr<strata::GgufModel> model;
885        try {
886            model = std::make_unique<strata::GgufModel>(strata::GgufModel::open(shards[si]));
887        } catch (const std::exception& ex) {
888            std::fprintf(stderr, "iq_nibble_parity: %s\n", ex.what());
889            return 2;
890        }
891        const std::string tag(1, (char) ('A' + si));
892        std::printf("\n#### model %s: %s (%zu shards)\n", tag.c_str(), shards[si].c_str(), model->size());
893        std::vector<int> pick;
894        int count[64] = {};
895        for (int l = 0; l < 256; ++l) {
896            int gt = -1, dt = -1;
897            if (!layer_fmt(*model, l, gt, dt)) break;
898            if (!nib::fmt_built(gt)) continue;
899            const bool want = only.empty() ? count[gt]++ < per_fmt : std::find(only.begin(), only.end(), l) != only.end();
900            if (want) pick.push_back(l);
901        }
902        for (int l : pick) {
903            Layer Y;
904            Y.tag = tag;
905            if (!read_layer(*model, l, NE, Y)) {
906                std::printf("layer %d: cannot read its experts\n", l);
907                ++total;
908                continue;
909            }
910            long long b = convert(Y, ggml_check);
911            if (negative) {   // the control: one code byte changed per slot (item 3 of row 5), which (6) must see
912                for (int e = 0; e < Y.ne; ++e) {
913                    uint8_t* at = Y.slots + (size_t) e * Y.V.slot_bytes + nib::code_off(5, 3);
914                    uint8_t v = 0;
915                    CK(cudaMemcpy(&v, at, 1, cudaMemcpyDeviceToHost));
916                    v ^= 0x11;
917                    CK(cudaMemcpy(at, &v, 1, cudaMemcpyHostToDevice));
918                }
919                std::printf("    NEGATIVE CONTROL: one code byte changed per slot - the rows below must differ\n");
920                std::vector<unsigned long long> hp(Y.ne);
921                for (int e = 0; e < Y.ne; ++e) hp[e] = (unsigned long long) (Y.slots + (size_t) e * Y.V.slot_bytes);
922                unsigned long long* dp = nullptr;
923                CK(cudaMalloc(&dp, (size_t) Y.ne * 8));
924                CK(cudaMemcpy(dp, hp.data(), (size_t) Y.ne * 8, cudaMemcpyHostToDevice));
925                b += gguf_parity(Y, dp, true);
926                CK(cudaFree(dp));
927            }
928            b += grouped_parity(Y, rng, plans, dx, scr, dout);
929            total += b;
930            ++layers_done;
931            // the synthetic experts of this format, once: this layer's blobs with random gate/up blocks
932            if (syn > 0 && std::find(syn_done.begin(), syn_done.end(), Y.f.gu_type) == syn_done.end() && !negative) {
933                syn_done.push_back(Y.f.gu_type);
934                Layer S;
935                S.tag = "syn";
936                S.layer = Y.layer;
937                S.f = Y.f;
938                S.ne = std::min(syn, Y.ne);
939                S.host.assign(Y.host.begin(), Y.host.begin() + (ptrdiff_t) ((size_t) S.ne * Y.f.bytes));
940                long long sb = synthesize(S, rng);
941                sb += convert(S, ggml_check);
942                sb += grouped_parity(S, rng, std::max(1, plans / 2), dx, scr, dout);
943                total += sb;
944                CK(cudaFree(S.raw));
945                CK(cudaFree(S.slots));
946            }
947            CK(cudaFree(Y.raw));
948            CK(cudaFree(Y.slots));
949        }
950    }
951    std::printf("\n%s: %d layers (+ %zu synthetic formats), %lld differences\n", total == 0 ? "PASS" : "FAIL", layers_done,
952                syn_done.size(), total);
953    return total == 0 ? 0 : 1;
954}