okami.mom/strata

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

Niko1221Merge branch 'f-140' into f-140-j2e0f28e7d

main
20.3 KiB366 linesraw
1// tests/core/expert_layout_test.cpp - native_experts.txt (v2/v3/v4) and the expert arena filled from GGUF shards,
2// without a model or a GPU.
3//
4//   1. Copies of the real packs' native_experts.txt (tests/data/native_experts: Q2_0, IQ2_XS, IQ3_XXS, IQ3_S,
5//      Coder IQ1_M, Swift IQ2_XS; v2 and v3 headers) parse to the layout the pre-v4 reader produced: the test
6//      parses each line again with that reader's rules (one shard name for all three roles) and compares every
7//      field, and the totals with the header's.
8//   2. The v4 shard column `gate,up,down` (an empty field = the --native shard); v5, four names, two names and a
9//      trailing column are refused.
10//   3. check_experts_gguf + load_experts_gguf on a synthetic arena at the real dimensions 2560/640 with Unsloth's
11//      format pairs (Q4_K/Q5_1, Q5_K/Q8_0): layer 1's gate/up in another file than its down.  Every byte of the
12//      arena is compared with the source tensors.  Then the refusals: an offset that is not the tensor's, a
13//      truncated file, a role named in the wrong file, a type or a shape the pack does not say, a missing file.
14#include "gguf_fixture.hpp"
15
16#include "strata/core/expert_source.hpp"
17#include "strata/core/pinned.hpp"
18#include "strata/kernels/cpu/expert_layout.hpp"
19#include "strata/kernels/cpu/native_expert.hpp"
20
21#include <algorithm>
22#include <chrono>
23#include <cstring>
24#include <cstdlib>
25#include <cstdio>
26#include <filesystem>
27#include <fstream>
28#include <sstream>
29#include <string>
30#include <vector>
31
32namespace fs = std::filesystem;
33using strata::kernels::cpu::ExpertLayout;
34
35namespace {
36int g_fail = 0;
37void check(bool ok, const std::string& what) {
38    std::printf("  %-84s %s\n", what.c_str(), ok ? "ok" : "FAIL");
39    if (!ok) ++g_fail;
40}
41
42struct TempDir {
43    fs::path path;
44    TempDir() {
45        path = fs::temp_directory_path() /
46               ("strata-expert-layout-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
47        fs::create_directories(path);
48    }
49    ~TempDir() {
50        std::error_code ignored;
51        fs::remove_all(path, ignored);
52    }
53};
54
55void write_text(const fs::path& p, const std::string& s) { std::ofstream(p, std::ios::binary) << s; }
56
57bool load(const fs::path& dir, int64_t n_layers, int64_t n_expert, std::string& err) {
58    err.clear();
59    return strata::kernels::cpu::expert_layout_load(dir.string(), n_layers, n_expert, err);
60}
61
62// ---- 1. the real packs' files
63void real_packs(const fs::path& data) {
64    for (const char* pack : {"q2_0", "iq2_xs", "iq3_xxs", "iq3_s", "coder-iq1_m", "swift-iq2_xs"}) {
65        TempDir d;
66        fs::copy_file(data / (std::string(pack) + ".txt"), d.path / "native_experts.txt");
67        std::string err;
68        const bool ok = load(d.path, 48, 512, err);
69        check(ok, std::string(pack) + ": loads" + (ok ? "" : ": " + err));
70        if (!ok) continue;
71        const ExpertLayout& L = strata::kernels::cpu::expert_layout();
72        // the pre-v4 reader's rules, applied to the same text
73        std::ifstream in(d.path / "native_experts.txt");
74        std::string line;
75        long long hdr_n = -1, hdr_total = -1;
76        bool same = L.native && L.n_layers == 48 && L.gguf_off.size() == 3 * 48;
77        uint64_t max_blob = 0;
78        while (std::getline(in, line)) {
79            if (line.empty()) continue;
80            if (line[0] == '#') {
81                if (line.find("(n_expert ") == std::string::npos) continue;
82                std::istringstream h(line.substr(line.find("(n_expert ") + 10));
83                char comma = 0;
84                std::string word;
85                h >> hdr_n >> comma >> word >> hdr_total;   // "(n_expert N, total T; ..."
86                continue;
87            }
88            std::istringstream ss(line);
89            long long l = 0, gt = 0, dt = 0;
90            unsigned long long off = 0, blob = 0, o[3] = {0, 0, 0};
91            std::string file;
92            ss >> l >> gt >> dt >> off >> blob >> o[0] >> o[1] >> o[2];
93            ss >> file;
94            same = same && L.fmt[(size_t) l].gu_type == gt && L.fmt[(size_t) l].d_type == dt &&
95                   L.offset[(size_t) l] == off && L.bytes[(size_t) l] == blob;
96            for (int r = 0; r < 3; ++r) {
97                same = same && L.gguf_off[(size_t) (3 * l + r)] == o[r];
98                const std::string got = L.gguf_file.empty() ? std::string() : L.gguf_file[(size_t) (3 * l + r)];
99                same = same && got == file;
100            }
101            if (blob > max_blob) max_blob = blob;
102        }
103        same = same && L.n_expert == hdr_n && (long long) L.total == hdr_total && L.max_blob == max_blob;
104        check(same, std::string(pack) + ": every field as the pre-v4 reader, totals as the header (v" +
105                        std::to_string(L.version) + ", n_expert " + std::to_string(L.n_expert) + ")");
106    }
107}
108
109// ---- 2. the v4 column and the refusals
110std::string manifest(int version, const std::string& col1, int64_t blob, int n_expert = 2) {
111    std::string s = "# strata native experts v" + std::to_string(version) +
112                    ": layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard | gate,up,down] "
113                    "(n_expert " + std::to_string(n_expert) + ", total " + std::to_string(2 * blob * n_expert) + ")\n";
114    s += "0 12 7 0 " + std::to_string(blob) + " 100 200 300\n";
115    s += "1 12 7 " + std::to_string(blob * n_expert) + " " + std::to_string(blob) + " 400 500 600" +
116         (col1.empty() ? "" : " " + col1) + "\n";
117    return s;
118}
119
120void columns() {
121    strata::kernels::cpu::NativeFmt f;
122    std::string err;
123    if (!strata::kernels::cpu::native_fmt(12, 7, 2560, 640, f, err)) {
124        check(false, "Q4_K/Q5_1 native format: " + err);
125        return;
126    }
127    const int64_t blob = (int64_t) f.bytes;
128    TempDir d;
129    write_text(d.path / "native_experts.txt", manifest(4, "B.gguf,B.gguf,", blob));
130    bool ok = load(d.path, 2, 512, err);
131    const ExpertLayout& L = strata::kernels::cpu::expert_layout();
132    check(ok && L.version == 4 && L.gguf_file.size() == 6 && L.gguf_file[0].empty() && L.gguf_file[2].empty() &&
133              L.gguf_file[3] == "B.gguf" && L.gguf_file[4] == "B.gguf" && L.gguf_file[5].empty() &&
134              L.gguf_off[5] == 600,
135          "v4: `B.gguf,B.gguf,` = gate and up in B.gguf, down in the --native shard" + (ok ? "" : ": " + err));
136    write_text(d.path / "native_experts.txt", manifest(3, "A.gguf", blob));
137    ok = load(d.path, 2, 512, err);
138    check(ok && L.gguf_file[3] == "A.gguf" && L.gguf_file[4] == "A.gguf" && L.gguf_file[5] == "A.gguf",
139          "v3: one name covers the three roles");
140    write_text(d.path / "native_experts.txt", manifest(5, "", blob));
141    ok = load(d.path, 2, 512, err);
142    check(!ok && err.find("v5") != std::string::npos, "v5 is refused (\"" + err.substr(0, 40) + "...\")");
143    write_text(d.path / "native_experts.txt", manifest(4, "a,b,c,d", blob));
144    check(!load(d.path, 2, 512, err) && err.find("gate,up,down") != std::string::npos, "four names are refused");
145    write_text(d.path / "native_experts.txt", manifest(4, "a,b", blob));
146    check(!load(d.path, 2, 512, err), "two names are refused");
147    write_text(d.path / "native_experts.txt", manifest(4, "a extra", blob));
148    check(!load(d.path, 2, 512, err), "a column after the shard column is refused");
149}
150
151// ---- 3. the arena from synthetic shards
152void arena() {
153    using fixture::Tensor;
154    constexpr int64_t H = 2560, FF = 640, NE = 2;
155    const uint32_t Q4_K = 12, Q5_1 = 7, Q5_K = 13, Q8_0 = 8, Q3_K = 11, IQ3_S = 21;
156    strata::kernels::cpu::NativeFmt f0, f1;
157    std::string err;
158    if (!strata::kernels::cpu::native_fmt(Q4_K, Q5_1, H, FF, f0, err) ||
159        !strata::kernels::cpu::native_fmt(Q5_K, Q8_0, H, FF, f1, err)) {
160        check(false, "Q4_K/Q5_1 and Q5_K/Q8_0 native formats: " + err);
161        return;
162    }
163    TempDir d;
164    const fs::path A = d.path / "M-00002-of-00003.gguf", B = d.path / "M-00003-of-00003.gguf";
165    // A: layer 0 (all roles) and layer 1's down; B: layer 1's gate and up
166    const std::vector<Tensor> ta = {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q4_K, 11},
167                                    {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q4_K, 12},
168                                    {"blk.0.ffn_down_exps.weight", {FF, H, NE}, Q5_1, 13},
169                                    {"blk.1.ffn_down_exps.weight", {FF, H, NE}, Q8_0, 23}};
170    const std::vector<Tensor> tb = {{"blk.1.ffn_gate_exps.weight", {H, FF, NE}, Q5_K, 21},
171                                    {"blk.1.ffn_up_exps.weight", {H, FF, NE}, Q5_K, 22}};
172    const auto wa = fixture::write(A, {}, ta);
173    const auto wb = fixture::write(B, {}, tb);
174    auto at = [](const fixture::Written& w, size_t i) { return std::to_string(w.data_start + w.offsets[i]); };
175    const uint64_t total = (f0.bytes + f1.bytes) * NE;
176    auto text = [&](const std::string& down1, const std::string& col1) {
177        return "# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off "
178               "[shard | gate,up,down] (n_expert 2, total " + std::to_string(total) + ")\n" +
179               "0 12 7 0 " + std::to_string(f0.bytes) + " " + at(wa, 0) + " " + at(wa, 1) + " " + at(wa, 2) + "\n" +
180               "1 13 8 " + std::to_string(f0.bytes * NE) + " " + std::to_string(f1.bytes) + " " + at(wb, 0) + " " +
181               at(wb, 1) + " " + down1 + " " + col1 + "\n";
182    };
183    const fs::path pack = d.path / "pack";
184    fs::create_directories(pack);
185    write_text(pack / "native_experts.txt", text(at(wa, 3), B.filename().string() + "," + B.filename().string() + ","));
186    bool ok = load(pack, 2, 512, err);
187    check(ok, "the v4 manifest of the split layer loads" + (ok ? "" : ": " + err));
188    if (!ok) return;
189    const ExpertLayout& L = strata::kernels::cpu::expert_layout();
190    ok = strata::core::check_experts_gguf(A.string(), L, err);
191    check(ok, "check_experts_gguf: every span is its tensor" + (ok ? "" : ": " + err));
192    std::vector<uint8_t> dst((size_t) L.total, 0xEE);
193    const strata::core::LoadStats st = strata::core::load_experts_gguf(A.string(), dst.data(), L, 3);
194    check(st.ok && st.bytes == L.total && L.total == total, "load_experts_gguf reads the whole arena (" +
195                                                                 std::to_string(L.total) + " B)");
196    // every byte: expert e's slice of role r comes from byte e * per[r] of that role's tensor
197    bool exact = true;
198    for (int64_t l = 0; l < 2 && exact; ++l) {
199        const auto& fm = L.fmt[(size_t) l];
200        const uint64_t per[3] = {fm.up_off, fm.up_off, fm.bytes - fm.down_off};
201        const uint64_t off[3] = {0, fm.up_off, fm.down_off};
202        const uint8_t seed[2][3] = {{11, 12, 13}, {21, 22, 23}};
203        for (int64_t e = 0; e < NE && exact; ++e)
204            for (int r = 0; r < 3 && exact; ++r) {
205                const uint8_t* got = dst.data() + L.blob_offset(l, e) + off[r];
206                for (uint64_t j = 0; j < per[r]; ++j)
207                    if (got[j] != fixture::pattern(seed[l][r], (uint64_t) e * per[r] + j)) { exact = false; break; }
208            }
209    }
210    check(exact, "every blob is [gate | up | down] of its expert, layer 1 from both files");
211
212    {   // CS-T: the same blobs from FileExpertSource reading the shards in place (no experts.bin in the pack)
213        strata::core::FileExpertSource fs;
214        fs.set_gguf(A.string());
215        std::string e1;
216        const bool opened = fs.open(pack.string(), 2, NE, e1);
217        check(opened && fs.gguf_mode(), "FileExpertSource opens the GGUF in place" + (opened ? "" : ": " + e1));
218        if (opened) {
219            bool same = true, copies = true, transient = true;
220            std::vector<uint8_t> buf((size_t) std::max(f0.bytes, f1.bytes));
221            for (int64_t l = 0; l < 2; ++l)
222                for (int64_t e = 0; e < NE; ++e) {
223                    fs.begin_layer(l, nullptr, 0);
224                    const uint8_t* b = fs.blob(l, e);
225                    const size_t n = (size_t) L.blob_bytes(l);
226                    same = same && b != nullptr && std::memcmp(b, dst.data() + L.blob_offset(l, e), n) == 0;
227                    copies = copies && fs.copy_blob(l, e, buf.data()) &&
228                             std::memcmp(buf.data(), dst.data() + L.blob_offset(l, e), n) == 0;
229                    const uint64_t released = fs.release(l, e);
230#if defined(_WIN32)
231                    const char* setting = std::getenv("STRATA_FILE_RELEASE");
232                    const bool enabled = setting != nullptr && std::strcmp(setting, "1") == 0;
233                    check(enabled ? released > 0 : released == 0, "GGUF mapped release honors its opt-in switch");
234#else
235                    check(released == 0, "GGUF mapped release remains unchanged outside Windows");
236#endif
237                    copies = copies && fs.copy_blob(l, e, buf.data()) &&
238                             std::memcmp(buf.data(), dst.data() + L.blob_offset(l, e), n) == 0;
239                    transient = transient && fs.transient(l, e);
240                }
241            check(same && copies && transient, "blob() and copy_blob() equal the loaded arena byte for byte (transient)");
242            // a blob asked again in the same layer is the same buffer; its bytes hold through two more layers
243            fs.begin_layer(0, nullptr, 0);
244            const uint8_t* p = fs.blob(0, 1);
245            const uint8_t* q = fs.blob(0, 1);
246            fs.begin_layer(1, nullptr, 0);
247            (void) fs.blob(1, 0);
248            (void) fs.blob(1, 1);
249            fs.begin_layer(0, nullptr, 0);
250            (void) fs.blob(0, 0);
251            check(p == q && std::memcmp(p, dst.data() + L.blob_offset(0, 1), (size_t) L.blob_bytes(0)) == 0,
252                  "an assembled blob stays put while it is in use");
253            check(fs.file_read_bytes() > 0, "the file tier counts its bytes (" + std::to_string(fs.file_read_bytes()) + ")");
254            // prefetch: a layer's experts fetched together on several threads, then the same bytes from blob()
255            bool pre = true;
256            for (int round = 0; round < 3; ++round)
257                for (int64_t l = 0; l < 2; ++l) {
258                    fs.begin_layer(l, nullptr, 0);
259                    fs.begin_layer(l == 0 ? 1 : 0, nullptr, 0);   // age the buffers so the prefetch refills them
260                    fs.begin_layer(l, nullptr, 0);
261                    const int64_t both[2] = {1, 0};
262                    fs.set_fetch_threads(2);
263                    fs.prefetch(l, both, 2);
264                    for (int64_t e = 0; e < NE; ++e) {
265                        const uint8_t* b = fs.blob(l, e);
266                        pre = pre && b != nullptr &&
267                              std::memcmp(b, dst.data() + L.blob_offset(l, e), (size_t) L.blob_bytes(l)) == 0;
268                    }
269                }
270            check(pre && fs.file_blob_bytes() > 0 && fs.file_ms() >= 0.0,
271                  "prefetch on 2 threads, then blob(): the same bytes");
272        }
273        fs.close();
274        // with experts.bin present, the pack's file is mapped as before, whatever set_gguf says
275        {
276            std::ofstream eb(pack / "experts.bin", std::ios::binary);
277            eb.write((const char*) dst.data(), (std::streamsize) dst.size());
278        }
279        strata::core::FileExpertSource fb;
280        fb.set_gguf(A.string());
281        std::string e2;
282        const bool ob = fb.open(pack.string(), 2, NE, e2);
283        const uint8_t* b11 = ob ? fb.blob(1, 1) : nullptr;
284        check(ob && !fb.gguf_mode() && !fb.transient(1, 1) && b11 != nullptr &&
285                  std::memcmp(b11, dst.data() + L.blob_offset(1, 1), (size_t) L.blob_bytes(1)) == 0,
286              "with experts.bin the mapped file is used (unchanged behaviour)");
287        fb.close();
288        fs::remove(pack / "experts.bin");
289    }
290
291    auto refused = [&](const std::string& what, const std::string& needle) {
292        std::string e2;
293        const bool bad = load(pack, 2, 512, e2) && !strata::core::check_experts_gguf(A.string(),
294                                                                                    strata::kernels::cpu::expert_layout(), e2);
295        check(bad && e2.find(needle) != std::string::npos, what + " (\"..." + needle + "...\")");
296    };
297    const std::string both = B.filename().string() + "," + B.filename().string() + ",";
298    write_text(pack / "native_experts.txt", text(std::to_string(std::stoull(at(wa, 3)) + 32), both));
299    refused("an offset that is not the tensor's is refused", "starts at byte");
300    write_text(pack / "native_experts.txt", text(at(wa, 3), ""));
301    refused("layer 1's gate named in the file that does not hold it is refused", "is not in it");
302    write_text(pack / "native_experts.txt", text(at(wa, 3), both + ",x"));
303    std::string e3;
304    check(!load(pack, 2, 512, e3), "a malformed column is refused at load");
305    write_text(pack / "native_experts.txt", text(at(wa, 3), "missing.gguf,missing.gguf,"));
306    refused("a shard that is not there is refused", "cannot open");
307    fixture::write(B, {}, tb, /*cut=*/100);
308    write_text(pack / "native_experts.txt", text(at(wa, 3), both));
309    refused("a truncated shard is refused before anything is read", "past the end");
310
311    // a type and a shape the pack does not say: Q3_K and IQ3_S are both 110 B per 256, so only the type differs
312    TempDir d2;
313    const fs::path C = d2.path / "C.gguf";
314    const auto wc = fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, IQ3_S, 31},
315                                           {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32},
316                                           {"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}});
317    strata::kernels::cpu::NativeFmt f2;
318    if (!strata::kernels::cpu::native_fmt(Q3_K, Q5_1, H, FF, f2, err)) {
319        check(false, "Q3_K/Q5_1 native format: " + err);
320        return;
321    }
322    fs::create_directories(d2.path / "pack");
323    write_text(d2.path / "pack" / "native_experts.txt",
324               "# strata native experts v3: (n_expert 2, total " + std::to_string(f2.bytes * NE) + ")\n0 11 7 0 " +
325                   std::to_string(f2.bytes) + " " + std::to_string(wc.data_start + wc.offsets[0]) + " " +
326                   std::to_string(wc.data_start + wc.offsets[1]) + " " + std::to_string(wc.data_start + wc.offsets[2]) + "\n");
327    ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(),
328                                                                                  strata::kernels::cpu::expert_layout(), err);
329    check(ok && err.find("is IQ3_S") != std::string::npos, "a gate of another type than the pack's is refused");
330    // the same bytes with the pack's types, but a down tensor of three experts where the pack says two
331    fixture::write(C, {}, {{"blk.0.ffn_gate_exps.weight", {H, FF, NE}, Q3_K, 31},
332                           {"blk.0.ffn_up_exps.weight", {H, FF, NE}, Q3_K, 32},
333                           {"blk.0.ffn_down_exps.weight", {FF, H, NE + 1}, Q5_1, 33}});
334    ok = load(d2.path / "pack", 1, 512, err) && !strata::core::check_experts_gguf(C.string(),
335                                                                                  strata::kernels::cpu::expert_layout(), err);
336    check(ok && err.find("is not [640, 2560, 2]") != std::string::npos, "a down tensor of another shape is refused");
337}
338}  // namespace
339
340int main(int argc, char** argv) {
341    // `expert_layout_test --real PACK_DIR NATIVE_SHARD`: a real pack's native_experts.txt against its model's files
342    // (headers only - check_experts_gguf reads no expert byte)
343    if (argc == 4 && std::string(argv[1]) == "--real") {
344        std::string err;
345        if (!load(argv[2], 48, 512, err)) { std::printf("layout refused: %s\n", err.c_str()); return 1; }
346        const ExpertLayout& L = strata::kernels::cpu::expert_layout();
347        const bool ok = strata::core::check_experts_gguf(argv[3], L, err);
348        size_t split = 0;
349        for (int64_t l = 0; l < L.n_layers && !L.gguf_file.empty(); ++l)
350            split += L.gguf_file[(size_t) (3 * l)] != L.gguf_file[(size_t) (3 * l + 2)];
351        std::printf("%s: v%d, %lld layers x %lld experts, %.2f GiB, %zu layer(s) split per role: %s%s\n", argv[2],
352                    L.version, (long long) L.n_layers, (long long) L.n_expert, (double) L.total / (1u << 30), split,
353                    ok ? "every span is its tensor" : "REFUSED: ", ok ? "" : err.c_str());
354        return ok ? 0 : 1;
355    }
356    std::printf("expert_layout_test\n");
357    if (argc < 2) {
358        std::printf("usage: expert_layout_test <tests/data/native_experts>\n");
359        return 2;
360    }
361    real_packs(argv[1]);
362    columns();
363    arena();
364    std::printf(g_fail ? "expert_layout_test: %d FAILED\n" : "expert_layout_test: all passed\n", g_fail);
365    return g_fail ? 1 : 0;
366}