okami.mom/strata

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

Niko1221Merge branch 'f-q4-on242' into r131-q44167bd17a

main
10.3 KiB220 linesraw
1// tests/core/gguf_split_test.cpp - a split model's shards (strata::gguf_split_paths) and their joint view
2// (strata::GgufModel), on synthetic GGUFs: no model, no GPU.
3//
4// The layout is Unsloth's UD-Q4_K_XL in miniature: shard 1 holds the metadata and no tensor, shards 2-4 the
5// tensors, and layer 11's down sits in shard 2 while its gate and up are in shard 3.  Then the ways a real
6// download goes wrong: a shard missing, a shard of another model (split keys that disagree), a tensor in two
7// shards, a directory that does not add up to split.tensors.count, a truncated shard, and shard 1 opened alone.
8#include "gguf_fixture.hpp"
9
10#include "strata/artifact/gguf_split.hpp"
11
12#include <chrono>
13#include <cstdio>
14#include <filesystem>
15#include <string>
16#include <vector>
17
18namespace fs = std::filesystem;
19
20namespace {
21int g_fail = 0;
22void check(bool ok, const std::string& what) {
23    std::printf("  %-78s %s\n", what.c_str(), ok ? "ok" : "FAIL");
24    if (!ok) ++g_fail;
25}
26
27struct TempDir {
28    fs::path path;
29    TempDir() {
30        path = fs::temp_directory_path() /
31               ("strata-gguf-split-test-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
32        fs::create_directories(path);
33    }
34    ~TempDir() {
35        std::error_code ignored;
36        fs::remove_all(path, ignored);
37    }
38};
39
40std::string shard_name(int i, int n) {
41    char b[64];
42    std::snprintf(b, sizeof b, "Model-UD-Q4_K_XL-%05d-of-%05d.gguf", i, n);
43    return b;
44}
45
46using fixture::Tensor;
47const uint32_t F32 = 0, Q8_0 = 8;
48
49/// Writes the 4-shard model; `mutate(i, kv, tensors)` may change shard i (0-based) before it is written.
50template <class F> std::vector<std::string> write_model(const fs::path& dir, F mutate, uint64_t total = 7) {
51    std::vector<std::string> paths;
52    for (int i = 0; i < 4; ++i) {
53        std::vector<fixture::Kv> kv;
54        if (i == 0) kv.push_back(fixture::str("general.architecture", "qwen4exp"));
55        for (const auto& k : fixture::split_keys((uint64_t) i, 4, total)) kv.push_back(k);
56        std::vector<Tensor> ts;
57        if (i == 1) ts = {{"output.weight", {64, 4}, Q8_0, 1}, {"token_embd.weight", {64, 4}, Q8_0, 2},
58                          {"blk.11.ffn_down_exps.weight", {32, 32, 2}, F32, 3}};
59        if (i == 2) ts = {{"blk.11.ffn_gate_exps.weight", {32, 32, 2}, F32, 4},
60                          {"blk.11.ffn_up_exps.weight", {32, 32, 2}, F32, 5}, {"blk.12.attn_q.weight", {32, 8}, F32, 6}};
61        if (i == 3) ts = {{"output_norm.weight", {32}, F32, 7}};
62        uint64_t cut = 0;
63        mutate(i, kv, ts, cut);
64        const fs::path p = dir / shard_name(i + 1, 4);
65        fixture::write(p, kv, ts, cut);
66        paths.push_back(p.string());
67    }
68    return paths;
69}
70auto same = [](int, std::vector<fixture::Kv>&, std::vector<Tensor>&, uint64_t&) {};
71
72std::string error_of(const std::vector<std::string>& paths) {
73    try {
74        strata::GgufModel m(paths);
75    } catch (const std::exception& e) {
76        return e.what();
77    }
78    return {};
79}
80}  // namespace
81
82// `gguf_split_test --real SHARD`: the same view of a real model (headers only): its shards, the architecture
83// check on the metadata shard, and where the tensors the engine reads by name live.
84int real_model(const std::string& any) {
85    try {
86        const strata::GgufModel m = strata::GgufModel::open(any);
87        size_t tensors = 0;
88        for (size_t i = 0; i < m.size(); ++i) {
89            std::printf("  shard %zu: %s, %zu tensors, data at %llu\n", i + 1, m.shard(i).path().c_str(),
90                        m.shard(i).tensors().size(), (unsigned long long) m.shard(i).data_start());
91            tensors += m.shard(i).tensors().size();
92        }
93        const std::string arch = strata::check_architecture(m.meta());
94        std::printf("  %zu tensors; architecture check on the metadata shard: %s\n", tensors,
95                    arch.empty() ? "ok" : arch.c_str());
96        int bad = arch.empty() ? 0 : 1;
97        for (const char* name : {"output.weight", "token_embd.weight", "per_layer_token_embd.weight",
98                                 "blk.1.ple_key.weight", "blk.11.ffn_gate_exps.weight", "blk.11.ffn_up_exps.weight",
99                                 "blk.11.ffn_down_exps.weight"}) {
100            size_t s = 0;
101            const strata::TensorInfo* t = m.find(name, &s);
102            if (!t) { std::printf("  %-30s absent\n", name); continue; }
103            const bool ok = m.in_bounds(*t, s);
104            bad += !ok;
105            std::printf("  %-30s shard %zu, %s, %llu B, %s\n", name, s + 1, t->type_name(),
106                        (unsigned long long) strata::tensor_payload_bytes(*t), ok ? "in bounds" : "OUT OF BOUNDS");
107        }
108        return bad ? 1 : 0;
109    } catch (const std::exception& e) {
110        std::printf("  refused: %s\n", e.what());
111        return 1;
112    }
113}
114
115int main(int argc, char** argv) {
116    if (argc == 3 && std::string(argv[1]) == "--real") return real_model(argv[2]);
117    std::printf("gguf_split_test\n");
118    {
119        TempDir d;
120        const auto paths = write_model(d.path, same);
121        // any shard names the family; the list is in split order, metadata shard first
122        std::vector<std::string> got;
123        try { got = strata::gguf_split_paths(paths[2]); } catch (...) {}
124        check(got == paths, "gguf_split_paths from shard 3: the 4 shards in order");
125        try { got = strata::gguf_split_paths(paths[0]); } catch (...) { got.clear(); }
126        check(got == paths, "gguf_split_paths from shard 1: the same 4 shards");
127        check(strata::gguf_split_paths((d.path / "plain.gguf").string()).size() == 1,
128              "a name without -NNNNN-of-MMMMM is a model of one file");
129        std::string err;
130        try {
131            const strata::GgufModel m(paths);
132            size_t s_out = 9, s_gate = 9, s_down = 9, s_up = 9;
133            const strata::TensorInfo* out = m.find("output.weight", &s_out);
134            const strata::TensorInfo* gate = m.find("blk.11.ffn_gate_exps.weight", &s_gate);
135            const strata::TensorInfo* up = m.find("blk.11.ffn_up_exps.weight", &s_up);
136            const strata::TensorInfo* down = m.find("blk.11.ffn_down_exps.weight", &s_down);
137            check(m.size() == 4 && m.meta().get("general.architecture") && m.meta().tensors().empty(),
138                  "shard 1: the metadata, no tensor");
139            check(out && s_out == 1 && m.in_bounds(*out, s_out), "output.weight found in shard 2, in bounds");
140            check(gate && up && down && s_gate == 2 && s_up == 2 && s_down == 1,
141                  "layer 11 per role: gate/up in shard 3, down in shard 2");
142            check(m.find("blk.99.ffn_gate_exps.weight") == nullptr, "an absent tensor is nullptr");
143            check(strata::check_architecture(m.meta()).find("block_count") != std::string::npos,
144                  "the architecture guard reads the metadata shard (and wants its keys)");
145        } catch (const std::exception& e) {
146            err = e.what();
147        }
148        check(err.empty(), "the 4-shard model opens" + (err.empty() ? std::string() : ": " + err));
149    }
150    {
151        TempDir d;
152        const auto paths = write_model(d.path, same);
153        fs::remove(paths[3]);
154        std::string err;
155        try { strata::gguf_split_paths(paths[0]); } catch (const std::exception& e) { err = e.what(); }
156        check(err.find("missing model shard") != std::string::npos && err.find(shard_name(4, 4)) != std::string::npos,
157              "a missing shard is an error that names it");
158    }
159    {
160        TempDir d;
161        const auto paths = write_model(d.path, [](int i, auto&, auto& ts, uint64_t&) {
162            if (i == 3) ts.push_back({"blk.11.ffn_up_exps.weight", {32, 32, 2}, F32, 9});
163        }, 8);
164        const std::string err = error_of(paths);
165        check(err.find("in two shards") != std::string::npos && err.find(shard_name(3, 4)) != std::string::npos &&
166                  err.find(shard_name(4, 4)) != std::string::npos,
167              "a tensor in two shards is refused, naming both");
168    }
169    {
170        TempDir d;
171        const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) {
172            if (i == 2) kv = fixture::split_keys(1, 4, 7);    // says it is shard 2
173        });
174        check(error_of(paths).find("does not declare itself shard 3 of 4") != std::string::npos,
175              "a shard whose split.no disagrees with its place is refused");
176    }
177    {
178        TempDir d;
179        const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) {
180            if (i == 3) kv = fixture::split_keys(3, 4, 9);    // another model's split.tensors.count
181        });
182        check(!error_of(paths).empty(), "a shard of another model (split.tensors.count differs) is refused");
183    }
184    {
185        TempDir d;
186        const auto paths = write_model(d.path, [](int i, auto&, auto& ts, uint64_t&) {
187            if (i == 3) ts.clear();                         // a directory short of split.tensors.count
188        });
189        check(error_of(paths).find("split.tensors.count is 7") != std::string::npos,
190              "shards that do not add up to split.tensors.count are refused");
191    }
192    {
193        TempDir d;
194        const auto paths = write_model(d.path, [](int i, auto& kv, auto&, uint64_t&) {
195            if (i == 0) kv.erase(kv.begin());               // no general.architecture in shard 1
196        });
197        check(error_of(paths).find("general.architecture") != std::string::npos,
198              "a split model whose first shard has no metadata is refused");
199        check(error_of({paths[0]}).find("opened as a whole model") != std::string::npos,
200              "shard 1 of 4 opened as a whole model is refused");
201    }
202    {
203        TempDir d;
204        const auto paths = write_model(d.path, [](int i, auto&, auto&, uint64_t& cut) {
205            if (i == 2) cut = 100;                          // the last tensor of shard 3 is cut short
206        });
207        bool truncated = false, first_ok = false;
208        try {
209            const strata::GgufModel m(paths);
210            size_t s = 0;
211            const strata::TensorInfo* q = m.find("blk.12.attn_q.weight", &s);
212            const strata::TensorInfo* g = m.find("blk.11.ffn_gate_exps.weight");
213            truncated = q && !m.in_bounds(*q, s);
214            first_ok = g && m.in_bounds(*g, 2);
215        } catch (...) {}
216        check(truncated && first_ok, "a truncated shard: its last tensor is out of bounds, the others are not");
217    }
218    std::printf(g_fail ? "gguf_split_test: %d FAILED\n" : "gguf_split_test: all passed\n", g_fail);
219    return g_fail ? 1 : 0;
220}