okami.mom/strata

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

Niko1221Merge f-022-int (68864c564) into f-022-gyrocuda: release notes keep both sides1df3a3108

main
10.2 KiB206 linesraw
1// src/spec/suffix_drafter_test.cpp - plan v0.3 P6: suffix-lookup drafter tests and an offline simulation.
2//
3//   suffix_drafter_test                      unit tests
4//   suffix_drafter_test --simulate [--k K] FILE.ids ...
5//
6// The simulation replays text as if a model had produced it: each step drafts up to K tokens, accepts the
7// prefix that matches the true next tokens, and commits that prefix plus one model token (the verify pass's
8// bonus). tokens/step is the lookup drafter's ceiling speedup on that text when a K+1-token verify costs the same
9// as a 1-token step. Two regimes per file:
10//   continue  history = first half of the prompt; generate its second half (natural continuation)
11//   copy      history = the whole prompt; generate its middle third again (output quoting input: edits)
12// No model runs; this measures the drafter on text, not on the model's own outputs.
13#include "strata/spec/suffix_drafter.hpp"
14
15#include <cstdio>
16#include <cstdlib>
17#include <cstring>
18#include <fstream>
19#include <sstream>
20#include <string>
21#include <vector>
22
23using strata::spec::SuffixDrafter;
24
25namespace {
26int g_fail = 0;
27void check(bool ok, const char* what) {
28    if (!ok) { std::fprintf(stderr, "FAIL: %s\n", what); ++g_fail; }
29}
30
31std::vector<int32_t> read_ids(const char* path) {
32    std::ifstream f(path);
33    std::string text((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
34    for (char& c : text) if (c == ',') c = ' ';
35    std::istringstream in(text);
36    std::vector<int32_t> ids;
37    for (int32_t v; in >> v;) ids.push_back(v);
38    return ids;
39}
40
41struct Sim { long steps = 0, tokens = 0, proposals = 0, accepted = 0; };
42
43Sim simulate(const std::vector<int32_t>& history, const std::vector<int32_t>& target, int K) {
44    SuffixDrafter d(3, 32, history.size() + target.size() + 16);
45    d.append(history.data(), history.size());
46    Sim s;
47    std::vector<int32_t> draft(K);
48    size_t i = 0;
49    while (i < target.size()) {
50        const int n = d.propose(K, draft.data());
51        int a = 0;
52        while (a < n && i + a < target.size() && draft[a] == target[i + a]) ++a;
53        if (n > 0) { ++s.proposals; s.accepted += a; }
54        const size_t commit = std::min(target.size() - i, (size_t) a + 1);
55        d.append(&target[i], commit);
56        i += commit;
57        s.tokens += (long) commit;
58        ++s.steps;
59    }
60    return s;
61}
62
63void unit_tests() {
64    {   // a repeated passage is proposed verbatim
65        SuffixDrafter d;
66        const std::vector<int32_t> doc = {10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
67        d.append(doc.data(), doc.size());
68        const int32_t again[] = {10, 11, 12};
69        d.append(again, 3);
70        int32_t out[8];
71        const int n = d.propose(5, out);
72        check(n == 5 && out[0] == 13 && out[4] == 17, "repeat proposes the continuation");
73        check(d.last_match() == 3, "match length is the shared suffix");
74    }
75    {   // no earlier occurrence: nothing proposed
76        SuffixDrafter d;
77        const std::vector<int32_t> doc = {1, 2, 3, 4, 5, 6, 7};
78        d.append(doc.data(), doc.size());
79        int32_t out[4];
80        check(d.propose(4, out) == 0, "no match proposes nothing");
81    }
82    {   // two occurrences of the trigram: the longer match wins even though it is older
83        SuffixDrafter d;
84        const std::vector<int32_t> doc = {7, 8, 1, 2, 3, 100, 101, 9, 1, 2, 3, 200, 201, 50, 7, 8, 1, 2, 3};
85        d.append(doc.data(), doc.size());
86        int32_t out[2];
87        const int n = d.propose(2, out);
88        check(n == 2 && out[0] == 100 && out[1] == 101, "longest match preferred over most recent");
89        check(d.last_match() == 5, "longest match length 5");
90    }
91    {   // a match shorter than min_match is ignored (only a bigram in common)
92        SuffixDrafter d(4);
93        const std::vector<int32_t> doc = {1, 2, 3, 9, 5, 2, 3};
94        d.append(doc.data(), doc.size());
95        int32_t out[2];
96        check(d.propose(2, out) == 0, "min_match respected");
97    }
98    {   // periodic text: the continuation may run into the current suffix
99        SuffixDrafter d;
100        const std::vector<int32_t> doc = {1, 2, 3, 1, 2, 3, 1, 2, 3};
101        d.append(doc.data(), doc.size());
102        int32_t out[6];
103        const int n = d.propose(6, out);
104        check(n >= 3 && out[0] == 1 && out[1] == 2 && out[2] == 3, "periodic continuation");
105    }
106    {   // bounded memory: appending beyond the nominal capacity does not crash and still works
107        SuffixDrafter d(3, 32, 1024);
108        std::vector<int32_t> doc;
109        for (int i = 0; i < 5000; ++i) doc.push_back(i % 997);
110        d.append(doc.data(), doc.size());
111        int32_t out[4];
112        check(d.propose(4, out) > 0, "propose after overflow of nominal capacity");
113    }
114    {
115        // --lookup-chain: the match continues from the drafts appended to the history, which stays unchanged
116        SuffixDrafter d(3, 32, 256);
117        const int32_t hist[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 50, 51, 52, 1, 2};
118        d.append(hist, sizeof(hist) / sizeof(hist[0]));
119        const int32_t drafts[] = {3, 4};
120        int32_t out[8] = {};
121        const int k = d.propose_after(drafts, 2, 3, out);
122        check(k == 3 && out[0] == 5 && out[1] == 6 && out[2] == 7, "propose_after continues after the drafts");
123        check(d.last_match() >= 4, "propose_after match length counts the drafts");
124        check(d.size() == sizeof(hist) / sizeof(hist[0]), "propose_after leaves the history unchanged");
125        const int32_t miss[] = {99, 98, 97};
126        check(d.propose_after(miss, 3, 3, out) == 0, "propose_after without a match proposes nothing");
127        // the plain proposal is unaffected: the history's own suffix (52, 1, 2) has no earlier occurrence
128        check(d.propose(3, out) == 0, "propose after propose_after");
129        check(d.propose_after(nullptr, 0, 3, out) == d.propose(3, out), "propose_after with no drafts == propose");
130    }
131    {   // randomized soundness (run under ASan/UBSan in CI-like builds): small vocabularies repeat a lot, tiny tables fill up,
132        // propose_after is interleaved; every proposal must be a real earlier continuation of the matched suffix
133        uint64_t rng = 0x243F6A8885A308D3ull;
134        auto next = [&rng] { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; return rng; };
135        long proposals = 0, bad = 0;
136        for (int round = 0; round < 300; ++round) {
137            const int vocab = 2 + (int) (next() % 6), min_m = 3 + (int) (next() % 3);
138            const size_t cap = 8 + (size_t) (next() % 200);   // often far below the history: the table fills
139            SuffixDrafter d(min_m, 4 + (int) (next() % 40), cap);
140            std::vector<int32_t> hist;
141            for (int step = 0; step < 400; ++step) {
142                const int burst = 1 + (int) (next() % 3);
143                for (int b = 0; b < burst; ++b) {
144                    const int32_t t = hist.size() > 8 && (next() % 3) == 0 ? hist[hist.size() - 1 - (size_t) (next() % 8)]
145                                                                           : (int32_t) (next() % (uint64_t) vocab);
146                    hist.push_back(t);
147                    d.append(t);
148                }
149                const int max_k = 1 + (int) (next() % 8);
150                int32_t out[16] = {};
151                int32_t extra[3] = {};
152                const int n_extra = (int) (next() % 4);
153                for (int e = 0; e < n_extra; ++e) extra[e] = (int32_t) (next() % (uint64_t) vocab);
154                const int k = n_extra > 0 && (next() % 2) ? d.propose_after(extra, n_extra, max_k, out) : d.propose(max_k, out);
155                if (k < 0 || k > max_k) { ++bad; continue; }
156                if (d.size() != hist.size()) { ++bad; continue; }
157                if (k == 0) continue;
158                ++proposals;
159                const int m = d.last_match();
160                if (m < min_m) { ++bad; continue; }
161                // the same query through propose() on the history (no extra tokens) must agree with the invariant too
162                bool found = false;
163                for (size_t p = 0; p + 1 < hist.size() + (size_t) n_extra && !found; ++p) {
164                    // candidate continuation hist[p+1 ..] after a suffix of length m that ends at p
165                    bool match = true;
166                    for (int t = 0; t < k && match; ++t) {
167                        const size_t at = p + 1 + (size_t) t;
168                        const int32_t v = at < hist.size() ? hist[at] : (at - hist.size() < (size_t) n_extra ? extra[at - hist.size()] : -1);
169                        match = v == out[t];
170                    }
171                    found = match;
172                }
173                if (!found) ++bad;
174            }
175        }
176        check(bad == 0, "randomized proposals are real continuations within bounds");
177        check(proposals > 1000, "randomized test exercised proposals");
178    }
179    std::printf("suffix_drafter unit tests: %s\n", g_fail ? "FAILED" : "OK");
180}
181}  // namespace
182
183int main(int argc, char** argv) {
184    if (argc > 1 && std::strcmp(argv[1], "--simulate") == 0) {
185        int K = 8, first = 2;
186        if (argc > 3 && std::strcmp(argv[2], "--k") == 0) { K = std::atoi(argv[3]); first = 4; }
187        std::printf("%-28s %8s | %-44s | %-44s\n", "prompt", "tokens", "continue: tok/step  proposals  acc/proposal",
188                    "copy: tok/step  proposals  acc/proposal");
189        for (int f = first; f < argc; ++f) {
190            const std::vector<int32_t> ids = read_ids(argv[f]);
191            if (ids.size() < 64) continue;
192            const size_t half = ids.size() / 2;
193            const Sim c = simulate({ids.begin(), ids.begin() + half}, {ids.begin() + half, ids.end()}, K);
194            const size_t a = ids.size() / 3, b = 2 * ids.size() / 3;
195            const Sim p = simulate(ids, {ids.begin() + a, ids.begin() + b}, K);
196            const char* name = std::strrchr(argv[f], '/') ? std::strrchr(argv[f], '/') + 1 : argv[f];
197            std::printf("%-28s %8zu | %8.2f %10.1f%% %10.2f              | %8.2f %10.1f%% %10.2f\n", name, ids.size(),
198                        (double) c.tokens / c.steps, 100.0 * c.proposals / c.steps,
199                        c.proposals ? (double) c.accepted / c.proposals : 0.0, (double) p.tokens / p.steps,
200                        100.0 * p.proposals / p.steps, p.proposals ? (double) p.accepted / p.proposals : 0.0);
201        }
202        return 0;
203    }
204    unit_tests();
205    return g_fail ? 1 : 0;
206}