okami.mom/strata

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

Niko1221rc1 merge split (1ba231217)fe57a0cb5

main
75.9 KiB1375 linesraw
1// fnx_run MODEL.gguf check REF.bin OUT.bin [W]   the reference prompt in windows of W rows, per-layer dumps to OUT.bin
2// fnx_run MODEL.gguf gen REF.bin N            greedy: the reference prompt, then N tokens one row per window
3// fnx_run MODEL.gguf rows REF.bin T N         N windows of T rows (the reference tokens, cycled): time per window
4// fnx_run MODEL.gguf bench REF.bin T N        N verify windows of T rows, each committing one: wall and GPU time
5// fnx_run MODEL.gguf bench_step REF.bin L N C [step]  verify windows of 1..MAXT rows, then batched windows of 1..L lanes,
6//                                             at a context of C tokens: medians of N windows each
7// fnx_run MODEL.gguf mtp RT_DIR REF.bin N K [VOCAB [LK]]  greedy decoding with the draft layer (data/mtp-rt), K drafts
8//                                             per round (VOCAB: the draft vocabulary, default RT_DIR's; LK lookup drafts)
9// fnx_run MODEL.gguf spec REF.bin GEN.txt K [BAD%]  speculative windows of K perfect drafts from gen's output, BAD% of
10//                                             windows with one draft corrupted: the output must be gen's
11// fnx_run MODEL.gguf logits PROMPT.bin CONT.lgr T OUT.lgr  the prompt, then CONT.lgr's steps in windows of T: top-64s
12// fnx_run MODEL.gguf exact|read|decode|batch|compare ...   the lab's standard checks (lab_check below)
13#include <cmath>
14#include <numeric>
15#include <optional>
16#include <algorithm>
17#include <array>
18#include <chrono>
19#include <fstream>
20#include <random>
21#include <sstream>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25#include <string>
26#include <vector>
27
28#include <cerrno>
29#include <cinttypes>
30#include <climits>
31#include <cuda_runtime.h>
32#include <dlfcn.h>
33#include <sys/stat.h>
34#include <unistd.h>
35#include <iterator>
36#include <stdexcept>
37
38#include "../src/engine.hpp"
39#include "batch_check.hpp"
40#include "ref_tokens.hpp"
41#include "../src/env.hpp"
42
43// the draft layer's runtime: Flash-Next's files, or the 27B's own layer in its GGUF (Mtp's "nextn")
44#if FNX_27B
45#define MTP_RT "nextn"
46#else
47#define MTP_RT FNX_DIR "/data/mtp-rt"
48#endif
49
50// timings: the middle value, and the p-quantile at index p * (n - 1)
51static double pct(std::vector<double> v, double p) {
52    if (v.empty()) throw std::runtime_error("pct: no values");
53    std::sort(v.begin(), v.end());
54    return v[(size_t) (p * (v.size() - 1))];
55}
56static double median(std::vector<double> v) {
57    if (v.empty()) throw std::runtime_error("median: no values");
58    std::sort(v.begin(), v.end());
59    return v[v.size() / 2];
60}
61
62// the reference prompt (through the prompt path when prefill, else in windows of MAXT), then the continuation of
63// REF.lgr in windows of T: the top 64 logits of each step to OUT.lgr (fnx_logref's format)
64static int run_logits(fnx::Model& m, fnx::Engine& e, const char* prompt_path, const char* ref_path, int T, const char* out_path,
65                      bool prefill) {
66    const std::vector<int> prompt = ref_tokens(prompt_path);
67    if (T < 1 || T > fnx::MAXT) { std::fprintf(stderr, "T: 1..%d\n", fnx::MAXT); return 2; }
68    // the continuation's tokens (fnx_logref's records)
69    std::vector<int> cont;
70    {
71        std::FILE* f = std::fopen(ref_path, "rb");
72        char magic[4];
73        uint32_t k = 0;
74        int32_t np = 0, ns = 0;
75        if (!f || std::fread(magic, 1, 4, f) != 4 || std::memcmp(magic, "LGR1", 4) || std::fread(&k, 4, 1, f) != 1 ||
76            std::fread(&np, 4, 1, f) != 1) { std::fprintf(stderr, "%s: not an .lgr file\n", ref_path); return 1; }
77        std::vector<int32_t> pr((size_t) np);
78        if (std::fread(pr.data(), 4, pr.size(), f) != pr.size() || std::fread(&ns, 4, 1, f) != 1) return 1;
79        if (std::vector<int>(pr.begin(), pr.end()) != prompt) { std::fprintf(stderr, "the .lgr file has another prompt\n"); return 1; }
80        for (int i = 0; i < ns; ++i) {
81            int32_t tok;
82            if (std::fread(&tok, 4, 1, f) != 1) return 1;
83            cont.push_back(tok);
84            std::fseek(f, 4 + (long) k * 8, SEEK_CUR);
85        }
86        std::fclose(f);
87    }
88    constexpr uint32_t K = 64;
89    std::FILE* out = std::fopen(out_path, "wb");
90    if (!out) { std::perror(out_path); return 1; }
91    const int32_t np = (int32_t) prompt.size(), ns = (int32_t) cont.size();
92    std::fwrite("LGR1", 1, 4, out);
93    std::fwrite(&K, 4, 1, out);
94    std::fwrite(&np, 4, 1, out);
95    for (int t : prompt) {
96        const int32_t v = t;
97        std::fwrite(&v, 4, 1, out);
98    }
99    std::fwrite(&ns, 4, 1, out);
100    int written = 0;
101    auto put_rows = [&](const std::vector<float>& lg, int vocab, int r0, int r1) {
102        for (int r = r0; r < r1 && written < ns; ++r, ++written) {
103            const float* row = lg.data() + (size_t) r * vocab;
104            float mx = -INFINITY;
105            for (int i = 0; i < vocab; ++i) mx = std::max(mx, row[i]);
106            double s = 0;
107            for (int i = 0; i < vocab; ++i) s += std::exp((double) row[i] - mx);
108            const float lse = (float) (mx + std::log(s));
109            std::vector<int> idx((size_t) vocab);
110            std::iota(idx.begin(), idx.end(), 0);
111            std::partial_sort(idx.begin(), idx.begin() + K, idx.end(),
112                              [&](int a, int b) { return row[a] > row[b] || (row[a] == row[b] && a < b); });
113            const int32_t taken = cont[(size_t) written];
114            std::fwrite(&taken, 4, 1, out);
115            std::fwrite(&lse, 4, 1, out);
116            for (uint32_t k = 0; k < K; ++k) {
117                const int32_t id = idx[k];
118                std::fwrite(&id, 4, 1, out);
119                std::fwrite(&row[id], 4, 1, out);
120            }
121        }
122    };
123    const int vocab = m.cards[fnx::NCARD - 1].v1;
124    // FNX_IMAGES=FILE.sve (img_logref's): each run of image-pad tokens takes the file's next picture (its cells get
125    // ids of their own, its rows and grid go to set_images)
126    std::vector<int> feed = prompt;
127    std::vector<float> img_rows;
128    std::vector<fnx::Engine::Image> imgs;
129    if (const char* sv = std::getenv("FNX_IMAGES")) {
130        std::FILE* f = std::fopen(sv, "rb");
131        if (!f) { std::perror(sv); return 1; }
132        std::vector<std::array<int, 4>> recs;   // n, nx, ny, first row
133        int32_t h[5];
134        while (std::fread(h, 4, 5, f) == 5) {
135            if (h[0] != 0x31455653 || h[4] != fnx::N) { std::fprintf(stderr, "%s: not strata-vision records of width %d\n", sv, fnx::N); return 1; }
136            const size_t off = img_rows.size();
137            img_rows.resize(off + (size_t) h[1] * fnx::N);
138            if (std::fread(img_rows.data() + off, 4, (size_t) h[1] * fnx::N, f) != (size_t) h[1] * fnx::N) return 1;
139            recs.push_back({h[1], h[2], h[3], (int) (off / fnx::N)});
140        }
141        std::fclose(f);
142        size_t k = 0;
143        for (size_t i = 0; i < feed.size();) {
144            if (feed[i] != (int) m.ple_image) { ++i; continue; }
145            if (k >= recs.size()) { std::fprintf(stderr, "more images in the prompt than in %s\n", sv); return 1; }
146            const auto& r = recs[k];
147            for (int j = 0; j < r[0]; ++j) feed[i + j] = fnx::Engine::IMAGE_TOK + (int) k * 65536 + j;
148            imgs.push_back(fnx::Engine::Image{(int) i, r[0], r[1], r[2], img_rows.data() + (size_t) r[3] * fnx::N});
149            i += r[0];
150            ++k;
151        }
152        e.set_images(imgs);
153        std::fprintf(stderr, "logits: %zu image(s)\n", imgs.size());
154    }
155    // the prompt: its last window's last row is step 0. FNX_PREFILL=1: all but its last token through the batched path
156    if (prefill) {
157        const auto t0 = std::chrono::steady_clock::now();
158        e.prefill(std::vector<int>(feed.begin(), feed.end() - 1));
159        const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
160        std::fprintf(stderr, "prefill: %zu tokens in %.2f s (%.0f tok/s)\n", feed.size() - 1, s, (feed.size() - 1) / s);
161        e.window({feed.back()});
162        put_rows(e.last_logits(1), vocab, 0, 1);
163    } else
164        for (size_t i = 0; i < feed.size(); i += fnx::MAXT) {
165            std::vector<int> w(feed.begin() + i, feed.begin() + std::min(feed.size(), i + fnx::MAXT));
166            e.window(w);
167            if (i + w.size() == feed.size()) put_rows(e.last_logits((int) w.size()), vocab, (int) w.size() - 1, (int) w.size());
168        }
169    // the continuation in windows of T: row r of a window starting at step j gives step j + r + 1
170    for (int j = 0; j + 1 < ns; j += T) {
171        std::vector<int> w(cont.begin() + j, cont.begin() + std::min(ns - 1, j + T));
172        e.window(w);
173        put_rows(e.last_logits((int) w.size()), vocab, 0, (int) w.size());
174    }
175    if (std::ferror(out)) {
176        std::fclose(out);
177        std::fprintf(stderr, "logits: %s: a write failed\n", out_path);
178        return 1;
179    }
180    if (std::fclose(out) != 0) {
181        std::fprintf(stderr, "logits: %s: close failed (a buffered write did not reach the disk)\n", out_path);
182        return 1;
183    }
184    std::fprintf(stderr, "logits: %d prompt tokens, %d steps in windows of %d\n", np, written, T);
185    return 0;
186}
187
188// ---------------------------------------------------------------- the lab's standard checks (fixed inputs, run from fnx/)
189// exact [NAME]   ref/long64.bin (62,794 tokens), code1 and edit1 each through the prompt path, then their llama.cpp
190//                continuation steps in windows of 5: the logits to LAB/MODEL-NAME[-PROMPT].lgr (default "try"),
191//                compared with llama.cpp CUDA's on that model (see below) and, byte for byte and by KL, with
192//                LAB/MODEL-base[-PROMPT].lgr; "exact base" writes the baselines themselves
193// read N [N...]  the first N tokens of ref/long64.bin through the prompt path on a fresh engine (after warm_graphs, as
194//                sfnx starts): the read's time and tok/s
195// LAB is FNX_LAB_DIR or /tmp/fnx-lab-UID (tools/lab.sh's directory).
196struct Lgr {
197    uint32_t k = 0;
198    std::vector<int32_t> prompt;
199    struct Step {
200        int32_t tok;
201        float lse;
202        std::vector<int32_t> id;
203        std::vector<float> v;
204    };
205    std::vector<Step> steps;
206};
207static bool load_lgr(const std::string& path, Lgr& g) {
208    std::FILE* f = std::fopen(path.c_str(), "rb");
209    if (!f) return false;
210    char magic[4];
211    int32_t np = 0, ns = 0;
212    bool ok = std::fread(magic, 1, 4, f) == 4 && !std::memcmp(magic, "LGR1", 4) && std::fread(&g.k, 4, 1, f) == 1 &&
213              std::fread(&np, 4, 1, f) == 1;
214    if (ok) {
215        g.prompt.resize((size_t) np);
216        ok = std::fread(g.prompt.data(), 4, g.prompt.size(), f) == g.prompt.size() && std::fread(&ns, 4, 1, f) == 1;
217    }
218    for (int i = 0; ok && i < ns; ++i) {
219        Lgr::Step s;
220        s.id.resize(g.k);
221        s.v.resize(g.k);
222        ok = std::fread(&s.tok, 4, 1, f) == 1 && std::fread(&s.lse, 4, 1, f) == 1;
223        for (uint32_t j = 0; ok && j < g.k; ++j) ok = std::fread(&s.id[j], 4, 1, f) == 1 && std::fread(&s.v[j], 4, 1, f) == 1;
224        g.steps.push_back(std::move(s));
225    }
226    std::fclose(f);
227    if (!ok) throw std::runtime_error(path + ": a short or malformed .lgr file");
228    return true;
229}
230// ref/lgrcmp.py's measures: top-1 agreement, the agreeing run from the start, KL(ref || other) over the union of both
231// top-Ks (a token outside a side's top-K gets its K-th logit), the top-10 overlap
232struct LgrCmp {
233    int agree = 0, run = 0;
234    size_t n = 0;
235    double kl_mean = 0, kl_median = 0, kl_p99 = 0, kl_max = 0, top10 = 0;
236    double top1_pct() const { return 100.0 * agree / (double) n; }
237    std::string str() const {
238        char buf[256];
239        std::snprintf(buf, sizeof buf, "top-1 %d/%zu (first %d in a row), KL mean %.2e median %.2e p99 %.2e max %.2e, top-10 overlap %.2f",
240                      agree, n, run, kl_mean, kl_median, kl_p99, kl_max, top10);
241        return buf;
242    }
243};
244static LgrCmp lgr_compare(const Lgr& r, const Lgr& o) {
245    if (r.prompt != o.prompt) throw std::runtime_error("lgr_compare: different prompts");
246    const size_t n = std::min(r.steps.size(), o.steps.size());
247    if (n == 0) throw std::runtime_error("lgr_compare: no steps");
248    int agree = 0, run = 0;
249    bool open = true;
250    double ov = 0;
251    std::vector<double> kls;
252    for (size_t i = 0; i < n; ++i) {
253        const Lgr::Step &a = r.steps[i], &b = o.steps[i];
254        if (a.tok != b.tok) throw std::runtime_error("lgr_compare: step " + std::to_string(i) + " took different tokens");
255        if (a.id[0] == b.id[0]) {
256            ++agree;
257            run += open;
258        } else {
259            open = false;
260        }
261        auto logit = [](const Lgr::Step& s, int t) {
262            for (size_t j = 0; j < s.id.size(); ++j)
263                if (s.id[j] == t) return s.v[j];
264            return s.v.back();
265        };
266        std::vector<int32_t> u(a.id);
267        u.insert(u.end(), b.id.begin(), b.id.end());
268        std::sort(u.begin(), u.end());
269        u.erase(std::unique(u.begin(), u.end()), u.end());
270        double kl = 0;
271        for (int t : u) {
272            const double p = std::exp((double) logit(a, t) - a.lse), q = std::exp((double) logit(b, t) - b.lse);
273            if (p > 0 && q > 0) kl += p * std::log(p / q);
274        }
275        kls.push_back(std::max(kl, 0.0));
276        int o10 = 0;
277        for (int x = 0; x < 10; ++x)
278            for (int y = 0; y < 10; ++y) o10 += a.id[x] == b.id[y];
279        ov += o10;
280    }
281    std::vector<double> sk(kls);
282    std::sort(sk.begin(), sk.end());
283    LgrCmp c;
284    c.agree = agree, c.run = run, c.n = n;
285    c.kl_mean = std::accumulate(kls.begin(), kls.end(), 0.0) / n, c.kl_median = sk[n / 2];
286    c.kl_p99 = sk[std::min(n - 1, (size_t) (0.99 * n))], c.kl_max = sk.back(), c.top10 = ov / n;
287    return c;
288}
289static bool same_bytes(const std::string& a, const std::string& b) {
290    std::ifstream fa(a, std::ios::binary), fb(b, std::ios::binary);
291    if (!fa || !fb) return false;
292    const std::string sa(std::istreambuf_iterator<char>(fa), {}), sb(std::istreambuf_iterator<char>(fb), {});
293    return !sa.empty() && sa == sb;
294}
295static std::string lab_dir() {
296    if (const char* d = std::getenv("FNX_LAB_DIR")) return d;
297    return "/tmp/fnx-lab-" + std::to_string(getuid());
298}
299
300// The exactness bar (README, "Exactness"): llama.cpp's CPU backend against its CUDA one, teacher-forced on the same
301// tokens, for code1, edit1 and the picture; for long64, llama.cpp's own q8_0 K/V cache against its f16 one, since
302// summation order alone moves long64's KL between 1.8e-3 and 4.3e-3. The Q8_0 model is held to the same bar (its
303// references are llama.cpp's CPU backend on Q8_0). A run passes with KL mean <= KL_SLACK x the bar's and top-1 at most
304// TOP1_SLACK points under the bar's: sFNX's fp16 ring sums put Q8_0's code1 at 1.10x, while the one precision loss
305// caught so far (fast-math decays in the recurrent core) put code1 at 1.44x. The picture (ref/img/sphinx, 200 steps):
306// llama.cpp's CPU backend 98.50% / 6.38e-3; sFNX 99.00% / 5.96e-3.
307struct Bar {
308    const char* prompt;
309    double top1_pct, kl_mean, kl_slack;
310};
311constexpr double TOP1_SLACK = 1.5;
312#if FNX_27B
313// the 27B's (make FNX_MODEL=27b), on Qwen3.8-27B Q8_0 (docs/verification.md, "The 27B"): the widest of llama.cpp's own
314// spreads, each teacher-forced on its CUDA run's tokens (the file the check compares against,
315// ref/lgr/llama_cuda_<model>_<prompt>.lgr). Its CPU backend against CUDA (llama_cpu_*: code1 8.95e-5, edit1 1.48e-7,
316// the picture 99.50% / 4.69e-4), and its CUDA with the int8 products of quantized activations off, cuBLAS for every
317// product (ref/llama_cublas_only.patch, llama_cublas_*: code1 1.25e-4, edit1 1.23e-7, the picture 99.00% / 8.91e-4,
318// long64 1.04e-4); long64 its q8_0 K/V against its f16 K/V (2.08e-4), as Flash-Next's. Top-1 the CPU backend's (the
319// highest), KL the widest; the slack on top is Flash-Next's, for sFNX's own summation orders
320constexpr Bar BARS[] = {
321    {"code1", 100.00, 1.25e-4, 1.25},
322    {"edit1", 100.00, 1.48e-7, 1.25},
323    {"picture", 99.50, 8.91e-4, 1.25},
324    {"long64", 99.50, 2.08e-4, 1.0},
325};
326#else
327constexpr Bar BARS[] = {
328    {"code1", 98.33, 4.85e-4, 1.25},
329    {"edit1", 100.00, 4.12e-6, 1.25},
330    {"picture", 98.50, 6.38e-3, 1.25},
331    {"long64", 97.50, 4.98e-3, 1.0},
332};
333#endif
334// empty when c is within prompt's bar, else what is outside it
335static std::string breach(const std::string& prompt, const LgrCmp& c) {
336    for (const Bar& b : BARS) {
337        if (prompt != b.prompt) continue;
338        std::string why;
339        char buf[160];
340        if (c.kl_mean > b.kl_mean * b.kl_slack) {
341            std::snprintf(buf, sizeof buf, "KL mean %.2e over %.2e (%.2fx the bar's %.2e)", c.kl_mean, b.kl_mean * b.kl_slack, b.kl_slack, b.kl_mean);
342            why = buf;
343        }
344        if (c.top1_pct() < b.top1_pct - TOP1_SLACK) {
345            std::snprintf(buf, sizeof buf, "top-1 %.2f%% under %.2f%% (the bar's %.2f%% less %.1f)", c.top1_pct(), b.top1_pct - TOP1_SLACK,
346                          b.top1_pct, TOP1_SLACK);
347            why += (why.empty() ? "" : "; ") + std::string(buf);
348        }
349        return why;
350    }
351    return "no bar for " + prompt;
352}
353
354// What made a run's logits, for the base's identity record (LAB/MODEL-base.id): the model file, the engine code that
355// ran (the library or binary holding this function, as loaded: a library rebuilt but not reloaded is still the old
356// one), the source tree's revision, and the FNX_ settings. A base is only compared against runs of the same model
357// file; the rest is shown so a difference can be traced to its build.
358static std::string file_line(const std::string& path) {
359    struct stat st;
360    if (stat(path.c_str(), &st) != 0) return path + " (cannot stat)";
361    char buf[96];
362    std::snprintf(buf, sizeof buf, " %lld bytes, modified %lld", (long long) st.st_size, (long long) st.st_mtime);
363    return path + buf;
364}
365static std::string loaded_code() {
366    Dl_info di;
367    if (!dladdr((void*) &file_line, &di) || !di.dli_fname) return "unknown (dladdr failed)";
368    char real[PATH_MAX];
369    const std::string path = realpath(di.dli_fname, real) ? real : di.dli_fname;
370    // the mapping's inode from /proc/self/maps: the file now at that path may be a newer build
371    const auto addr = (uintptr_t) di.dli_fbase;
372    std::ifstream maps("/proc/self/maps");
373    for (std::string line; std::getline(maps, line);) {
374        uintptr_t lo = 0, hi = 0;
375        unsigned long long ino = 0;
376        char perms[8], dev[16];
377        long long off = 0;
378        if (std::sscanf(line.c_str(), "%" SCNxPTR "-%" SCNxPTR " %7s %llx %15s %llu", &lo, &hi, perms, &off, dev, &ino) != 6) continue;
379        if (addr < lo || addr >= hi) continue;
380        struct stat st;
381        const bool same = stat(path.c_str(), &st) == 0 && (unsigned long long) st.st_ino == ino;
382        return same ? file_line(path) : path + " (inode " + std::to_string(ino) + ", replaced on disk since it was loaded)";
383    }
384    return file_line(path);
385}
386// what the logits depend on besides the model and the code's sums: the card count it was built for, decode's ring and
387// rope scaling (named only when on, so an unscaled build's line is the one its bases recorded)
388static std::string build_line(int ncard, bool f32, double rope_scale = 0.0) {
389    std::string l = "build ncard " + std::to_string(ncard) + " ring " + (f32 ? "fp32" : "fp16-pairs");
390    if (rope_scale) {
391        char s[64];
392        std::snprintf(s, sizeof s, " rope yarn x%.9g", rope_scale);
393        l += s;
394        if (const char* o = std::getenv("FNX_YARN_ORIG_CTX")) l += std::string(" orig ") + o;
395    }
396    return l;
397}
398static std::string run_identity(const char* model) {
399    std::string id;
400    char real[PATH_MAX];
401    id += "model " + file_line(realpath(model, real) ? real : model) + "\n";
402    id += "code " + loaded_code() + "\n";
403    std::string rev;
404    if (std::FILE* p = popen("git -C '" FNX_DIR "' describe --always --dirty --abbrev=12 2>&1", "r")) {
405        char buf[256];
406        while (std::fgets(buf, sizeof buf, p)) rev += buf;
407        if (pclose(p) != 0) rev = "unknown (git: " + rev + ")";
408    }
409    while (!rev.empty() && (rev.back() == '\n' || rev.back() == ' ')) rev.pop_back();
410    id += "tree " FNX_DIR " " + rev + "\n";
411    id += build_line(fnx::NCARD, fnx::ring_f32(), fnx::rope_scale()) + "\n";
412    std::vector<std::string> env;
413    for (char** e = environ; *e; ++e)
414        if (!std::strncmp(*e, "FNX_", 4)) env.emplace_back(*e);
415    std::sort(env.begin(), env.end());
416    id += "env";
417    for (const std::string& e : env) id += " " + e;
418    return id + "\n";
419}
420// the line of an identity record that starts with key + " "
421static std::string id_line(const std::string& id, const std::string& key) {
422    std::istringstream in(id);
423    for (std::string l; std::getline(in, l);)
424        if (l.compare(0, key.size() + 1, key + " ") == 0) return l;
425    return "";
426}
427static void sync_cards() {
428    for (int c = 0; c < fnx::NCARD; ++c) {
429        if (cudaSetDevice(c) != cudaSuccess || cudaDeviceSynchronize() != cudaSuccess)
430            throw std::runtime_error(std::string("sync_cards: ") + cudaGetErrorString(cudaGetLastError()));
431    }
432}
433static int env_ctx(int need) {
434    const char* c = std::getenv("FNX_MAX_CTX");
435    return std::max(c ? std::atoi(c) : 0, need);
436}
437static int lab_check(fnx::Model& m, int argc, char** argv) {
438    const std::string mode = argv[2];
439    const char* long64 = "ref/long64.bin";
440    const std::vector<int> toks = ref_tokens(long64);
441    if (mode == "read") {
442        if (argc < 4) { std::fprintf(stderr, "read needs N [N...]\n"); return 2; }
443        for (int i = 3; i < argc; ++i) {
444            const int n = std::atoi(argv[i]);
445            if (n < 1 || n > (int) toks.size()) { std::fprintf(stderr, "read: N in 1..%zu\n", toks.size()); return 2; }
446            const auto te = std::chrono::steady_clock::now();
447            fnx::Engine e(m, env_ctx(n + 1024), 1);
448            sync_cards();
449            const auto tg = std::chrono::steady_clock::now();
450            e.warm_graphs();
451            sync_cards();
452            const auto t0 = std::chrono::steady_clock::now();
453            e.prefill(std::vector<int>(toks.begin(), toks.begin() + n));
454            sync_cards();
455            const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
456            std::printf("read %d tokens: %.0f ms, %.0f tok/s (engine made in %.1f s, its graphs warmed in %.1f s)\n", n, s * 1000, n / s,
457                        std::chrono::duration<double>(tg - te).count(), std::chrono::duration<double>(t0 - tg).count());
458        }
459        return 0;
460    }
461    if (mode == "decode") {
462        // one request alone as prod decodes it (Session: MTP drafts up to K=6 (their count follows acceptance), lookup drafts up to 15, prod's draft layer files),
463        // on an engine made like prod's (262,144 positions, 6 lanes): the code edit (ends at 636 tokens) and new code (N
464        // tokens, default 1,024), greedy, each once to warm up, then timed; then prose reasoning in the style of thinking
465        // (N tokens) sampled as prod samples (serve/sfnx.json), since thinking is decoded so: seeds 1-5 summed. SAMPLES:
466        // which of edit1, code1, prose2 to run (comma separated, default all), or code1s: new code sampled as prose2 is
467        const int n = argc > 3 ? std::atoi(argv[3]) : 1024, K = argc > 4 ? std::atoi(argv[4]) : 6, LK = argc > 5 ? std::atoi(argv[5]) : 15;
468        if (n < 1) { std::fprintf(stderr, "decode [N]: N >= 1\n"); return 2; }
469        const std::string samples = argc > 6 ? argv[6] : "edit1,code1,prose2";
470        auto wanted = [&](const std::string& name) { return ("," + samples + ",").find("," + name + ",") != std::string::npos; };
471        for (size_t a = 0, b; a <= samples.size(); a = b + 1) {
472            b = samples.find(',', a);
473            if (b == std::string::npos) b = samples.size();
474            const std::string one = samples.substr(a, b - a);
475            if (one != "edit1" && one != "code1" && one != "prose2" && one != "code1s") {
476                std::fprintf(stderr, "decode SAMPLES: edit1, code1, prose2, code1s (comma separated), not '%s'\n", one.c_str());
477                return 2;
478            }
479        }
480        const fnx::Mtp mtp(m, MTP_RT, FNX_DIR "/data/draft_vocab_en.bin");
481        fnx::Engine e(m, env_ctx(262144), 6);
482        e.mtp_attach(mtp);
483        const std::vector<int> eos{248044, 248046};
484        fnx::Sampling greedy, served;
485        served.temperature = 0.6f, served.top_p = 0.95f, served.pen_present = 1.0f;
486        auto run_one = [&](const std::vector<int>& prompt, const fnx::Sampling& smp) {
487            e.reset();
488            fnx::Session s(e, K, LK, eos);
489            fnx::GenStats st;
490            s.read(prompt, st);
491            s.generate(n, smp, [](int) {}, nullptr, st);
492            return st;
493        };
494        auto report = [](const std::string& p, const fnx::GenStats& st) {
495            std::printf("decode %s: %d tokens in %.0f ms, %.1f tok/s, %.2f tokens a round, %.2f ms a round (%d rounds, %d with lookup drafts; drafts %ld of %ld)\n",
496                        p.c_str(), st.generated, st.decode_ms, st.generated * 1000.0 / st.decode_ms, (double) st.generated / st.rounds,
497                        st.decode_ms / st.rounds, st.rounds, st.lookup_rounds, st.drafts_accepted, st.drafts_offered);
498            std::printf("  a round: verify %.2f ms (GPU %.2f, launch %.2f), drafts %.2f ms in %.1f calls (GPU %.2f), commit %.2f, "
499                        "the session's own %.2f\n",
500                        st.verify_ms / st.rounds, st.verify_gpu_ms / st.rounds, st.launch_ms / st.rounds, st.draft_ms / st.rounds,
501                        (double) st.draft_calls / st.rounds, st.draft_gpu_ms / st.rounds, st.commit_ms / st.rounds,
502                        (st.decode_ms - st.verify_ms - st.draft_ms - st.commit_ms) / st.rounds);
503        };
504        bool warm = false;
505        for (const char* p : {"edit1", "code1"}) {
506            if (!wanted(p)) continue;
507            const std::vector<int> prompt = ref_tokens((std::string("ref/") + p + ".bin").c_str());
508            run_one(prompt, greedy);
509            warm = true;
510            report(p, run_one(prompt, greedy));
511        }
512        for (const char* p : {"prose2", "code1s"}) {
513            if (!wanted(p)) continue;
514            const std::string file = std::string(p) == "code1s" ? "code1" : p;
515            const std::vector<int> prompt = ref_tokens(("ref/" + file + ".bin").c_str());
516            if (!warm) {   // the graphs and the first request's costs, out of the timed runs
517                fnx::Sampling w = served;
518                w.seed = 0;
519                fnx::Session s(e, K, LK, eos);
520                fnx::GenStats st;
521                e.reset();
522                s.read(prompt, st);
523                s.generate(64, w, [](int) {}, nullptr, st);
524                warm = true;
525            }
526            fnx::GenStats sum;
527            for (uint64_t seed = 1; seed <= 5; ++seed) {
528                served.seed = seed;
529                const fnx::GenStats st = run_one(prompt, served);
530                sum.generated += st.generated, sum.decode_ms += st.decode_ms, sum.rounds += st.rounds, sum.lookup_rounds += st.lookup_rounds;
531                sum.drafts_accepted += st.drafts_accepted, sum.drafts_offered += st.drafts_offered;
532                sum.verify_ms += st.verify_ms, sum.verify_gpu_ms += st.verify_gpu_ms, sum.launch_ms += st.launch_ms;
533                sum.draft_ms += st.draft_ms, sum.draft_gpu_ms += st.draft_gpu_ms, sum.commit_ms += st.commit_ms, sum.draft_calls += st.draft_calls;
534            }
535            report(std::string(p) + " (served sampling, seeds 1-5)", sum);
536        }
537        return 0;
538    }
539    if (mode == "cache2") {
540        // the conversation cache where a prompt shares much with what a lane holds (prompts made from long64's tokens,
541        // message boundaries where a chat template puts them):
542        //   A. X and Y share a 9k system prompt (75% of each) and alternate on one lane: X's next turn reuses all of X
543        //      (Y's read parks X, though it shares more than half)
544        //   B. a 17k system prompt changed at token 16,000: the prompt reuses 12,288 (the first message's last checkpoint
545        //      before the change) instead of nothing
546        // each cached read against the same prompt read from scratch as cache_test compares them: the first token's top-64
547        // (KL(fresh || cached), at most 1.5e-3, the worst measured, and the same top-1), then 16 greedy tokens a row at a
548        // time (printed, not judged: they may part at a near-tie); exit 1 when a reuse is not what the cache promises or a
549        // first token is off
550        constexpr int TURN = 248045, SYS = 8678, USER = 872;
551        std::vector<int> fill;
552        for (int t : toks)
553            if (t != TURN && t != 248044 && t != 248046) fill.push_back(t);
554        auto span = [&](size_t a, size_t n) {
555            if (a + n > fill.size()) throw std::runtime_error("cache2: long64 too short");
556            return std::vector<int>(fill.begin() + (long) a, fill.begin() + (long) (a + n));
557        };
558        auto cat = [](std::vector<int> a, const std::vector<int>& b) {
559            a.insert(a.end(), b.begin(), b.end());
560            return a;
561        };
562        auto msg = [&](int role, const std::vector<int>& body) { return cat({TURN, role}, body); };
563        const fnx::Mtp mtp(m, MTP_RT, FNX_DIR "/data/draft_vocab_en.bin");
564        fnx::Engine e(m, env_ctx(65536), 1);
565        e.mtp_attach(mtp);
566        const std::vector<int> eos{248044, 248046};
567        int fails = 0;
568        struct Res {
569            std::vector<std::pair<float, int>> top;
570            std::vector<int> gen;
571        };
572        // the prompt read, then its last token's window (top-64) and greedy tokens one row a window
573        auto first16 = [&](fnx::Session& s, const std::vector<int>& p, int& reused) {
574            fnx::GenStats st;
575            s.read(p, st);
576            reused = st.reused;
577            Res r;
578            std::vector<int> o = e.verify({p.back()});
579            r.top = e.top_tokens(1, {})[0];
580            e.commit(1);
581            r.gen.push_back(o[0]);
582            while (r.gen.size() < 16) {
583                o = e.verify({r.gen.back()});
584                e.commit(1);
585                r.gen.push_back(o[0]);
586            }
587            return r;
588        };
589        auto fresh16 = [&](const std::vector<int>& p) {
590            e.reset();
591            fnx::Session f(e, 6, 15, eos, TURN, 0, 0);
592            int r = 0;
593            return first16(f, p, r);
594        };
595        auto judge = [&](const char* name, int reused, int want, const Res& got, const Res& ref) {
596            auto lse = [](const std::vector<std::pair<float, int>>& t) {
597                double mx = t[0].first, s = 0;
598                for (const auto& x : t) s += std::exp(x.first - mx);
599                return mx + std::log(s);
600            };
601            const double la = lse(got.top), lb = lse(ref.top);
602            double kl = 0;
603            for (const auto& x : ref.top) {
604                double qa = got.top.back().first;
605                for (const auto& y : got.top)
606                    if (y.second == x.second) qa = y.first;
607                kl += std::exp(x.first - lb) * ((x.first - lb) - (qa - la));
608            }
609            int same = 0;
610            while (same < 16 && got.gen[(size_t) same] == ref.gen[(size_t) same]) ++same;
611            const bool top1 = got.top[0].second == ref.top[0].second, ok = reused == want && top1 && kl <= 1.5e-3;
612            std::printf("cache2 %s: reused %d (want %d), first token KL %.2e, top-1 %s, %d of 16 greedy tokens as from scratch: %s\n", name,
613                        reused, want, kl, top1 ? "the same" : "DIFFERENT", same, ok ? "ok" : "FAIL");
614            if (!ok) ++fails;
615        };
616        {   // A
617            e.reset();
618            fnx::Session s(e, 6, 15, eos, TURN, (size_t) 32 << 30, 0);
619            const std::vector<int> sys = msg(SYS, span(0, 9000));
620            const std::vector<int> X = cat(sys, msg(USER, span(20000, 3000))), Y = cat(sys, msg(USER, span(30000, 3000)));
621            int r = 0;
622            first16(s, X, r);
623            const std::vector<int> hx = e.lane_history(0);   // X as the lane holds it: its prompt and the reply kept
624            first16(s, Y, r);
625            const std::vector<int> X2 = cat(hx, msg(USER, span(40000, 500)));
626            int reused = 0;
627            const Res got = first16(s, X2, reused);
628            judge("A (X's next turn after Y on its lane)", reused, (int) hx.size(), got, fresh16(X2));
629        }
630        {   // B
631            e.reset();
632            fnx::Session s(e, 6, 15, eos, TURN, (size_t) 32 << 30, 0);
633            const std::vector<int> sys1 = msg(SYS, span(0, 17000));
634            std::vector<int> sys2 = sys1;
635            sys2[16000] = sys2[16000] == fill[1] ? fill[2] : fill[1];
636            const std::vector<int> P1 = cat(sys1, msg(USER, span(20000, 2000))), P2 = cat(sys2, msg(USER, span(20000, 2000)));
637            int r = 0;
638            first16(s, P1, r);
639            first16(s, msg(USER, span(30000, 3000)), r);   // another conversation: P1 parked
640            int reused = 0;
641            const Res got = first16(s, P2, reused);
642            judge("B (the system prompt changed at 16,000)", reused, 12288, got, fresh16(P2));
643        }
644        return fails ? 1 : 0;
645    }
646    if (mode == "bdecode") {
647        // LANES requests decoding together through batched windows with drafts (FNX_BATCH_DRAFTS lookup or 1; the drafts
648        // a lane: the plan's, or FNX_BATCH_FIXED), prod's sampling, seeds fixed: lanes take PROMPTS in turn (comma
649        // separated ref/ names, default prose2,code1), N tokens each (default 512); each lane's prompt read first, then
650        // windows until every lane is done. One warm-up run
651        const int nl = argc > 3 ? std::atoi(argv[3]) : 2, n = argc > 4 ? std::atoi(argv[4]) : 512;
652        if (nl < 1 || nl > 6 || n < 1) { std::fprintf(stderr, "bdecode [LANES 1..6] [N >= 1] [PROMPTS]\n"); return 2; }
653        const std::string names = argc > 5 ? argv[5] : "prose2,code1";
654        if (fnx::batch_drafts() == fnx::BatchDrafts::off) { std::fprintf(stderr, "bdecode: set FNX_BATCH_DRAFTS (lookup or 1)\n"); return 2; }
655        const fnx::Mtp mtp(m, MTP_RT, FNX_DIR "/data/draft_vocab_en.bin");
656        fnx::Engine e(m, env_ctx(262144), 6);
657        e.mtp_attach(mtp);
658        const std::vector<int> eos{248044, 248046};
659        std::vector<int> lanes{0};
660        while ((int) lanes.size() < nl) lanes.push_back(e.add_lane());
661        std::vector<std::vector<int>> prompts;
662        for (size_t a = 0, b; a <= names.size(); a = b + 1) {
663            b = names.find(',', a);
664            if (b == std::string::npos) b = names.size();
665            prompts.push_back(ref_tokens(("ref/" + names.substr(a, b - a) + ".bin").c_str()));
666        }
667        fnx::Sampling s;
668        s.temperature = 0.6f, s.top_p = 0.95f, s.pen_present = 1.0f;
669        fnx::BatchDecoder dec(e, 6, 15, eos, fnx::batch_drafts());
670        const int seed0 = (int) fnx::env_int("FNX_BDECODE_SEED", 1000);   // lane r's sampling seed: seed0 + r
671        for (int run = 0; run < 2; ++run) {
672            std::vector<fnx::BatchLane> bl((size_t) nl);
673            for (int r = 0; r < nl; ++r) {
674                e.use_lane(lanes[(size_t) r]);
675                e.reset();
676                fnx::Session sess(e, 6, 15, eos, 248045, 0, lanes[(size_t) r]);
677                fnx::GenStats st;
678                const std::vector<int>& p = prompts[(size_t) r % prompts.size()];
679                sess.read(p, st);
680                bl[(size_t) r].start(lanes[(size_t) r], s, std::mt19937_64(seed0 + r), p);
681            }
682            std::vector<int> got((size_t) nl, 0);
683            std::vector<bool> ended((size_t) nl, false);
684            int windows = 0, rows = 0, full = 0, full_rows = 0;
685            long lane_windows = 0, full_tokens = 0;   // the windows each lane was in, summed; the tokens of windows with every lane
686            double ms = 0, verify_ms = 0, full_ms = 0, full_verify = 0, full_draft = 0, full_capture = 0;
687            long full_calls = 0, full_captures = 0;
688            for (;;) {
689                std::vector<fnx::BatchLane*> ls;
690                std::vector<int> idx, limit;
691                for (int r = 0; r < nl; ++r)
692                    if (!ended[(size_t) r] && got[(size_t) r] < n) {
693                        ls.push_back(&bl[(size_t) r]);
694                        idx.push_back(r);
695                        limit.push_back(n - got[(size_t) r]);
696                    }
697                if (ls.empty()) break;
698                fnx::BatchDecoder::fit(ls);
699                long emitted = 0;
700                const auto out = dec.window(ls, limit, [&](int i, int) { ++got[(size_t) idx[(size_t) i]], ++emitted; });
701                ms += dec.last_ms;
702                verify_ms += dec.last_verify_ms;
703                ++windows;
704                rows += dec.last_rows;
705                lane_windows += (long) ls.size();
706                if ((int) ls.size() == nl) {
707                    ++full, full_rows += dec.last_rows, full_tokens += emitted, full_ms += dec.last_ms;
708                    full_verify += dec.last_verify_ms, full_draft += dec.last_draft_ms, full_calls += dec.last_calls;
709                    if (e.last_capture_ms > 0) ++full_captures, full_capture += e.last_capture_ms;
710                }
711                for (size_t i = 0; i < out.size(); ++i)
712                    if (out[i].eos) ended[(size_t) idx[i]] = true;
713            }
714            if (run == 0) continue;
715            long tokens = 0, offered = 0, accepted = 0;
716            for (int r = 0; r < nl; ++r) tokens += got[(size_t) r], offered += bl[(size_t) r].offered, accepted += bl[(size_t) r].accepted;
717            std::printf("bdecode %d lanes: every lane in: %.1f tok/s, %.2f rows and %.2f ms a window (%d windows); overall %ld tokens, "
718                        "%.1f tok/s, %d windows, %.2f ms a window (verify %.2f), %.2f tokens a lane a window, drafts %ld of %ld\n",
719                        nl, full ? full_tokens * 1000.0 / full_ms : 0.0, full ? (double) full_rows / full : 0.0, full ? full_ms / full : 0.0,
720                        full, tokens, tokens * 1000.0 / ms, windows, ms / windows, verify_ms / windows, (double) tokens / lane_windows,
721                        accepted, offered);
722            if (full)
723                std::printf("bdecode %d lanes: every lane in, a window: verify %.2f ms, drafting %.2f ms (%.2f draft-layer calls), the "
724                            "rest %.2f ms; graph captures in %ld of %d windows, %.2f ms each\n",
725                            nl, full_verify / full, full_draft / full, (double) full_calls / full, (full_ms - full_verify - full_draft) / full,
726                            full_captures, full, full_captures ? full_capture / full_captures : 0.0);
727        }
728        return 0;
729    }
730    if (mode == "compare") {   // two .lgr files (ref/lgrcmp.py's measures), the first as the reference
731        if (argc < 5) { std::fprintf(stderr, "compare REF.lgr OTHER.lgr\n"); return 2; }
732        Lgr a, b;
733        if (!load_lgr(argv[3], a) || !load_lgr(argv[4], b)) { std::fprintf(stderr, "compare: cannot open both files\n"); return 1; }
734        std::printf("%s vs %s: %s\n", argv[3], argv[4], lgr_compare(a, b).str().c_str());
735        return 0;
736    }
737    if (mode == "batch") {
738        // tools/batch_check.sh's lanes: two long prompts (past 2,048 positions, so the QSA selection runs) and a short one
739        const int gen = argc > 3 ? std::atoi(argv[3]) : 64;
740        if (gen < 1) { std::fprintf(stderr, "batch [GEN]: GEN >= 1\n"); return 2; }
741        const fnx::Mtp mtp(m, MTP_RT, "data/draft_vocab_en.bin");
742        fnx::Engine e(m, env_ctx(100000));
743        return batch_check(m, e, mtp, gen,
744                           {ref_tokens("ref/long2.bin"), ref_tokens("ref/code1.bin"), ref_tokens("ref/long2.bin")});
745    }
746    // exact: the model's llama.cpp reference (FNX_EXACT_REF for long64, else by the model's name: Q4's from llama.cpp
747    // CUDA, Q8_0's from its CPU backend (tools/q8_exact.sh; code1 and edit1 only), any other model's
748    // ref/lgr/llama_cuda_<model>_<prompt>.lgr, which has no bar), held to the bar above, and its own base
749    std::string stem = argv[1];
750    stem = stem.substr(stem.rfind('/') + 1);
751    if (const size_t s = stem.find("-00001-of-"); s != std::string::npos) stem = stem.substr(0, s);
752    else if (stem.size() > 5 && stem.compare(stem.size() - 5, 5, ".gguf") == 0) stem.resize(stem.size() - 5);
753    // the prompts: long64 (62,794 tokens: long-context drift, where any summation reorder moves KL by ~2e-3), the
754    // README's code1 and edit1 (61 and 686 tokens: little room for chaos, so a real error shows plainly) and its
755    // picture (ref/img/sphinx: the logo, the encoder's rows from sphinx.sve; llama.cpp's reference made on Q4
756    // only). code1 and edit1 also run in windows of 1, 2, 3, 11 and 16 rows, which must give the 5-row windows' logits
757    // byte for byte: decode verifies windows of 1..MAXT rows, so a kernel whose sums depend on the row count (or one
758    // that takes another path for small windows, as FNX_HC1) would move served output while every 5-row check passed.
759#if FNX_27B   // the 27B's references are its own, named by the model (Flash-Next's Q4 and Q8 files are not its)
760    const bool q4 = false, q8 = false;
761    const std::string pic_stem = "ref/img/sphinx_" + stem;
762#else
763    const bool q4 = stem.find("UD-Q4_K_XL") != std::string::npos, q8 = stem.find("Q8_0") != std::string::npos;
764#endif
765    const std::string name = argc > 3 ? argv[3] : "try", dir = lab_dir();
766    const bool base_run = name == "base";
767    // a base is written only from a run within the bar: its files go to MODEL-base-new*.lgr first and replace the
768    // base (with its identity record) only when every prompt passed
769    const std::string id_path = dir + "/" + stem + "-base.id", out_name = base_run ? "base-new" : name;
770    const std::string me = run_identity(argv[1]);
771    std::string base_id;
772    {
773        std::ifstream f(id_path);
774        base_id.assign(std::istreambuf_iterator<char>(f), {});
775    }
776    // a base made by another build (card count, ring) is neither compared with nor written over: its logits differ in
777    // their last bits by design, and a base written over would be lost to the build that owns it. A record from before
778    // build lines is three cards', its ring as its env set it
779    if (!base_id.empty()) {
780        std::string theirs = id_line(base_id, "build");
781        if (theirs.empty()) theirs = build_line(3, id_line(base_id, "env").find(" FNX_RING_F32=1") != std::string::npos);
782        if (theirs != id_line(me, "build")) {
783            const char* rs = std::getenv("FNX_ROPE_SCALE");
784            std::printf("exact: the base in %s is another build's (%s; this one: %s): give this build a lab directory of its own, "
785                        "FNX_LAB_DIR=/tmp/fnx-lab-%u-%dcard%s%s\n",
786                        dir.c_str(), theirs.c_str(), id_line(me, "build").c_str(), (unsigned) getuid(), fnx::NCARD, rs ? "-yarn" : "",
787                        rs ? rs : "");
788            return 1;
789        }
790    }
791    if (!base_run) {
792        if (base_id.empty())
793            std::printf("exact: no base identity %s (a base from before identity records, or none): make one with `exact base`\n",
794                        id_path.c_str());
795        else if (id_line(base_id, "model") != id_line(me, "model"))
796            std::printf("exact: the base was made from another model file:\n  base: %s\n  now:  %s\n  make a new one with `exact base`\n",
797                        id_line(base_id, "model").c_str(), id_line(me, "model").c_str());
798        else {
799            std::printf("exact: base from %s\n               %s\n", id_line(base_id, "tree").c_str(), id_line(base_id, "code").c_str());
800            if (id_line(base_id, "env") != id_line(me, "env"))
801                std::printf("  (other settings: base %s; now %s)\n", id_line(base_id, "env").c_str(), id_line(me, "env").c_str());
802        }
803    }
804    const bool base_usable = !base_id.empty() && id_line(base_id, "model") == id_line(me, "model");
805    int rc = 0;
806    std::vector<std::pair<std::string, std::string>> made;   // a base run's files: candidate, base
807    std::string verdicts;
808    auto fail = [&](const std::string& what) {
809        std::printf("  FAIL: %s\n", what.c_str());
810        rc = 1;
811    };
812    for (const char* p : {"long64", "code1", "edit1", "picture"}) {
813        const bool pic = std::string(p) == "picture", long64 = std::string(p) == "long64";
814#if !FNX_27B   // the 27B has its own picture reference
815        if (pic && !q4) {
816            std::printf("exact %s picture: not run (llama.cpp's picture reference is Q4's only)\n", name.c_str());
817            continue;
818        }
819#endif
820        if (long64 && q8 && !std::getenv("FNX_EXACT_REF")) {
821            std::printf("exact %s long64: not run (no llama.cpp reference on Q8_0 at 62k; FNX_EXACT_REF=FILE.lgr gives one)\n",
822                        name.c_str());
823            continue;
824        }
825#if FNX_27B
826        const std::string prompt = pic ? pic_stem + ".bin" : std::string("ref/") + p + ".bin",
827#else
828        const std::string prompt = pic ? "ref/img/sphinx.bin" : std::string("ref/") + p + ".bin",
829#endif
830                          tag = long64 ? "" : std::string("-") + p;
831        // a scaled build is held to llama.cpp run with the same scaling (ref/fnx_logref and ref/img_logref read the same
832        // settings), else the comparison measures the rope change itself; the file names the scale, the trained length
833        // it scales from when set, and the model unless it is Q4's
834        const double scale = fnx::rope_scale();
835        std::string scaled_env, yarn_tag;
836        if (scale) {
837            char s[64];
838            std::snprintf(s, sizeof s, "%.9g", scale);
839            scaled_env = std::string("FNX_ROPE_SCALE=") + s + " ";
840            yarn_tag = std::string("llama_yarn_") + s;
841            if (const char* oc = std::getenv("FNX_YARN_ORIG_CTX")) {
842                scaled_env += std::string("FNX_YARN_ORIG_CTX=") + oc + " ";
843                yarn_tag += std::string("_orig") + oc;
844            }
845            if (!q4) yarn_tag += "_" + stem;
846        }
847        std::string llama_s = long64 && std::getenv("FNX_EXACT_REF") ? std::getenv("FNX_EXACT_REF")
848                              : scale                                ? "ref/lgr/" + yarn_tag + "_" + p + ".lgr"
849#if FNX_27B
850                              : pic                                  ? pic_stem + ".lgr"
851#else
852                              : pic                                  ? "ref/img/sphinx.lgr"
853#endif
854                              : q4                                   ? "ref/lgr/llama_cuda_" + std::string(p) + ".lgr"
855                              : q8                                   ? "ref/lgr/llama_cpu_q8w_" + std::string(p) + ".lgr"
856                                                                     : "ref/lgr/llama_cuda_" + stem + "_" + p + ".lgr";
857        if (std::FILE* f = std::fopen(llama_s.c_str(), "rb")) std::fclose(f);
858        else {
859            if (pic)
860                std::fprintf(stderr, "exact: no llama.cpp reference %s for %s; make it with\n  %sref/img_logref %s MMPROJ.gguf "
861                             "ref/img/sphinx.png 'What does this picture show? Answer in two sentences.' 200 %s\n",
862                             llama_s.c_str(), stem.c_str(), scaled_env.c_str(), argv[1],
863#if FNX_27B
864                             scale ? llama_s.substr(0, llama_s.size() - 4).c_str() : pic_stem.c_str());
865#else
866                             scale ? llama_s.substr(0, llama_s.size() - 4).c_str() : "ref/img/sphinx");
867#endif
868            else
869                std::fprintf(stderr, "exact: no llama.cpp reference %s for %s; make it with\n  %sref/fnx_logref %s %s %d %s\n",
870                             llama_s.c_str(), stem.c_str(), scaled_env.c_str(), argv[1], prompt.c_str(), long64 ? 200 : 300,
871                             llama_s.c_str());
872            std::printf("exact %s %s: FAIL: no llama.cpp reference %s\n", name.c_str(), p, llama_s.c_str());
873            rc = 1;
874            continue;
875        }
876        const int n_prompt = (int) ref_tokens(prompt.c_str()).size();
877        // the logits of the prompt and the reference's steps in windows of T rows, on a fresh engine
878        auto logits = [&](int T, const std::string& out) {
879            fnx::Engine e(m, env_ctx(n_prompt + 1024), 1);
880#if FNX_27B
881            if (pic) setenv("FNX_IMAGES", (pic_stem + ".sve").c_str(), 1);
882#else
883            if (pic) setenv("FNX_IMAGES", "ref/img/sphinx.sve", 1);
884#endif
885            const int r = run_logits(m, e, prompt.c_str(), llama_s.c_str(), T, out.c_str(), true);
886            if (pic) unsetenv("FNX_IMAGES");
887            return r;
888        };
889        const std::string out = dir + "/" + stem + "-" + out_name + tag + ".lgr", base = dir + "/" + stem + "-base" + tag + ".lgr";
890        {
891            const auto t0 = std::chrono::steady_clock::now();
892            if (const int r = logits(5, out)) return r;
893            std::printf("exact %s %s: logits in %.0f s to %s\n", name.c_str(), p,
894                        std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(), out.c_str());
895        }
896        Lgr ref, mine;
897        load_lgr(llama_s, ref);
898        load_lgr(out, mine);
899        const LgrCmp vs_llama = lgr_compare(ref, mine);
900        std::printf("  vs llama.cpp %s: %s\n", q8 ? "CPU" : "CUDA", vs_llama.str().c_str());
901        if (!std::isfinite(vs_llama.kl_mean)) fail("KL is not a number: one side's logits are broken");
902#if !FNX_27B
903        else if (!q4 && !q8) fail("no documented bar for " + stem + ": the numbers above are not judged");
904#endif
905        else if (scale) {
906            // YaRN moves the model's own outputs (docs/verification.md, "Rope scaling"), and llama.cpp's backends part
907            // differently under it, so the bar is not held here: only a port that is plainly broken fails, at 10x the
908            // bar's KL or 5 points of top-1 under it. The byte-for-byte base comparison below still judges
909            std::printf("  scaled: measured against a scaled llama.cpp, not held to the bar\n");
910            for (const Bar& b : BARS)
911                if (p == std::string(b.prompt) && (vs_llama.kl_mean > 10 * b.kl_mean || vs_llama.top1_pct() < b.top1_pct - 5))
912                    fail("far outside the bar for a scaled build (10x its KL or 5 points of top-1): a broken port, not YaRN's shift");
913        } else if (const std::string why = breach(p, vs_llama); !why.empty()) fail("outside the exactness bar: " + why);
914        verdicts += std::string("llama.cpp ") + p + " " + vs_llama.str() + "\n";
915        if (std::string(p) == "code1" || std::string(p) == "edit1")
916            for (int T : {1, 2, 3, 11, 16}) {
917                const std::string rows_out = dir + "/" + stem + "-" + out_name + tag + "-rows" + std::to_string(T) + ".lgr";
918                if (const int r = logits(T, rows_out)) return r;
919                if (same_bytes(out, rows_out)) std::printf("  windows of %d: the 5-row windows' logits byte for byte\n", T);
920                else {
921                    Lgr rows;
922                    load_lgr(rows_out, rows);
923                    fail("windows of " + std::to_string(T) + " give other logits than windows of 5: " + lgr_compare(mine, rows).str());
924                }
925            }
926        if (base_run) {
927            made.emplace_back(out, base);
928            continue;
929        }
930        Lgr b;
931        if (!base_usable) fail("no base to compare with (see above)");
932        else if (!load_lgr(base, b)) fail("no " + base + " (exact base writes it)");
933        else if (same_bytes(base, out)) std::printf("  vs base: byte for byte identical\n");
934        else fail("vs base: DIFFERENT: " + lgr_compare(b, mine).str());
935    }
936    if (base_run) {
937        if (rc != 0 || made.empty()) {
938            std::printf("exact base: NOT written (%s); the base stays as it was, this run's files are %s/%s-base-new*.lgr\n",
939                        made.empty() ? "nothing ran" : "a check failed", dir.c_str(), stem.c_str());
940            return 1;
941        }
942        // the old identity goes first: a base half replaced has no identity, and runs refuse to compare with it
943        if (std::remove(id_path.c_str()) != 0 && errno != ENOENT) throw std::runtime_error("exact base: cannot remove " + id_path);
944        for (const auto& [cand, base] : made)
945            if (std::rename(cand.c_str(), base.c_str()) != 0) throw std::runtime_error("exact base: cannot move " + cand + " to " + base);
946        const std::string tmp = id_path + ".new";
947        std::FILE* f = std::fopen(tmp.c_str(), "w");
948        if (!f) throw std::runtime_error("exact base: cannot write " + tmp);
949        const std::string rec = me + verdicts;
950        const bool ok = std::fwrite(rec.data(), 1, rec.size(), f) == rec.size();
951        if (std::fclose(f) != 0 || !ok || std::rename(tmp.c_str(), id_path.c_str()) != 0)
952            throw std::runtime_error("exact base: cannot write " + id_path);
953        std::printf("exact base: written for %zu prompt(s), identity in %s:\n%s", made.size(), id_path.c_str(), me.c_str());
954    }
955    return rc;
956}
957
958// one command on a loaded model, its arguments as fnx_run takes them (argv[1] the model's path, argv[2] the mode);
959// bin/fnx_lab calls it from libfnx_lab.so for each command, around a model it keeps loaded
960static bool lab_mode(const std::string& mode) {
961    return mode == "exact" || mode == "read" || mode == "batch" || mode == "compare" || mode == "decode" || mode == "bdecode" ||
962           mode == "cache2";
963}
964// a known mode with at least its first argument (each mode checks the rest); else the usage on stderr
965static bool args_ok(int argc, char** argv) {
966    const std::string mode = argc >= 3 ? argv[2] : "";
967    const bool plain = mode == "check" || mode == "gen" || mode == "rows" || mode == "bench" || mode == "bench_step" || mode == "mtp" ||
968                       mode == "spec" || mode == "logits";
969    if (lab_mode(mode) || (plain && argc >= 4)) return true;
970    std::fputs("usage: fnx_run MODEL.gguf MODE ARGS...\n"
971               "  check REF.bin OUT.bin [W] | gen REF.bin N | rows REF.bin T N | bench REF.bin T N | bench_step REF.bin L N C [step]\n"
972               "  mtp RT_DIR REF.bin N K [VOCAB [LK]] | spec REF.bin GEN.txt K [BAD%] | logits PROMPT.bin CONT.lgr T OUT.lgr\n"
973               "  exact [NAME] | read N [N...] | decode [N] [K] [LK] [SAMPLES] | bdecode [LANES] [N] [PROMPTS] | cache2 | batch [GEN] | compare REF.lgr OTHER.lgr\n",
974               stderr);
975    return false;
976}
977
978extern "C" int fnx_run_cmd(fnx::Model* model, int argc, char** argv) {
979    if (!model || !args_ok(argc, argv)) return 2;
980    const std::string mode = argv[2];
981    if (lab_mode(mode)) return lab_check(*model, argc, argv);
982    fnx::Model& m = *model;
983
984    // FNX_MAX_CTX: the context the engine allocates for (default 4096); FNX_LANES: lanes the K/V pool has room for
985    std::optional<fnx::Mtp> mtp_mode;   // mode mtp's draft layer, made before the engine
986    if (mode == "mtp" && argc >= 7) mtp_mode.emplace(m, argv[3], argc > 7 ? argv[7] : "");
987    fnx::Engine e(m, (int) fnx::env_int("FNX_MAX_CTX", 4096),
988                  (int) fnx::env_int("FNX_LANES", 1));
989    if (mode == "logits") {
990        if (argc < 7) { std::fprintf(stderr, "logits needs PROMPT.bin CONT.lgr T OUT.lgr\n"); return 2; }
991        return run_logits(m, e, argv[3], argv[4], std::atoi(argv[5]), argv[6],
992                          fnx::env_flag("FNX_PREFILL"));
993    }
994    if (mode == "mtp") {
995        if (argc < 7) { std::fprintf(stderr, "mtp needs RT_DIR REF.bin N K\n"); return 2; }
996        const fnx::Mtp& mtp = *mtp_mode;
997        e.mtp_attach(mtp);
998        const std::vector<int> prompt = ref_tokens(argv[4]);
999        const int n_gen = std::atoi(argv[5]), K = std::atoi(argv[6]);
1000        if (K < 1 || K + 1 > fnx::MAXT) { std::fprintf(stderr, "K: 1..%d\n", fnx::MAXT - 1); return 2; }
1001        const int LK = argc > 8 ? std::atoi(argv[8]) : 0, LNG = 3;   // lookup drafts (0: off), n-gram length
1002        if (LK < 0 || LK + 1 > fnx::MAXT) { std::fprintf(stderr, "LOOKUP_K: 0..%d\n", fnx::MAXT - 1); return 2; }
1003        // the prompt: all but its last token through the prompt path (the draft layer reading each row with the token
1004        // after it), then the last token through a window, the draft layer reading its row with the first generated.
1005        // FNX_PREFILL=0: the whole prompt in windows, each followed by the draft layer over its rows
1006        std::vector<int> out;
1007        int p = 0, T = 0, d = -1;
1008        const bool batched = fnx::env_int("FNX_PREFILL", 1) != 0;
1009        const auto t_read = std::chrono::steady_clock::now();
1010        if (batched && prompt.size() > 1) {
1011            e.prefill(std::vector<int>(prompt.begin(), prompt.end() - 1), prompt.back());
1012            p = e.pos();
1013            T = 1;
1014            out = e.window({prompt.back()});
1015            d = e.draft(1, true, 0, {out.back()}, p);
1016        } else
1017        for (size_t i = 0; i < prompt.size(); i += fnx::MAXT) {
1018            std::vector<int> w(prompt.begin() + i, prompt.begin() + std::min(prompt.size(), i + fnx::MAXT));
1019            p = e.pos();
1020            T = (int) w.size();
1021            out = e.window(w);
1022            std::vector<int> next(w.begin() + 1, w.end());
1023            next.push_back(i + T < prompt.size() ? prompt[i + T] : out.back());
1024            d = e.draft(T, true, 0, next, p);
1025        }
1026        {
1027            const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_read).count();
1028            std::fprintf(stderr, "prompt: %zu tokens in %.2f s (%.0f tok/s, %s)\n", prompt.size(), s, prompt.size() / s,
1029                         batched ? "prompt path" : "windows");
1030        }
1031        // the chain from the last row: K drafts in all
1032        double dwall = 0, dgpu = 0;
1033        long dcalls = 0;
1034        auto chain = [&](int d1, int src_row, int cell0) {
1035            std::vector<int> drafts{d1};
1036            for (int j = 1; j < K; ++j) {
1037                drafts.push_back(e.draft(1, false, j == 1 ? src_row : 0, {drafts.back()}, cell0 + j));
1038                dwall += e.last_draft_ms;
1039                dgpu += e.last_draft_gpu_ms;
1040                ++dcalls;
1041            }
1042            return drafts;
1043        };
1044        std::vector<int> got{out.back()};
1045        // the LK tokens after the latest earlier place of the last LNG tokens of prompt + got, if its first is d1
1046        auto lookup = [&](int d1) {
1047            std::vector<int> ctx(prompt);
1048            ctx.insert(ctx.end(), got.begin(), got.end());
1049            std::vector<int> r;
1050            if (LK == 0 || (int) ctx.size() <= LNG) return r;
1051            const size_t n0 = ctx.size() - LNG;
1052            for (size_t st = n0; st-- > 0;)
1053                if (std::equal(ctx.begin() + st, ctx.begin() + st + LNG, ctx.begin() + n0)) {
1054                    if (st + LNG < ctx.size() && ctx[st + LNG] == d1)
1055                        r.assign(ctx.begin() + st + LNG, ctx.begin() + std::min(ctx.size(), st + LNG + LK));
1056                    break;
1057                }
1058            return r;
1059        };
1060        int lookups = 0;
1061        std::vector<double> round_ms;
1062        std::vector<int> round_tok;
1063        std::vector<int> drafts = lookup(d);
1064        if (drafts.empty()) drafts = chain(d, T - 1, p + T - 1);
1065        int rounds = 0;
1066        long accepted = 0;
1067        std::vector<long> tried(K, 0), hit(K, 0);   // draft j: rounds that reached it, rounds that accepted it
1068        double verify_ms = 0, verify_gpu = 0, draft_ms = 0, head_ms = 0;
1069        std::vector<int> rows_hist(fnx::MAXT + 1, 0);   // verify windows by their rows
1070        const auto t0 = std::chrono::steady_clock::now();
1071        while ((int) got.size() <= n_gen) {
1072            std::vector<int> rows{got.back()};
1073            rows.insert(rows.end(), drafts.begin(), drafts.end());
1074            p = e.pos();
1075            const auto r0 = std::chrono::steady_clock::now();
1076            const std::vector<int> o = e.verify(rows);
1077            int n = 1;
1078            while (n < (int) rows.size() && rows[n] == o[n - 1]) ++n;
1079            e.commit(n);
1080            verify_ms += e.last_ms;
1081            verify_gpu += e.last_gpu_ms;
1082            ++rows_hist[rows.size()];
1083            ++rounds;
1084            accepted += n - 1;
1085            if ((int) rows.size() - 1 == K)
1086                for (int j = 0; j < K && j < n; ++j) {
1087                    ++tried[j];
1088                    if (j < n - 1) ++hit[j];
1089                }
1090            got.insert(got.end(), o.begin(), o.begin() + n);
1091            const auto d0 = std::chrono::steady_clock::now();
1092            const int d1 = e.draft(n, true, 0, std::vector<int>(o.begin(), o.begin() + n), p);
1093            head_ms += e.last_draft_ms;
1094            drafts = lookup(d1);
1095            if (!drafts.empty()) ++lookups;
1096            else drafts = chain(d1, n - 1, p + n - 1);
1097            const auto d2 = std::chrono::steady_clock::now();
1098            draft_ms += std::chrono::duration<double, std::milli>(d2 - d0).count();
1099            round_ms.push_back(std::chrono::duration<double, std::milli>(d2 - r0).count());
1100            round_tok.push_back(n);
1101        }
1102        const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
1103        std::printf("generated:");
1104        for (int t : got) std::printf(" %d", t);
1105        std::printf("\nmtp K=%d: %d rounds, %zu tokens, %.2f per round (drafts accepted %.1f%%), verify %.2f ms + drafts %.2f ms per round, "
1106                    "%.1f tok/s\n", K, rounds, got.size() - 1, (got.size() - 1.0) / rounds, 100.0 * accepted / ((double) rounds * K),
1107                    verify_ms / rounds, draft_ms / rounds, (got.size() - 1.0) * 1000.0 / ms);
1108        std::printf("draft step (one row): %.3f ms wall, %.3f ms GPU\n", dwall / (dcalls ? dcalls : 1), dgpu / (dcalls ? dcalls : 1));
1109        // a round: the verify window, then the draft layer over its accepted rows (the first draft), then the chain's
1110        // further drafts (or a lookup); the rest is the host between them
1111        std::printf("per round: verify %.2f ms wall (%.2f GPU), first draft %.2f ms, chain %.2f ms (%.2f steps), host %.2f ms; "
1112                    "verify windows by rows:", verify_ms / rounds, verify_gpu / rounds, head_ms / rounds, dwall / rounds,
1113                    (double) dcalls / rounds, (ms - verify_ms - draft_ms) / rounds);
1114        for (int t = 1; t <= fnx::MAXT; ++t)
1115            if (rows_hist[(size_t) t]) std::printf(" %d:%d", t, rows_hist[(size_t) t]);
1116        std::printf("\n");
1117        {   // the best stretch of at least 64 tokens: consecutive rounds, tokens over their wall time
1118            double best = 0;
1119            for (size_t a = 0; a < round_ms.size(); ++a) {
1120                double ms_ = 0;
1121                int tk = 0;
1122                for (size_t b = a; b < round_ms.size(); ++b) {
1123                    ms_ += round_ms[b];
1124                    tk += round_tok[b];
1125                    if (tk >= 64) {
1126                        best = std::max(best, tk * 1000.0 / ms_);
1127                        break;
1128                    }
1129                }
1130            }
1131            std::printf("lookup drafts in %d of %d rounds; best 64-token stretch %.1f tok/s\n", lookups, rounds, best);
1132        }
1133        std::printf("per step (given the steps before were accepted):");
1134        for (int j = 0; j < K; ++j) std::printf(" %.2f", tried[j] ? (double) hit[j] / tried[j] : 0.0);
1135        std::printf("\n");
1136        if (const std::vector<unsigned long long> pc = e.probe_counts(); !pc.empty() && pc[3] > 0) {
1137            std::printf("prefetch probe: %llu layer-windows, distinct experts a layer-window: picked %.2f, guessed %.2f, both %.2f "
1138                        "(%.1f%% of the picked guessed)\n",
1139                        pc[3], (double) pc[0] / pc[3], (double) pc[1] / pc[3], (double) pc[2] / pc[3], 100.0 * pc[2] / pc[0]);
1140            if (pc[4] > 0)
1141                std::printf("prefetch probe, experts in RAM: picked and not in a slot %.2f a layer-window, %.1f%% of them guessed; "
1142                            "guessed, not picked, not in a slot (wasted copies) %.2f\n",
1143                            (double) pc[4] / pc[3], 100.0 * pc[5] / pc[4], (double) pc[6] / pc[3]);
1144        }
1145        // FNX_ROUTE_COUNT=1 with FNX_ROUTE_FILE=path: the run's expert tallies (sfnx's format)
1146        if (const char* rf = std::getenv("FNX_ROUTE_FILE")) {
1147            const std::vector<unsigned> v = e.route_counts();
1148            std::FILE* f = std::fopen(rf, "wb");
1149            if (v.empty() || !f || std::fwrite(v.data(), 4, v.size(), f) != v.size() || std::fclose(f) != 0) {
1150                std::fprintf(stderr, "FNX_ROUTE_FILE %s: no tallies (FNX_ROUTE_COUNT=1?) or not written\n", rf);
1151                return 1;
1152            }
1153        }
1154        // FNX_ROUTE_TRACE=M with FNX_ROUTE_TRACE_FILE=path: decode's picks in order
1155        if (const char* tf = std::getenv("FNX_ROUTE_TRACE_FILE")) {
1156            const std::vector<unsigned> v = e.route_trace();
1157            std::FILE* f = std::fopen(tf, "wb");
1158            if (v.empty() || !f || std::fwrite(v.data(), 4, v.size(), f) != v.size() || std::fclose(f) != 0) {
1159                std::fprintf(stderr, "FNX_ROUTE_TRACE_FILE %s: no trace (FNX_ROUTE_TRACE=M?) or not written\n", tf);
1160                return 1;
1161            }
1162        }
1163        std::printf("rounds %d\n", rounds);
1164        return 0;
1165    }
1166    const std::vector<int> toks = ref_tokens(argv[3]);
1167    if (mode == "check") {
1168        if (argc < 5) { std::fprintf(stderr, "check needs REF.bin OUT.bin [W]\n"); return 2; }
1169        long long w_in = 5;
1170        if (argc > 5 && (!fnx::parse_whole(argv[5], w_in) || w_in < 1 || w_in > fnx::MAXT))
1171            throw std::runtime_error("check: window: want a whole number of rows 1.." + std::to_string(fnx::MAXT) + ", got '" + std::string(argv[5]) + "'");
1172        const int W = (int) w_in;
1173        std::FILE* out = std::fopen(argv[4], "wb");
1174        if (!out) { std::perror(argv[4]); return 1; }
1175        const std::string out_path = argv[4];
1176        e.dump = [&](const std::string& name, int layer, int T, int n, const std::vector<float>& v) {
1177            const std::string full = layer >= 0 ? name + "-" + std::to_string(layer) : name;
1178            const uint32_t nl = (uint32_t) full.size(), nd = 2;
1179            const int64_t ne[2] = {n, T};
1180            std::fwrite(&nl, 4, 1, out);
1181            std::fwrite(full.data(), 1, nl, out);
1182            std::fwrite(&nd, 4, 1, out);
1183            std::fwrite(ne, 8, 2, out);
1184            std::fwrite(v.data(), 4, v.size(), out);
1185            if (std::ferror(out)) throw std::runtime_error("check: " + out_path + " write failed");
1186        };
1187        std::vector<int> next;
1188        for (size_t i = 0; i < toks.size(); i += W) {
1189            std::vector<int> w(toks.begin() + i, toks.begin() + std::min(toks.size(), i + W));
1190            const std::vector<int> o = e.window(w);
1191            next.insert(next.end(), o.begin(), o.end());
1192            std::printf("window at %zu: %zu rows in %.1f ms\n", i, w.size(), e.last_ms);
1193        }
1194        if (std::fclose(out) != 0) throw std::runtime_error("check: " + out_path + ": close failed (a buffered write did not reach the disk)");
1195        std::printf("greedy next token per row:");
1196        for (int t : next) std::printf(" %d", t);
1197        std::printf("\n");
1198    } else if (mode == "spec") {
1199        if (argc < 6) { std::fprintf(stderr, "spec needs GEN.txt K\n"); return 2; }
1200        std::vector<int> ref;
1201        {
1202            std::ifstream f(argv[4]);
1203            std::string word;
1204            if (!(f >> word) || word != "generated:") { std::fprintf(stderr, "%s: not gen's output\n", argv[4]); return 2; }
1205            for (int t; f >> t;) ref.push_back(t);
1206        }
1207        const int K = std::atoi(argv[5]);
1208        const double bad = argc > 6 ? std::atof(argv[6]) / 100.0 : 0.0;
1209        if (K < 0 || K + 1 > fnx::MAXT) { std::fprintf(stderr, "K: 0..%d\n", fnx::MAXT - 1); return 2; }
1210        std::vector<int> o;
1211        for (size_t i = 0; i < toks.size(); i += fnx::MAXT) {
1212            std::vector<int> w(toks.begin() + i, toks.begin() + std::min(toks.size(), i + fnx::MAXT));
1213            o = e.window(w);
1214        }
1215        std::vector<int> got{o.back()};
1216        std::mt19937 rng(7);
1217        std::uniform_real_distribution<double> u(0.0, 1.0);
1218        int windows = 0;
1219        double ms = 0;
1220        while (got.size() + K + 1 <= ref.size()) {
1221            const size_t i = got.size() - 1;   // got[i] = ref[i]: this window's row 0
1222            std::vector<int> rows{got.back()};
1223            for (int j = 1; j <= K; ++j) rows.push_back(ref[i + j]);
1224            if (K > 0 && u(rng) < bad) rows[1 + (int) (u(rng) * K)] ^= 1;
1225            const std::vector<int> out = e.verify(rows);
1226            int n = 1;
1227            while (n < (int) rows.size() && rows[n] == out[n - 1]) ++n;
1228            e.commit(n);
1229            ms += e.last_ms;
1230            ++windows;
1231            for (int j = 0; j < n; ++j) got.push_back(out[j]);
1232        }
1233        size_t same = 0;
1234        while (same < got.size() && same < ref.size() && got[same] == ref[same]) ++same;
1235        std::printf("spec K=%d bad=%.0f%%: %d windows, %zu tokens (%.2f per window), %.2f ms per window, %.1f tok/s; "
1236                    "%zu of %zu tokens match the reference\n", K, bad * 100, windows, got.size() - 1,
1237                    (got.size() - 1.0) / windows, ms / windows, (got.size() - 1.0) * 1000.0 / ms, same, got.size());
1238        return same == got.size() ? 0 : 1;
1239    } else if (mode == "bench_step") {
1240        // what a window costs by its rows, at a context of C tokens of the prompt (read through the prompt path) on every
1241        // lane: verify windows of 1..MAXT rows on one lane, then batched windows (step: one row per lane) on 1..L lanes
1242        // (FNX_LANES >= L); medians of N windows each
1243        if (argc < 7) { std::fprintf(stderr, "bench_step needs L N C [step]\n"); return 2; }
1244        const bool step_only = argc > 7 && std::string(argv[7]) == "step";   // only batched windows of all L lanes
1245        const int L = std::atoi(argv[4]), n = std::atoi(argv[5]), nc = std::atoi(argv[6]);
1246        std::vector<int> lanes{0};
1247        while ((int) lanes.size() < L) lanes.push_back(e.add_lane());
1248        e.warm_graphs();   // every lane's rotary table, as sfnx does after adding its lanes
1249        std::vector<int> x(L);
1250        for (int r = 0; r < L; ++r) {
1251            e.use_lane(lanes[r]);
1252            std::vector<int> ctx(nc);
1253            for (int i = 0; i < nc; ++i) ctx[i] = toks[(i + 97 * r) % toks.size()];
1254            e.prefill(ctx);
1255            x[r] = toks[(nc + 97 * r) % toks.size()];
1256        }
1257        if (n < 2) { std::fprintf(stderr, "bench_step: N 2 or more (the first window captures the graph and is not timed)\n"); return 2; }
1258        e.use_lane(0);
1259        for (int T = 1; T <= (step_only ? 0 : fnx::MAXT); ++T) {
1260            std::vector<double> wall, gpu;
1261            for (int i = 0; i < n; ++i) {
1262                std::vector<int> w;
1263                for (int t = 0; t < T; ++t) w.push_back(toks[(i + t) % toks.size()]);
1264                e.verify(w);
1265                if (i > 0) wall.push_back(e.last_ms), gpu.push_back(e.last_gpu_ms);   // the first captures the graph
1266                e.commit(1);
1267            }
1268            std::fprintf(stderr, "verify, 1 lane, %d rows: wall %.3f ms, gpu %.3f ms\n", T, median(wall), median(gpu));
1269        }
1270        for (int k = step_only ? L : 1; k <= L; ++k) {
1271            const std::vector<int> use(lanes.begin(), lanes.begin() + k);
1272            std::vector<int> xk(x.begin(), x.begin() + k);
1273            std::vector<double> wall, gpu;
1274            for (int i = 0; i < n; ++i) {
1275                xk = e.step(use, xk);
1276                if (i > 0) wall.push_back(e.last_ms), gpu.push_back(e.last_gpu_ms);
1277            }
1278            std::fprintf(stderr, "step, %d lanes, 1 row each: wall %.3f ms, gpu %.3f ms\n", k, median(wall), median(gpu));
1279        }
1280    } else if (mode == "bench") {
1281        if (argc < 6) { std::fprintf(stderr, "bench needs T N\n"); return 2; }
1282        const int T = std::atoi(argv[4]), n = std::atoi(argv[5]);
1283        // FNX_BENCH_CTX=N: the windows at a context of N tokens (the prompt repeated, read through the prompt path)
1284        if (std::getenv("FNX_BENCH_CTX")) {
1285            const int nc = (int) fnx::env_int("FNX_BENCH_CTX", 0);
1286            std::vector<int> ctx(nc);
1287            for (int i = 0; i < nc; ++i) ctx[i] = toks[i % toks.size()];
1288            e.prefill(ctx);
1289        }
1290        std::vector<double> wall, gpu;
1291        for (int i = 0; i < n; ++i) {
1292            std::vector<int> w;
1293            for (int t = 0; t < T; ++t) w.push_back(toks[(i + t) % toks.size()]);
1294            e.verify(w);
1295            if (i > 0) {   // the first window of a T captures its graph
1296                wall.push_back(e.last_ms);
1297                gpu.push_back(e.last_gpu_ms);
1298            }
1299            e.commit(1);
1300        }
1301        auto stats = [](std::vector<double> v, double& med, double& trim) {
1302            med = median(v);
1303            std::sort(v.begin(), v.end());
1304            const size_t a = v.size() / 10, b = v.size() - a;
1305            trim = 0;
1306            for (size_t i = a; i < b; ++i) trim += v[i];
1307            trim /= (double) (b - a);
1308        };
1309        double wm, wt, gm, gt;
1310        stats(wall, wm, wt);
1311        stats(gpu, gm, gt);
1312        std::printf("bench %d windows of %d rows: wall median %.3f trimmed %.3f ms, gpu median %.3f trimmed %.3f ms\n", n - 1, T, wm, wt,
1313                    gm, gt);
1314    } else if (mode == "rows") {
1315        if (argc < 6) { std::fprintf(stderr, "rows needs T N\n"); return 2; }
1316        const int T = std::atoi(argv[4]), n = std::atoi(argv[5]);
1317        if (n < 2) { std::fprintf(stderr, "rows: N 2 or more (the first window captures the graph and is not timed)\n"); return 2; }
1318        std::vector<double> wall, gpu, launch, card[fnx::NCARD];
1319        size_t k = 0;
1320        for (int i = 0; i < n; ++i) {
1321            std::vector<int> w;
1322            for (int t = 0; t < T; ++t) w.push_back(toks[k++ % toks.size()]);
1323            e.window(w);
1324            if (i > 0) {   // the first window of a T captures its graph
1325                wall.push_back(e.last_ms);
1326                gpu.push_back(e.last_gpu_ms);
1327                launch.push_back(e.last_launch_ms);
1328                for (int c = 0; c < fnx::NCARD; ++c) card[c].push_back(e.last_card_ms[c]);
1329            }
1330        }
1331        std::printf("%d windows of %d rows: median wall %.2f ms, gpu %.2f ms (p90 wall %.2f), graph launches %.3f ms; "
1332                    "each card's gpu %.2f / %.2f / %.2f ms\n",
1333                    n - 1, T, median(wall), median(gpu), pct(wall, 0.9), median(launch), median(card[0]), median(card[1]), median(card[2]));
1334    } else {   // gen
1335        const int n = std::atoi(argv[4]);
1336        if (n < 2) { std::fprintf(stderr, "gen: N 2 or more\n"); return 2; }
1337        std::vector<int> o;
1338        for (size_t i = 0; i < toks.size(); i += fnx::MAXT) {
1339            std::vector<int> w(toks.begin() + i, toks.begin() + std::min(toks.size(), i + fnx::MAXT));
1340            o = e.window(w);
1341        }
1342        int cur = o.back();
1343        std::vector<int> gen{cur};
1344        double ms = 0;
1345        std::vector<double> wall, emb, gpu;
1346        for (int i = 1; i < n; ++i) {
1347            cur = e.window({cur})[0];
1348            ms += e.last_ms;
1349            wall.push_back(e.last_ms);
1350            emb.push_back(e.last_embed_ms);
1351            gpu.push_back(e.last_gpu_ms);
1352            gen.push_back(cur);
1353        }
1354        std::printf("generated:");
1355        for (int t : gen) std::printf(" %d", t);
1356        std::printf("\n%d single-row windows: %.2f ms each, %.1f tok/s\n", n - 1, ms / (n - 1), (n - 1) * 1000.0 / ms);
1357        std::printf("  p10/p50/p90 ms: wall %.2f/%.2f/%.2f  embed %.2f/%.2f/%.2f  gpu %.2f/%.2f/%.2f\n", pct(wall, .1),
1358                    pct(wall, .5), pct(wall, .9), pct(emb, .1), pct(emb, .5), pct(emb, .9), pct(gpu, .1), pct(gpu, .5),
1359                    pct(gpu, .9));
1360    }
1361    return 0;
1362}
1363
1364#ifndef FNX_LAB_LIB
1365int main(int argc, char** argv) {
1366    try {
1367        if (!args_ok(argc, argv)) return 2;   // before the model's minutes of loading
1368        fnx::Model m(argv[1]);
1369        return fnx_run_cmd(&m, argc, argv);
1370    } catch (const std::exception& e) {
1371        std::fprintf(stderr, "fnx_run: %s\n", e.what());
1372        return 1;
1373    }
1374}
1375#endif