okami.mom/strata

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

Niko1221rc1 merge split (1ba231217)fe57a0cb5

main
10.1 KiB201 linesraw
1// Host-only test of the GGUF reader's header checks: writes tiny GGUF files, one valid and several malformed, and
2// expects the valid one to load and each malformed one to be refused with a message naming the tensor; and the rotary
3// scaling a model's keys come to (model_rope), each llama.cpp reading of them followed or refused.
4// make bin/gguf_test && bin/gguf_test [DIR [MODEL.gguf ...]]   (DIR for the files, default /tmp; each MODEL, a real
5// model's first shard, must load too, with a rotary sFNX follows: only its headers are read)
6#include "../src/gguf.hpp"
7#include "../src/rope_gguf.hpp"
8
9#include <cstdio>
10#include <cstring>
11#include <stdexcept>
12#include <string>
13#include <vector>
14
15namespace {
16
17// metadata entries as GGUF lays them out: a string, a uint32 and a float32 key (types 8, 4 and 6)
18struct Kv {
19    std::vector<uint8_t> b;
20    uint64_t n = 0;
21    void put(const void* p, size_t len) { b.insert(b.end(), (const uint8_t*) p, (const uint8_t*) p + len); }
22    void key(const std::string& k, uint32_t type) {
23        const uint64_t len = k.size();
24        put(&len, 8);
25        put(k.data(), k.size());
26        put(&type, 4);
27        ++n;
28    }
29    void str(const std::string& k, const std::string& v) {
30        key(k, 8);
31        const uint64_t len = v.size();
32        put(&len, 8);
33        put(v.data(), v.size());
34    }
35    void u32(const std::string& k, uint32_t v) { key(k, 4); put(&v, 4); }
36    void f32(const std::string& k, float v) { key(k, 6); put(&v, 4); }
37};
38
39// one F32 tensor "w" with the given n_dims and sizes, its data at offset 0 of the data section, data_bytes of data
40std::vector<uint8_t> make(uint32_t n_dims, const std::vector<uint64_t>& ne, uint64_t data_bytes, uint64_t offset = 0, const Kv& kv = {}) {
41    std::vector<uint8_t> b;
42    auto put = [&](const void* p, size_t n) { b.insert(b.end(), (const uint8_t*) p, (const uint8_t*) p + n); };
43    auto u32 = [&](uint32_t v) { put(&v, 4); };
44    auto u64 = [&](uint64_t v) { put(&v, 8); };
45    u32(0x46554747u);   // "GGUF"
46    u32(3);             // version
47    u64(1);             // tensors
48    u64(kv.n);          // metadata keys
49    put(kv.b.data(), kv.b.size());
50    const std::string name = "w";
51    u64(name.size());
52    put(name.data(), name.size());
53    u32(n_dims);
54    for (uint64_t v : ne) u64(v);
55    u32(0);             // F32
56    u64(offset);
57    while (b.size() % 32) b.push_back(0);
58    b.resize(b.size() + data_bytes, 0);
59    return b;
60}
61
62std::string write(const std::string& dir, const std::string& tag, const std::vector<uint8_t>& b) {
63    const std::string path = dir + "/fnx_gguf_test_" + tag + ".gguf";
64    FILE* f = std::fopen(path.c_str(), "wb");
65    if (!f || std::fwrite(b.data(), 1, b.size(), f) != b.size() || std::fclose(f) != 0)
66        throw std::runtime_error("cannot write " + path);
67    return path;
68}
69
70int failures = 0;
71
72void expect_refused(const std::string& dir, const std::string& tag, const std::vector<uint8_t>& b, const char* want) {
73    const std::string path = write(dir, tag, b);
74    try {
75        fnx::Gguf g(path);
76        std::printf("FAIL %s: loaded\n", tag.c_str());
77        ++failures;
78    } catch (const std::runtime_error& e) {
79        const bool ok = std::strstr(e.what(), "tensor w") && std::strstr(e.what(), want);
80        std::printf("%s %s: %s\n", ok ? "ok  " : "FAIL", tag.c_str(), e.what());
81        failures += !ok;
82    }
83    std::remove(path.c_str());
84}
85
86}  // namespace
87
88int main(int argc, char** argv) {
89    const std::string dir = argc > 1 ? argv[1] : "/tmp";
90
91    {
92        const std::string path = write(dir, "valid", make(2, {8, 3}, 8 * 3 * 4));
93        try {
94            fnx::Gguf g(path);
95            const fnx::Tensor& t = g.t("w");
96            const bool ok = t.n_dims == 2 && t.ne[0] == 8 && t.ne[1] == 3 && t.ne[2] == 1 && t.ne[3] == 1 &&
97                            t.nbytes == 96 && t.row_bytes() == 32;
98            std::printf("%s valid: n_dims %d, ne %lld x %lld, %zu bytes\n", ok ? "ok  " : "FAIL", t.n_dims,
99                        (long long) t.ne[0], (long long) t.ne[1], t.nbytes);
100            failures += !ok;
101        } catch (const std::runtime_error& e) {
102            std::printf("FAIL valid: %s\n", e.what());
103            ++failures;
104        }
105        std::remove(path.c_str());
106    }
107
108    {   // a model's YaRN keys as the loader reads them (Model, choose_rope): a string type, numbers in either width
109        Kv kv;
110        kv.str("a.rope.scaling.type", "yarn");
111        kv.f32("a.rope.scaling.factor", 4.0f);
112        kv.u32("a.rope.scaling.original_context_length", 32768);
113        const std::string path = write(dir, "keys", make(2, {8, 3}, 8 * 3 * 4, 0, kv));
114        try {
115            fnx::Gguf g(path);
116            const bool ok = g.has_key("a.rope.scaling.type") && g.s("a.rope.scaling.type") == "yarn" && g.num("a.rope.scaling.factor") == 4.0 &&
117                            g.num("a.rope.scaling.original_context_length") == 32768.0 && g.i("a.rope.scaling.original_context_length") == 32768 &&
118                            !g.has_key("a.rope.scaling.alpha");
119            std::printf("%s keys: string, float and integer metadata read back\n", ok ? "ok  " : "FAIL");
120            failures += !ok;
121        } catch (const std::runtime_error& e) {
122            std::printf("FAIL keys: %s\n", e.what());
123            ++failures;
124        }
125        std::remove(path.c_str());
126    }
127
128    {   // model_rope: what llama.cpp makes of the keys, followed (factor, orig) or refused (the message holds `refused`)
129        struct Case {
130            const char* tag;
131            void (*keys)(Kv&);
132            double factor;
133            int orig;
134            const char* refused;
135        };
136        const Case cases[] = {
137            {"rope_none_at_all", [](Kv&) {}, 0, 0, nullptr},
138            {"rope_yarn", [](Kv& k) { k.str("a.rope.scaling.type", "yarn"); k.f32("a.rope.scaling.factor", 4); k.u32("a.rope.scaling.original_context_length", 32768); }, 4, 32768, nullptr},
139            {"rope_yarn_no_orig", [](Kv& k) { k.str("a.rope.scaling.type", "yarn"); k.f32("a.rope.scaling.factor", 2); }, 2, 0, nullptr},
140            {"rope_yarn_factor_1", [](Kv& k) { k.str("a.rope.scaling.type", "yarn"); k.f32("a.rope.scaling.factor", 1); }, 0, 0, nullptr},
141            {"rope_none_with_factor", [](Kv& k) { k.str("a.rope.scaling.type", "none"); k.f32("a.rope.scaling.factor", 4); }, 0, 0, nullptr},
142            {"rope_linear_factor_1", [](Kv& k) { k.str("a.rope.scaling.type", "linear"); k.f32("a.rope.scaling.factor", 1); }, 0, 0, nullptr},
143            {"rope_yarn_default_betas", [](Kv& k) { k.str("a.rope.scaling.type", "yarn"); k.f32("a.rope.scaling.factor", 2); k.f32("a.rope.scaling.yarn_beta_fast", 32); }, 2, 0, nullptr},
144            // no type is linear to llama.cpp, so a bare factor scales linearly there
145            {"rope_bare_factor", [](Kv& k) { k.f32("a.rope.scaling.factor", 4); }, 0, 0, "llama.cpp takes that as linear"},
146            {"rope_bare_scale_linear", [](Kv& k) { k.f32("a.rope.scale_linear", 2); }, 0, 0, "llama.cpp takes that as linear"},
147            {"rope_linear_4", [](Kv& k) { k.str("a.rope.scaling.type", "linear"); k.f32("a.rope.scaling.factor", 4); }, 0, 0, "follows yarn only"},
148            {"rope_longrope", [](Kv& k) { k.str("a.rope.scaling.type", "longrope"); }, 0, 0, "rope scaling is longrope"},
149            {"rope_compress", [](Kv& k) { k.str("a.rope.scaling.type", "yarn"); k.f32("a.rope.scaling.factor", 0.5f); }, 0, 0, "compress"},
150            {"rope_beta_fast_16", [](Kv& k) { k.str("a.rope.scaling.type", "yarn"); k.f32("a.rope.scaling.factor", 2); k.f32("a.rope.scaling.yarn_beta_fast", 16); }, 0, 0, "yarn_beta_fast"},
151            {"rope_log_mul", [](Kv& k) { k.f32("a.rope.scaling.yarn_log_multiplier", 0.1f); }, 0, 0, "yarn_log_multiplier"},
152            {"rope_attn_factor", [](Kv& k) { k.f32("a.rope.scaling.attn_factor", 0.5f); }, 0, 0, "attn_factor"},
153            {"rope_section_order", [](Kv& k) { k.str("a.rope.section_order", "tzyx"); }, 0, 0, "section_order"},
154        };
155        for (const Case& c : cases) {
156            Kv kv;
157            c.keys(kv);
158            const std::string path = write(dir, c.tag, make(2, {8, 3}, 8 * 3 * 4, 0, kv));
159            std::string got;
160            bool ok;
161            try {
162                fnx::Gguf g(path);
163                const fnx::ModelRope r = fnx::model_rope(g, "a.");
164                got = "x" + std::to_string(r.yarn_factor) + " from " + std::to_string(r.yarn_orig);
165                ok = !c.refused && r.yarn_factor == c.factor && r.yarn_orig == c.orig;
166            } catch (const std::runtime_error& e) {
167                got = e.what();
168                ok = c.refused && std::strstr(e.what(), c.refused);
169            }
170            std::printf("%s %s: %s\n", ok ? "ok  " : "FAIL", c.tag, got.c_str());
171            failures += !ok;
172            std::remove(path.c_str());
173        }
174    }
175
176    expect_refused(dir, "dims0", make(0, {}, 64), "0 dimensions");
177    expect_refused(dir, "dims5", make(5, {1, 1, 1, 1, 1}, 64), "5 dimensions");
178    expect_refused(dir, "dims_huge", make(0xffffffffu, {1}, 64), "4294967295 dimensions");
179    expect_refused(dir, "ne_zero", make(2, {8, 0}, 64), "size 0 in dimension 1");
180    expect_refused(dir, "ne_negative", make(1, {~0ull}, 64), "in dimension 0");
181    // 2^32 x 2^32 elements: 2^64 wraps to 0, which would pass the end check without the overflow test
182    expect_refused(dir, "count_overflow", make(2, {1ull << 32, 1ull << 32}, 64), "element count overflows");
183    // 2^62 elements of 4 bytes: the count fits, the byte count does not
184    expect_refused(dir, "bytes_overflow", make(1, {1ull << 62}, 64), "runs past the end");
185    expect_refused(dir, "past_end", make(2, {8, 3}, 95), "runs past the end");
186    expect_refused(dir, "offset_wraps", make(1, {8}, 64, ~0ull - 8), "runs past the end");
187
188    for (int a = 2; a < argc; ++a) {
189        try {
190            fnx::Gguf g(argv[a]);
191            const fnx::ModelRope r = fnx::model_rope(g, g.s("general.architecture") + ".");
192            std::printf("ok   %s: loads, rotary %s\n", argv[a], r.yarn_factor ? ("its own YaRN x" + std::to_string(r.yarn_factor)).c_str() : "unscaled");
193        } catch (const std::runtime_error& e) {
194            std::printf("FAIL %s: %s\n", argv[a], e.what());
195            ++failures;
196        }
197    }
198
199    std::printf(failures ? "%d FAILED\n" : "all passed\n", failures);
200    return failures ? 1 : 0;
201}