okami.mom/strata

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

waveringanadsv41: opt-in first-logit dump for serve parity gatesb019a3037

main
108.2 KiB2006 linesraw
1// Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17).
2// Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file.
3// src/ds4/ds4_main.cpp - maya-ds4: DeepSeek-V4.1-Flash on Maya.
4//
5//   maya-ds4 --pack <model>/maya-ds4 --ids 0,128803,... --n 16          greedy tokens after the ids
6//   maya-ds4 --pack ... --ids ... --dump-logits out.f32                every position's logits (the oracle's check)
7//   maya-ds4 --pack ... --serve                                       Maya's engine protocol on stdin / stdout
8//
9// --serve speaks what serve/server.py's StrataEngine expects: INFO lines, then `READY <context> stop`; per request
10// `GEN <max_new> [key=value ...] <id,id,...>` answered by `T <id>` lines and `DONE <generated> <prompt> <prompt ms>
11// <decode ms> <stop|length|cancel> 0 0 <reused> 0 0`; `STOP` ends a request early, `QUIT` the engine.  A prompt that
12// continues the state (the conversation so far) reuses it; one that only shares the last prompt's start goes back to
13// that prompt's end; anything else starts over.  `GENI <max_new> [keys] <file> <ids>` carries the prompt's pictures
14// (the file: see read_pics); the state is shared only where the same picture sits at the same place.  With
15// STRATA_DS4_SLOT_KEEP=1 the conversations are kept when another one takes the model (a slot each: the state, the
16// compressed KV included), and across runs in STRATA_DS4_SLOT_DIR - so a request that does not continue the state but
17// does continue a kept conversation reads only its new tokens.
18// `pin=N` on a GEN marks the first N prompt tokens as a start other requests share (a system prompt and its tools): the
19// read stops there for a checkpoint, so a request behind the same start - another agent - goes back to it instead of
20// reading it again (also without slots).  STRATA_DS4_REUSE=0 turns every reuse off (each request reads its whole prompt).
21#include "ds4_model.hpp"
22#include "ds4_scr_plan.hpp"
23#include "ds4_os.hpp"
24#include "ds4_packinfo.hpp"
25#include "ds4_slotmeta.hpp"
26#include "ds4_picspans.hpp"
27
28#include <algorithm>
29#include <cmath>
30#include <numeric>
31#include <atomic>
32#include <chrono>
33#include <climits>
34#include <condition_variable>
35#include <csignal>
36#include <filesystem>
37#include <memory>
38#include <cstdio>
39#include <fstream>
40#include <sstream>
41#include <cstdlib>
42#include <cstring>
43#include <deque>
44#include <iostream>
45#include <mutex>
46#include <string>
47#include <thread>
48#include <unordered_map>
49#include <vector>
50
51namespace {
52
53double now_ms() {
54    return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
55}
56
57// the bytes this process had the storage read for it (Linux's /proc/self/io; -1 where there is none): the Monitor's
58// disk reads a token, the experts read in place from the model's files included
59long long io_read_bytes() {
60#ifdef __linux__
61    std::FILE* f = std::fopen("/proc/self/io", "r");
62    if (f == nullptr) return -1;
63    char line[128];
64    long long v = -1;
65    while (std::fgets(line, sizeof line, f) != nullptr)
66        if (std::sscanf(line, "read_bytes: %lld", &v) == 1) break;
67    std::fclose(f);
68    return v;
69#else
70    return -1;
71#endif
72}
73
74std::vector<int> parse_ids(const std::string& s) {
75    std::vector<int> v;
76    const char* p = s.c_str();
77    while (*p) {
78        char* e = nullptr;
79        const long x = std::strtol(p, &e, 10);
80        if (e == p) break;
81        v.push_back((int) x);
82        p = e;
83        while (*p == ',' || *p == ' ') ++p;
84    }
85    return v;
86}
87
88void usage() {
89    std::fprintf(stderr,
90                 "maya-ds4 --pack <model>/maya-ds4 [--gpus 0,1,...] [--max-context N] [--reserve-mib N]\n"
91                 "           [--vram-experts F] [--cpu-threads N] [--expert-profile FILE|none] [--ssd-cache GB] [--ssd-policy lru|lfu|lfulru] [--no-expert-cache] [--verbose]\n"
92                 "           [--tp N] [--threads on|off] [--prefill-chunk N] [--dspark on|off|none|auto] [--dspark-block N] [--dspark-conf F] [--experts N|auto]\n"
93                 "           [--vision on|off] [--mmap-experts on|off|auto]\n"
94                 "           (--ids I,J,... [--images FILE] [--n N] [--dump-logits FILE] | --serve\n"
95                 "           | --encode-image FILE.rgb --size WxH --dump-image OUT\n"
96                 "           | --pack-info)\n");
97}
98
99// stdin lines on a thread, so a request can see STOP while it decodes
100struct Lines {
101    std::mutex mu;
102    std::condition_variable cv;
103    std::deque<std::string> q;
104    bool eof = false;
105    std::atomic<bool> stop{false};
106    void start() {
107        std::thread([this] {
108            std::string l;
109            while (std::getline(std::cin, l)) {
110                if (!l.empty() && l.back() == '\r') l.pop_back();
111                std::lock_guard<std::mutex> lk(mu);
112                if (l == "STOP" || l.rfind("STOP ", 0) == 0) {
113                    stop.store(true);
114                    continue;
115                }
116                if (l == "QUIT") stop.store(true);
117                q.push_back(l);
118                cv.notify_all();
119            }
120            std::lock_guard<std::mutex> lk(mu);
121            eof = true;
122            stop.store(true);
123            cv.notify_all();
124        }).detach();
125    }
126    bool next(std::string& l) {
127        std::unique_lock<std::mutex> lk(mu);
128        cv.wait(lk, [&] { return !q.empty() || eof; });
129        if (q.empty()) return false;
130        l = q.front();
131        q.pop_front();
132        return true;
133    }
134};
135
136// The drafts between two stats: each draft position (1st, 2nd, ..) - how often it was verified with every draft
137// before it kept, and how often it was kept then
138std::string per_position(const strata::ds4::Stats& s0, const strata::ds4::Stats& s1) {
139    std::string pp = "per position (kept / reached):";
140    for (int i = 0; i < 8; ++i) {
141        const long long r = s1.draft_reached[i] - s0.draft_reached[i], k = s1.draft_kept[i] - s0.draft_kept[i];
142        if (r <= 0) break;
143        char b[64];
144        std::snprintf(b, sizeof b, " %d: %lld/%lld %.0f%%", i + 1, k, r, 100.0 * (double) k / (double) r);
145        pp += b;
146    }
147    return pp;
148}
149
150static std::FILE* g_round_log = nullptr;
151static std::string g_round_tag;
152static std::vector<float> g_round_conf;
153static int g_round_nd = 0;
154
155// The drafts' cut on the product of their confidences (DeepInfer's cumulative rule): a draft is verified while the chance
156// that it and every draft before it are kept stays at least this - a long window whose later drafts are likely lost is
157// not verified whole.  STRATA_DS4_DSPARK_CUM=F, a request's dspark_cum key; 0: off, only the floor on each draft's own
158// confidence (dspark_conf).  Off by default (not measured faster on code: H100 / owner PC); Project Maya runs 0.5 (a Radeon 8065S: decode +6.5%, the same tokens)
159float dspark_cum_default() {
160    static const float v = [] {
161        const char* e = std::getenv("STRATA_DS4_DSPARK_CUM");
162        return e != nullptr ? (float) std::atof(e) : 0.0f;
163    }();
164    return v;
165}
166
167// ---- suffix drafting (DS4_SUFFIX_DRAFT=K): drafts copied from the token history, no drafter model ---------------------
168// The context's last n (DS4_SUFFIX_MIN, 3) tokens looked up among their earlier occurrences; the one whose match runs
169// furthest back proposes the up to K tokens that followed it, verified by verify() like DSpark's drafts (greedy: the
170// trunk's argmax; sampled: q a point at each draft, the speculative-sampling rule - exact either way).  A match shorter
171// than the floor drafts nothing; the floor rises while recent drafts are rejected, so text that does not repeat itself
172// runs plain steps.
173struct SuffixDrafter {
174    int kmax = 0, nmin = 3;
175    int floor_ = 3;                  // the shortest match that drafts now
176    double ema = 0.5;                // recent accepted share of the drafts offered
177    std::vector<int> h;              // the history indexed so far
178    std::unordered_map<uint64_t, std::vector<int32_t>> at;   // the n-gram ending at i -> every such i, ascending
179    long long rounds = 0, offered = 0, accepted = 0, tried = 0;
180
181    uint64_t key(size_t end) const {   // the n-gram h[end - nmin + 1 .. end]
182        uint64_t k = 1469598103934665603ull;
183        for (size_t i = end + 1 - (size_t) nmin; i <= end; ++i) k = (k ^ (uint64_t) (uint32_t) h[i]) * 1099511628211ull;
184        return k;
185    }
186    // the history becomes toks + [tok]: appended to, or indexed again where it does not continue what was indexed
187    void sync(const std::vector<int32_t>& toks, int tok) {
188        const size_t n = toks.size() + 1;
189        auto want = [&](size_t i) { return i < toks.size() ? toks[i] : tok; };
190        bool prefix = h.size() <= n;
191        for (size_t i = 0; prefix && i < h.size(); ++i) prefix = h[i] == want(i);
192        if (!prefix) {
193            h.clear();
194            at.clear();
195        }
196        h.reserve(n);
197        for (size_t i = h.size(); i < n; ++i) {
198            h.push_back(want(i));
199            if (i + 1 >= (size_t) nmin) at[key(i)].push_back((int32_t) i);
200        }
201    }
202    // up to `room` drafts after the history's end; empty: no match long enough
203    void propose(int room, std::vector<int>& d) {
204        d.clear();
205        const size_t n = h.size();
206        if (room <= 0 || n < (size_t) nmin + 1) return;
207        const auto it = at.find(key(n - 1));
208        if (it == at.end()) return;
209        const std::vector<int32_t>& v = it->second;
210        int best = -1, best_len = 0;
211        int seen = 0;
212        for (size_t j = v.size(); j-- > 0 && seen < 32;) {   // the latest occurrences first
213            const int p = v[j];
214            if ((size_t) p >= n - 1) continue;
215            ++seen;
216            int len = 0;
217            while (len < 64 && (size_t) len <= (size_t) p && h[(size_t) p - len] == h[n - 1 - len]) ++len;
218            if (len > best_len) {
219                best_len = len;
220                best = p;
221            }
222        }
223        if (best < 0 || best_len < floor_) return;
224        // a short match proposes few: 3 tokens of prose that happened before rarely go on the same way, and a window's
225        // cost grows with its rows; a copy's match is soon long
226        const int k = std::min({kmax, room, std::max(2, best_len - 1)});
227        for (size_t i = (size_t) best + 1; i < n && (int) d.size() < k; ++i) d.push_back(h[i]);
228    }
229    void record(int off, int acc) {
230        ++rounds;
231        offered += off;
232        accepted += acc;
233        ema = 0.8 * ema + 0.2 * ((double) acc / (double) std::max(1, off));
234        // a run of rejections asks longer matches of the next drafts; accepted ones bring the floor back
235        floor_ = ema < 0.2 ? std::min(floor_ + 1, 12) : ema > 0.5 ? std::max(nmin, floor_ - 1) : floor_;
236    }
237};
238// DS4_SUFFIX_DRAFT=K: on, at most K drafts a round; K=7 measured best (focalor, 5070 + CPU lane, Cache-Prior routing,
239// 128 tokens): a Python rewrite 12.8 -> 22.7 tok/s, a Go rename 12.6 -> 24.1, prose 13.1 -> 12.8 and 14.7 -> 14.7; the
240// greedy tokens the same as without on all four
241SuffixDrafter* g_suffix = nullptr;
242
243// One round of decoding after `tok` (the token at pos(), not fed yet): with the drafter, its drafts while their
244// confidence holds (at most `room` - 1 of them), verified together; else a plain step.  `out` gets the tokens that follow
245// tok (the accepted drafts, then the trunk's next), the last of them the next round's tok.
246bool round(strata::ds4::Model& m, int tok, int room, bool spec, float conf_min, float temperature, float top_p, int top_k,
247           float min_p, unsigned long long seed, unsigned long long& counter, std::vector<int>& out, int& offered,
248           int& accepted, std::string& err, float cum_min = -1.0f, bool suffix_ok = true) {
249    out.clear();
250    offered = accepted = 0;
251    if (spec && room > 1 && m.draft_block() > 0) {
252        std::vector<int> drafts;
253        std::vector<float> conf;
254        if (!m.draft(tok, drafts, conf, err, temperature, top_p, top_k, min_p, seed, counter)) return false;
255        g_round_conf = conf;
256        g_round_nd = (int) drafts.size();
257        int keep = 0;
258        if (cum_min < 0) cum_min = dspark_cum_default();
259        float cum = 1.0f;
260        while (keep < (int) drafts.size() && keep < room - 1 && conf[(size_t) keep] >= conf_min &&
261               (cum *= conf[(size_t) keep]) >= cum_min)
262            ++keep;
263        if (keep > 0) {
264            drafts.resize((size_t) keep);
265            int acc = 0, next = -1;
266            if (!m.verify(tok, drafts, temperature, top_p, top_k, min_p, seed, counter, acc, next, err)) return false;
267            if (g_round_log != nullptr) {   // DS4_ROUND_LOG: tag, drafts offered, accepted, the confidences
268                std::fprintf(g_round_log, "%s\t%d\t%d", g_round_tag.c_str(), keep, acc);
269                for (int i = 0; i < keep; ++i) std::fprintf(g_round_log, "\t%.4f", g_round_conf[(size_t) i]);
270                std::fprintf(g_round_log, "\n");
271            }
272            counter += (unsigned long long) acc + 1;
273            for (int i = 0; i < acc; ++i) out.push_back(drafts[(size_t) i]);
274            out.push_back(next);
275            offered = keep;
276            accepted = acc;
277            return true;
278        }
279    }
280    if (g_suffix != nullptr && suffix_ok && room > 1 && m.draft_block() == 0) {
281        std::vector<int> drafts;
282        g_suffix->sync(m.tokens(), tok);
283        g_suffix->propose(std::min(room - 1, 15), drafts);
284        if (!drafts.empty()) {
285            int acc = 0, next = -1;
286            if (!m.verify(tok, drafts, temperature, top_p, top_k, min_p, seed, counter, acc, next, err)) return false;
287            g_suffix->record((int) drafts.size(), acc);
288            if (g_round_log != nullptr)
289                std::fprintf(g_round_log, "%s\tsuffix\t%zu\t%d\n", g_round_tag.c_str(), drafts.size(), acc);
290            counter += (unsigned long long) acc + 1;
291            for (int i = 0; i < acc; ++i) out.push_back(drafts[(size_t) i]);
292            out.push_back(next);
293            offered = (int) drafts.size();
294            accepted = acc;
295            return true;
296        }
297        ++g_suffix->tried;
298    }
299    if (!m.step(tok, true, err)) return false;
300    out.push_back(m.sample(temperature, top_p, top_k, min_p, seed, counter++));
301    return true;
302}
303
304struct Req {
305    long long max_new = 0;
306    float temperature = 0.0f, top_p = 1.0f, min_p = 0.0f;
307    int top_k = 64;
308    unsigned long long seed = 0;
309    int spec = -1;          // spec=0|1: this request drafts or not (-1: as the engine was started)
310    float conf = -1.0f;     // dspark_conf=F: the drafts' confidence floor for this request (-1: the engine's)
311    long long pin = 0;      // pin=N: the first N prompt tokens are a start other requests share (a system prompt and its
312                            // tools): the state at N is kept as a checkpoint, so another agent behind the same start
313                            // goes back to it instead of reading it again
314    float cum = -1.0f;      // dspark_cum=F: the cut on the product of the confidences (-1: the engine's, dspark_cum_default)
315    std::string file;   // GENI: the pictures
316    std::vector<int> ids;
317    int score = 0;          // score=N (a test of reuse, e.g. SCR): the prompt's last N tokens read in windows of 8 with
318    std::string score_out;  // their next-token log-probabilities written to scoreout=PATH (quant_quality.py rows)
319};
320
321namespace ps = strata::ds4::picspans;
322
323// A prompt's picture: where its span starts, its pixels (the server's resize: RGB rows, both sides multiples of the
324// patch size), a hash of them; once encoded, its span's rows
325struct Pic {
326    int64_t start = 0;
327    int width = 0, height = 0;
328    uint64_t hash = 0;
329    size_t len = 0;   // the span (0: not known yet)
330    std::vector<uint8_t> rgb;
331};
332
333// GENI's file: int32 'DSI1', int32 count, then per picture int64 start, int32 width, int32 height and its
334// height x width x 3 RGB bytes, in prompt order
335bool read_pics(const std::string& path, std::vector<Pic>& v, std::string& err) {
336    std::FILE* f = std::fopen(path.c_str(), "rb");
337    if (f == nullptr) {
338        err = "cannot open the pictures' file " + path;
339        return false;
340    }
341    char magic[4] = {};
342    int32_t n = 0;
343    bool ok = std::fread(magic, 1, 4, f) == 4 && std::memcmp(magic, "DSI1", 4) == 0 && std::fread(&n, 4, 1, f) == 1 &&
344              n >= 0 && n <= 4096;
345    for (int i = 0; ok && i < n; ++i) {
346        Pic p;
347        int32_t wh[2] = {};
348        ok = std::fread(&p.start, 8, 1, f) == 1 && std::fread(wh, 4, 2, f) == 2 && wh[0] > 0 && wh[1] > 0 &&
349             (int64_t) wh[0] * wh[1] <= (64 << 20);
350        if (!ok) break;
351        p.width = wh[0], p.height = wh[1];
352        p.rgb.resize((size_t) p.width * p.height * 3);
353        ok = std::fread(p.rgb.data(), 1, p.rgb.size(), f) == p.rgb.size();
354        uint64_t h = 1469598103934665603ull;   // FNV-1a over the size and the pixels
355        for (int32_t x : wh)
356            for (int b = 0; b < 4; ++b) h = (h ^ (uint8_t) (x >> (8 * b))) * 1099511628211ull;
357        for (uint8_t b : p.rgb) h = (h ^ b) * 1099511628211ull;
358        p.hash = h;
359        v.push_back(std::move(p));
360    }
361    std::fclose(f);
362    if (!ok) err = path + ": not a pictures' file (DSI1)";
363    return ok;
364}
365
366// the encoded spans, the latest few (a conversation sends its pictures with every turn)
367struct SpanCache {
368    std::deque<std::pair<uint64_t, std::shared_ptr<const std::vector<uint16_t>>>> q;
369    std::shared_ptr<const std::vector<uint16_t>> get(strata::ds4::Model& m, const Pic& p, std::string& err) {
370        for (size_t i = 0; i < q.size(); ++i)
371            if (q[i].first == p.hash) {
372                auto r = q[i].second;
373                q.erase(q.begin() + (long) i);
374                q.emplace_front(p.hash, r);
375                return r;
376            }
377        auto rows = std::make_shared<std::vector<uint16_t>>();
378        if (!m.encode_image(p.rgb.data(), p.width, p.height, *rows, err)) return nullptr;
379        q.emplace_front(p.hash, rows);
380        if (q.size() > 8) q.pop_back();
381        return rows;
382    }
383};
384
385bool parse_gen(const std::string& line, Req& r, bool geni) {
386    const char* p = line.c_str() + (geni ? 5 : 4);
387    char* e = nullptr;
388    r.max_new = std::strtoll(p, &e, 10);
389    if (e == p) return false;
390    p = e;
391    for (;;) {
392        while (*p == ' ') ++p;
393        const char* s = p;
394        while (*p && *p != ' ') ++p;
395        if (p == s) break;
396        const std::string tok(s, (size_t) (p - s));
397        const size_t eq = tok.find('=');
398        if (eq == std::string::npos && geni && r.file.empty()) {
399            r.file = tok;
400            continue;
401        }
402        if (eq == std::string::npos) {
403            r.ids = parse_ids(tok);
404            break;
405        }
406        const std::string k = tok.substr(0, eq), v = tok.substr(eq + 1);
407        if (k == "temperature") r.temperature = std::strtof(v.c_str(), nullptr);
408        else if (k == "top_p") r.top_p = std::strtof(v.c_str(), nullptr);
409        else if (k == "top_k") r.top_k = std::atoi(v.c_str());
410        else if (k == "min_p") r.min_p = std::strtof(v.c_str(), nullptr);
411        else if (k == "seed") r.seed = std::strtoull(v.c_str(), nullptr, 10);
412        else if (k == "spec") r.spec = std::atoi(v.c_str()) != 0;
413        else if (k == "dspark_conf") r.conf = std::strtof(v.c_str(), nullptr);
414        else if (k == "pin") r.pin = std::atoll(v.c_str());
415        else if (k == "score") r.score = std::max(0, std::atoi(v.c_str()));
416        else if (k == "scoreout") r.score_out = v;
417        else if (k == "dspark_cum" || k == "spec_cum") r.cum = std::strtof(v.c_str(), nullptr);
418    }
419    return !r.ids.empty() && (!geni || !r.file.empty());
420}
421
422int serve(strata::ds4::Model& m, const std::string& eos_list, bool spec, float conf_min, const std::string& pack) {
423    std::vector<int> eos = parse_ids(eos_list);
424    for (const std::string& l : m.info_lines()) std::printf("%s\n", l.c_str());
425    std::printf("READY %lld stop\n", (long long) m.max_context());
426    std::fflush(stdout);
427    std::fprintf(stderr, "maya ds4 serve: GEN <max_new> [keys] <ids>; GENI <max_new> [keys] <pictures> <ids>; STOP, QUIT\n");
428    Lines in;
429    in.start();
430    std::string line;
431    unsigned long long counter = 0;
432    std::vector<Pic> held;   // the pictures the state holds (start, hash, span)
433    SpanCache spans;
434    const int img_tok = m.image_token();
435    // CONVERSATION SLOTS: a request that does not continue the conversation in the model first sets that one aside
436    // (Model::slot_save: its window rings, the compressors' partial groups and every source's compressed KV and index
437    // keys), then takes back the kept conversation this prompt does continue (slot_load) - chats, and an agent's side
438    // requests, that interleave no longer re-read each other's prompts (70k and 185k tokens alternating: 75-200 s a
439    // switch at ~930 tok/s).  STRATA_DS4_SLOT_KEEP=1 turns them on and keeps them across runs, in STRATA_DS4_SLOT_DIR
440    // (default <pack>/slots): a slot is a .bin (the state) and a .meta (this model's identity, the conversation's
441    // tokens and its size), both written under a temporary name first; a slot whose .meta is missing, foreign or does
442    // not match its file, or unused for STRATA_DS4_SLOT_DAYS (7) days, is removed at start.  STRATA_DS4_SLOT_CAP (4) is
443    // the conversations kept in RAM; past it the least recently used is written to the folder and read back from there
444    // (RAM first, the folder past the cap), and the engine's end writes the ones in RAM to the folder, so the next run
445    // reads on from them.  STRATA_DS4_SLOT_GB (16) caps the folder's .bin files: at start, and after every write, the
446    // folder's least recently used conversation is removed while they are over it (never the one just written, so a
447    // conversation bigger than the cap stays).  STRATA_DS4_SLOT_MIN (1024) is the shortest conversation set aside (a
448    // shorter one is read again in about the time its slot would take).  A conversation with pictures keeps them in a
449    // .pics file (start, span, hash, size each): the matchers compare a picture's span by its hash (picspans::keyed),
450    // so a prompt takes back a slot only where its tokens and its pictures agree.
451    const auto env_num = [](const char* k, double d) { const char* v = std::getenv(k); return v ? std::atof(v) : d; };
452    const bool slot_keep =
453        std::getenv("STRATA_DS4_SLOT_KEEP") != nullptr && std::atoi(std::getenv("STRATA_DS4_SLOT_KEEP")) != 0;
454    const bool reuse = std::getenv("STRATA_DS4_REUSE") == nullptr || std::atoi(std::getenv("STRATA_DS4_REUSE")) != 0;
455    const char* scr_env = std::getenv("STRATA_DS4_SCR");
456    const bool scr = scr_env != nullptr && std::string(scr_env) == "1";
457    std::vector<int64_t> scr_pads;
458    std::vector<int64_t> state_pads;   // (the pads of the conversation in the model, as a request starts: a slot keeps them)
459    // (with SCR on, a slot also holds the masters - the engine's - and the pad positions - a .pads file beside it)
460    int slot_max = slot_keep ? std::max(0, (int) env_num("STRATA_DS4_SLOT_CAP", 4)) : 0;
461    const size_t slot_min = (size_t) std::max(1.0, env_num("STRATA_DS4_SLOT_MIN", 1024));
462    const double slot_days = env_num("STRATA_DS4_SLOT_DAYS", 7);
463    const uint64_t slot_budget = (uint64_t) (env_num("STRATA_DS4_SLOT_GB", 16) * 1073741824.0);
464    namespace fs = std::filesystem;
465    std::filesystem::path slot_dir;
466    struct Slot {
467        std::vector<int32_t> tokens;
468        std::string path;                            // empty: the state is in data (RAM)
469        uint64_t bytes = 0, used = 0;
470        std::shared_ptr<std::vector<uint8_t>> data;   // the RAM slot's bytes (null: a file slot)
471        std::vector<int64_t> cks;                     // the positions short of its end it can be taken back at
472        std::vector<int64_t> pads;                    // SCR: the pad tokens' positions in `tokens`
473        std::vector<ps::Span> pics;                   // its pictures, in `tokens`' positions
474        std::vector<int32_t> keys;                    // `tokens` as the matchers see them (picspans::keyed)
475    };
476    const auto spans_of = [](const std::vector<Pic>& v) {
477        std::vector<ps::Span> out;
478        for (const Pic& q : v) out.push_back({q.start, (int64_t) q.len, q.hash, q.width, q.height});
479        return out;
480    };
481    const auto pics_of_spans = [](const std::vector<ps::Span>& v, size_t below) {
482        std::vector<Pic> out;
483        for (const ps::Span& s : v)
484            if ((size_t) s.start < below) {
485                Pic q;
486                q.start = s.start, q.width = s.width, q.height = s.height, q.hash = s.hash, q.len = (size_t) s.len;
487                out.push_back(std::move(q));
488            }
489        return out;
490    };
491    const auto ranges_of = [](const std::vector<ps::Span>& v) {
492        std::vector<std::pair<int64_t, int64_t>> out;
493        for (const ps::Span& s : v) out.emplace_back(s.start, s.len);
494        return out;
495    };
496    std::vector<Slot> slots;
497    uint64_t slot_clock = 0, slot_seq = 0;
498    const std::string slot_identity = m.slot_identity();
499    const auto note = [&](const std::string& msg) {
500        std::fprintf(stderr, "ds4 slots: %s\n", msg.c_str());
501        std::printf("NOTE sessions: %s\n", msg.c_str());
502        std::fflush(stdout);
503    };
504    const auto gb = [](uint64_t b) {
505        char s[32];
506        std::snprintf(s, sizeof s, "%.2f GB", (double) b / 1e9);
507        return std::string(s);
508    };
509    const auto meta_of = [](const std::string& bin) { return bin.substr(0, bin.size() - 4) + ".meta"; };
510    const auto pads_of = [](const std::string& bin) { return bin.substr(0, bin.size() - 4) + ".pads"; };
511    const auto picf_of = [](const std::string& bin) { return bin.substr(0, bin.size() - 4) + ".pics"; };
512    const auto pads_read = [&](const std::string& bin) {
513        std::vector<int64_t> v;
514        std::ifstream f(pads_of(bin), std::ios::binary);
515        int64_t x = 0;
516        while (f.read((char*) &x, 8)) v.push_back(x);
517        return v;
518    };
519    const auto meta_write = [&](const std::string& path, const std::vector<int32_t>& toks, uint64_t bytes,
520                                const std::vector<int64_t>& cks) -> bool {
521        return strata::ds4::slotmeta::write(path, slot_identity, toks, bytes, cks);
522    };
523    // a .meta of this model -> its tokens and the slot's size (false: foreign, damaged or not this model's)
524    const auto meta_read = [&](const std::string& path, std::vector<int32_t>& toks, uint64_t& bytes,
525                               std::vector<int64_t>& cks) -> bool {
526        return strata::ds4::slotmeta::read(path, slot_identity, m.max_context(), toks, bytes, cks);
527    };
528    const auto slot_age_days = [](const std::string& p) {
529        std::error_code ec;
530        const auto t = fs::last_write_time(p, ec);
531        if (ec) return 1e9;
532        return std::chrono::duration<double>(fs::file_time_type::clock::now() - t).count() / 86400.0;
533    };
534    const auto slot_drop = [&](size_t i) {
535        if (slots[i].data)   // a RAM slot: its buffer simply dies
536            slots[i].data.reset();
537        else {
538            std::error_code ec;
539            std::filesystem::remove(slots[i].path, ec);
540            std::filesystem::remove(meta_of(slots[i].path), ec);
541            std::filesystem::remove(pads_of(slots[i].path), ec);
542            std::filesystem::remove(picf_of(slots[i].path), ec);
543        }
544        slots.erase(slots.begin() + (long) i);
545    };
546    const auto slot_count = [&](int& ram, int& disk) {
547        ram = disk = 0;
548        for (const Slot& s : slots) (s.data ? ram : disk) += 1;
549    };
550    // the folder's conversations (their .bin; a .meta beside each is a few KB: identity and tokens)
551    const auto slot_folder_bytes = [&]() {
552        uint64_t total = 0;
553        std::error_code ec;
554        for (const auto& de : std::filesystem::directory_iterator(slot_dir, ec)) {
555            const std::string fn = de.path().filename().string();
556            if (fn.rfind("slot-", 0) == 0 && fn.size() > 9 && fn.compare(fn.size() - 4, 4, ".bin") == 0) {
557                const uint64_t bytes = (uint64_t) std::filesystem::file_size(de.path(), ec);
558                if (!ec) total += bytes;
559            }
560        }
561        return total;
562    };
563    // the folder over STRATA_DS4_SLOT_GB: its least recently used conversation goes first, and never `keep` (the one just
564    // written), so a conversation bigger than the cap stays
565    const auto slot_trim = [&](const std::string& keep) {
566        const uint64_t before = slot_folder_bytes();
567        size_t dropped = 0;
568        while (slot_folder_bytes() > slot_budget) {
569            size_t lru = SIZE_MAX;
570            for (size_t i = 0; i < slots.size(); ++i)
571                if (!slots[i].data && slots[i].path != keep && (lru == SIZE_MAX || slots[i].used < slots[lru].used))
572                    lru = i;
573            if (lru == SIZE_MAX) break;
574            slot_drop(lru);
575            ++dropped;
576        }
577        if (dropped > 0) {
578            char msg[256];
579            std::snprintf(msg, sizeof msg, "the folder held %s (over STRATA_DS4_SLOT_GB, %s): %zu least recently used "
580                          "conversation(s) removed, %s left", gb(before).c_str(), gb(slot_budget).c_str(), dropped,
581                          gb(slot_folder_bytes()).c_str());
582            note(msg);
583        }
584    };
585    // a RAM slot into the folder (its bytes, then its .meta); false: not written (its bytes go, then)
586    const auto slot_write_file = [&](Slot& s) -> bool {
587        std::error_code ec;
588        const auto space = std::filesystem::space(slot_dir, ec);
589        if (!ec && space.available < ((uint64_t) 8 << 30)) {   // (8 GB free, the GLM engine's guard)
590            std::fprintf(stderr, "ds4 slots: under 8 GB free in %s - the conversation is not written\n",
591                         slot_dir.string().c_str());
592            return false;
593        }
594        const auto stamp = std::chrono::duration_cast<std::chrono::milliseconds>(
595                               std::chrono::system_clock::now().time_since_epoch()).count();
596        const std::string path =
597            (slot_dir / ("slot-" + std::to_string(stamp) + "-" + std::to_string(++slot_seq) + ".bin")).string();
598        {
599            std::ofstream f(path + ".tmp", std::ios::binary | std::ios::trunc);
600            f.write((const char*) s.data->data(), (std::streamsize) s.data->size());
601            f.flush();
602            if (!f) {
603                std::filesystem::remove(path + ".tmp", ec);
604                std::fprintf(stderr, "ds4 slots: writing %s.tmp failed (disk full?)\n", path.c_str());
605                return false;
606            }
607        }
608        if (!s.pads.empty()) {   // (before the .meta: a slot whose .meta is there has its pads)
609            std::ofstream pf(pads_of(path), std::ios::binary | std::ios::trunc);
610            pf.write((const char*) s.pads.data(), (std::streamsize) (s.pads.size() * 8));
611        }
612        const bool pics_ok = s.pics.empty() || ps::write(picf_of(path), s.pics);   // (also before the .meta)
613        fs::rename(path + ".tmp", path, ec);
614        if (ec || !pics_ok || !meta_write(meta_of(path), s.tokens, s.data->size(), s.cks)) {
615            std::filesystem::remove(pads_of(path), ec);
616            std::filesystem::remove(picf_of(path), ec);
617            std::filesystem::remove(path + ".tmp", ec);
618            std::filesystem::remove(path, ec);
619            std::fprintf(stderr, "ds4 slots: writing %s failed\n", path.c_str());
620            return false;
621        }
622        s.path = path;
623        s.bytes = s.data->size();
624        s.data.reset();
625        slot_trim(path);   // (the folder over its cap: the least recently used conversation goes, not this one)
626        return true;
627    };
628    // the conversation in the model into a slot (the state is lost otherwise: another one takes the model)
629    const auto slot_put = [&](const char* why) {
630        if (slot_max <= 0) return;
631        const std::vector<int32_t>& t = m.tokens();
632        if (t.size() < slot_min) return;   // (a fresh engine's 0-token state is no conversation: nothing to set aside)
633        const auto t0 = std::chrono::steady_clock::now();
634        auto buf = std::make_shared<std::vector<uint8_t>>();
635        std::string e;
636        const uint64_t bytes = m.slot_save(*buf, e);   // (a state unchanged since it was taken refuses here: nothing
637        if (bytes == 0) {                             // changes, its slot stays)
638            if (e != "it is already set aside")
639                std::fprintf(stderr, "ds4 slots: setting the conversation aside failed (%s) - it is read from token 0 "
640                                     "when it comes back\n", e.c_str());
641            return;
642        }
643        std::vector<ps::Span> pics = spans_of(held);
644        std::vector<int32_t> keys = ps::keyed(t, pics);
645        for (size_t i = slots.size(); i-- > 0;)   // an earlier state of this conversation is superseded
646            if (slots[i].keys.size() <= keys.size() && std::equal(slots[i].keys.begin(), slots[i].keys.end(), keys.begin()))
647                slot_drop(i);
648        slots.push_back({t, "", bytes, ++slot_clock, nullptr, m.check_positions(), scr ? state_pads : std::vector<int64_t>{},
649                         std::move(pics), std::move(keys)});
650        slots.back().data = buf;
651        while (true) {   // past the cap: the least recently used conversation in RAM to the folder, or gone
652            int ram = 0, disk = 0;
653            slot_count(ram, disk);
654            if (ram <= slot_max) break;
655            size_t lru = SIZE_MAX;
656            for (size_t i = 0; i < slots.size(); ++i)
657                if (slots[i].data && (lru == SIZE_MAX || slots[i].used < slots[lru].used)) lru = i;
658            if (lru == SIZE_MAX) break;
659            if (!slot_write_file(slots[lru])) slot_drop(lru);
660        }
661        int ram = 0, disk = 0;
662        slot_count(ram, disk);
663        char msg[256];
664        std::snprintf(msg, sizeof msg, "saved a %zu-token conversation%s%s (%s in RAM in %.1f s); %d in RAM, %d in %s",
665                      t.size(), held.empty() ? "" : (" with " + std::to_string(held.size()) + " picture(s)").c_str(), why, gb(bytes).c_str(),
666                      std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(), ram, disk,
667                      slot_dir.string().c_str());
668        note(msg);
669    };
670    // kept conversation i back in the model, whole (false: e says why; the model is reset if the load broke off)
671    const auto slot_bring = [&](size_t i, std::string& e) -> bool {
672        const int64_t n = (int64_t) slots[i].tokens.size();
673        const auto marked = [&](bool ok) {   // (the state's pictures: no Engram n-grams over them)
674            if (ok && !slots[i].pics.empty()) m.mark_images(ranges_of(slots[i].pics));
675            return ok;
676        };
677        if (slots[i].data) return marked(m.slot_load(slots[i].data->data(), slots[i].data->size(), n, e));
678        std::ifstream f(slots[i].path, std::ios::binary);
679        if (!f) {
680            e = "cannot read " + slots[i].path;
681            return false;
682        }
683        f.seekg(0, std::ios::end);
684        const std::streamoff sz = f.tellg();
685        f.seekg(0, std::ios::beg);
686        if (sz <= 0) {
687            e = slots[i].path + " is empty";
688            return false;
689        }
690        std::vector<uint8_t> file((size_t) sz);
691        if (!f.read((char*) file.data(), sz)) {
692            e = "reading " + slots[i].path + " failed";
693            return false;
694        }
695        return marked(m.slot_load(file.data(), file.size(), n, e));
696    };
697    // the kept conversation this prompt shares the most of - past `floor` tokens, what the model itself can go back
698    // to - back in the model: the tokens it covers (0: none).  A conversation the prompt continues whole comes back
699    // whole (`whole`); one it leaves part way - a retried prompt, a history the client renders again without the
700    // earlier reasoning - comes back at its latest checkpoint the prompt still agrees with (the end of a prompt, the
701    // position before it, the anchor where its run of continued prompts began).
702    const auto slot_take = [&](const std::vector<int>& prompt, size_t floor, bool& whole) -> size_t {
703        whole = false;
704        if (slot_max <= 0 || prompt.size() < 2) return 0;
705        std::vector<strata::ds4::slotmeta::Cand> cands;
706        for (const Slot& sl : slots) cands.push_back({&sl.keys, &sl.cks});
707        size_t len = 0;
708        const size_t best = strata::ds4::slotmeta::pick(cands, prompt, floor, &len);
709        if (best == SIZE_MAX) return 0;
710        const size_t whole_len = slots[best].tokens.size();
711        const auto t0 = std::chrono::steady_clock::now();
712        const bool ram = slots[best].data != nullptr;
713        std::string e;
714        if (!slot_bring(best, e)) {
715            note("taking a conversation back failed (" + (e.empty() ? std::string("it did not load") : e) +
716                 ") - reading its prompt again");
717            slot_drop(best);
718            return 0;
719        }
720        if (len < whole_len && !(m.restore((int64_t) len) && (size_t) m.pos() == len)) {
721            note("going back to token " + std::to_string(len) + " of a kept conversation failed - reading its prompt again");
722            m.reset();
723            return 0;
724        }
725        whole = len == whole_len;
726        held = pics_of_spans(slots[best].pics, len);
727        slots[best].used = ++slot_clock;
728        if (!ram) {   // its age counts from its last use (a file slot's only)
729            std::error_code ec;
730            fs::last_write_time(meta_of(slots[best].path), fs::file_time_type::clock::now(), ec);
731        }
732        char msg[256];
733        std::string part;
734        if (!whole) part = " at token " + std::to_string(len) + " of " + std::to_string(whole_len);
735        std::snprintf(msg, sizeof msg, "took back a %zu-token conversation%s from %s (%.1f s); %zu new tokens to read",
736                      len, part.c_str(), ram ? "RAM" : "the folder",
737                      std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(),
738                      prompt.size() - len);
739        note(msg);
740        return len;
741    };
742    if (slot_max > 0) {
743        slot_dir = std::getenv("STRATA_DS4_SLOT_DIR") ? std::filesystem::path(std::getenv("STRATA_DS4_SLOT_DIR"))
744                                                      : std::filesystem::path(pack) / "slots";
745        std::error_code ec;
746        std::filesystem::create_directories(slot_dir, ec);
747        if (!std::filesystem::is_directory(slot_dir, ec)) {
748            std::fprintf(stderr, "ds4 slots: %s is not writable - conversations are not set aside\n",
749                         slot_dir.string().c_str());
750            slot_max = 0;
751        } else {
752            struct Found {
753                std::string bin;
754                std::vector<int32_t> toks;
755                uint64_t bytes;
756                std::vector<int64_t> cks;
757                fs::file_time_type t;
758                std::vector<ps::Span> pics;
759            };
760            std::vector<Found> found;
761            size_t refused = 0;
762            for (const auto& de : std::filesystem::directory_iterator(slot_dir, ec)) {   // a previous run's slots
763                const std::string fn = de.path().filename().string(), p = de.path().string();
764                if (fn.rfind("slot-", 0) != 0) continue;
765                const bool is_bin = fn.size() > 9 && fn.compare(fn.size() - 4, 4, ".bin") == 0;
766                const bool is_meta = fn.size() > 10 && fn.compare(fn.size() - 5, 5, ".meta") == 0;
767                const bool is_pads = fn.size() > 10 && fn.compare(fn.size() - 5, 5, ".pads") == 0;
768                if (is_pads || (fn.size() > 10 && fn.compare(fn.size() - 5, 5, ".pics") == 0)) {   // (kept with its .bin; one without goes)
769                    if (!fs::exists(p.substr(0, p.size() - 5) + ".bin", ec)) std::filesystem::remove(de.path(), ec);
770                    continue;
771                }
772                if (!is_bin && !is_meta) {   // a .tmp an interrupted write left
773                    std::filesystem::remove(de.path(), ec);
774                    continue;
775                }
776                if (!is_meta) continue;      // a .bin is judged by its .meta
777                const std::string bin = p.substr(0, p.size() - 5) + ".bin";
778                Found fd{bin, {}, 0, {}, fs::last_write_time(de.path(), ec), {}};
779                const uint64_t have = fs::exists(bin, ec) ? (uint64_t) fs::file_size(bin, ec) : 0;
780                if (meta_read(p, fd.toks, fd.bytes, fd.cks) && have == fd.bytes && fd.bytes > 0 && slot_age_days(p) <= slot_days &&
781                    ps::read(picf_of(bin), (int64_t) fd.toks.size(), fd.pics))
782                    found.push_back(std::move(fd));
783                else {
784                    ++refused;
785                    std::filesystem::remove(p, ec);
786                    std::filesystem::remove(bin, ec);
787                    std::filesystem::remove(picf_of(bin), ec);
788                }
789            }
790            for (const auto& de : std::filesystem::directory_iterator(slot_dir, ec)) {   // a .bin without its .meta
791                const std::string p = de.path().string(), fn = de.path().filename().string();
792                if (fn.rfind("slot-", 0) == 0 && fn.size() > 9 && fn.compare(fn.size() - 4, 4, ".bin") == 0 &&
793                    !fs::exists(meta_of(p), ec))
794                    std::filesystem::remove(de.path(), ec);
795            }
796            std::sort(found.begin(), found.end(), [](const Found& a, const Found& b) { return a.t < b.t; });
797            uint64_t total = 0;
798            for (auto& fd : found) {
799                total += fd.bytes;
800                std::vector<int32_t> keys = ps::keyed(fd.toks, fd.pics);
801                slots.push_back({std::move(fd.toks), fd.bin, fd.bytes, ++slot_clock, nullptr, std::move(fd.cks), pads_read(fd.bin),
802                                 std::move(fd.pics), std::move(keys)});
803            }
804            std::string msg = "folder " + slot_dir.string() + ": " + std::to_string(slots.size()) +
805                              " conversation(s) kept from earlier runs (" + gb(total) + ")";
806            if (refused) msg += ", " + std::to_string(refused) + " not this model's or incomplete - removed";
807            note(msg);
808            slot_trim("");   // (the folder over STRATA_DS4_SLOT_GB: the least recently used conversation goes first)
809        }
810    }
811    if (slot_max > 0) {
812#if !defined(_WIN32)
813        // (the server ends the engine with QUIT and waits for it; a SIGTERM to the whole process group - systemd
814        // stopping a service, a supervisor killing the server's group - must not end it mid-write, and a server that
815        // is already gone must not end it with SIGPIPE when it writes its last lines)
816        std::signal(SIGTERM, SIG_IGN);
817        std::signal(SIGINT, SIG_IGN);
818        std::signal(SIGPIPE, SIG_IGN);
819#endif
820    }
821    while (in.next(line)) {
822        if (line == "QUIT") break;
823        const bool geni = line.rfind("GENI ", 0) == 0;
824        if (!geni && line.rfind("GEN ", 0) != 0) {
825            std::printf("ERR unsupported command '%s' (GEN, GENI, STOP and QUIT)\n", line.substr(0, line.find(' ')).c_str());
826            std::fflush(stdout);
827            continue;
828        }
829        in.stop.store(false);
830        Req r;
831        if (!parse_gen(line, r, geni)) {
832            std::printf("ERR expected: GEN <max_new> [keys] <id,id,...> or GENI <max_new> [keys] <file> <id,id,...>\n");
833            std::fflush(stdout);
834            continue;
835        }
836        const double t0 = now_ms();
837        std::vector<Pic> pics;
838        {
839            std::string e;
840            if (geni && img_tok < 0) e = "this engine has no vision tower, so it cannot read pictures";
841            else if (geni && read_pics(r.file, pics, e))
842                for (const Pic& q : pics)
843                    if (q.start < 0 || (size_t) q.start >= r.ids.size() || r.ids[(size_t) q.start] != img_tok)
844                        e = "a picture's span does not start at an image token of the prompt";
845            if (!e.empty()) {
846                std::printf("ERR %s\n", e.c_str());
847                std::printf("DONE 0 %zu 0.0 0.0 cancel 0 0 0 0 0\n", r.ids.size());
848                std::fflush(stdout);
849                continue;
850            }
851        }
852        {   // each picture's span (the run of image tokens at its start): the matchers key it by the picture's hash
853            std::vector<ps::Span> sp = spans_of(pics);
854            ps::measure(r.ids, img_tok, sp);
855            for (size_t k = 0; k < pics.size(); ++k) pics[k].len = (size_t) sp[k].len;
856        }
857        if (!reuse) {   // (STRATA_DS4_REUSE=0, for A/Bs and tests: every request is a fresh read of its whole prompt)
858            m.reset();
859            held.clear();
860        }
861        state_pads = scr_pads;
862        // SCR with kept conversations (Bonsai's way): the cached prompt this one reuses most - the model's, or a kept
863        // one's - is the one it is planned against; a kept one that reuses more (by more than a junction's worth) is
864        // brought back whole first, and the conversation in the model set aside
865        // (pictures: the prompt and every conversation as the matchers see them, a span keyed by its picture's hash)
866        std::vector<int> pkey;
867        {
868            const std::vector<int32_t> k = ps::keyed(r.ids, spans_of(pics));
869            pkey.assign(k.begin(), k.end());
870        }
871        if (scr && reuse && slot_max > 0 && r.ids.size() > 2) {
872            const auto reuse_of = [&](const std::vector<int32_t>& t, const std::vector<int64_t>& pads) -> int64_t {
873                std::vector<int> phys;
874                (void) strata::core::scr_carry(pkey, t, pads, 201, phys);
875                size_t c0 = 0;
876                while (c0 < t.size() && c0 < phys.size() && t[c0] == phys[c0]) ++c0;
877                int64_t n = (int64_t) c0;
878                for (const auto& run : strata::ds4::scr_plan(t, phys).runs)
879                    if (run.at >= (int64_t) c0) n += run.n;
880                return n;
881            };
882            const int64_t live = m.tokens().empty() ? 0 : reuse_of(ps::keyed(m.tokens(), spans_of(held)), scr_pads);
883            // (the prompt keeps under half of the model's conversation: another conversation - that one is set aside
884            //  before SCR moves a little of it; an edit of the same one keeps most of it and is not)
885            const bool other = 2 * live < (int64_t) m.tokens().size();
886            if (other) slot_put(" (SCR: another conversation)");
887            size_t best = SIZE_MAX;
888            int64_t best_n = live + 512;
889            for (size_t i = 0; i < slots.size(); ++i) {
890                const int64_t n = reuse_of(slots[i].keys, slots[i].pads);
891                if (n > best_n) best = i, best_n = n;
892            }
893            if (best != SIZE_MAX) {
894                const double tb = now_ms();
895                const std::vector<int32_t> want = slots[best].keys;
896                if (!other && !m.tokens().empty()) slot_put(" (SCR: a kept conversation reuses more of the prompt)");
897                size_t k = SIZE_MAX;   // (slot_put may have dropped or moved slots)
898                for (size_t i = 0; i < slots.size() && k == SIZE_MAX; ++i)
899                    if (slots[i].keys == want) k = i;
900                std::string e;
901                if (k != SIZE_MAX && slot_bring(k, e)) {
902                    scr_pads = slots[k].pads;
903                    state_pads = scr_pads;
904                    held = pics_of_spans(slots[k].pics, SIZE_MAX);
905                    slots[k].used = ++slot_clock;
906                    char msg[256];
907                    std::snprintf(msg, sizeof msg, "SCR: took back a %zu-token conversation (%.1f s): it reuses %lld of the "
908                                  "prompt, the model's %lld", want.size(), (now_ms() - tb) / 1000.0, (long long) best_n,
909                                  (long long) live);
910                    note(msg);
911                } else {
912                    if (k != SIZE_MAX) {
913                        note("SCR: taking a conversation back failed (" + e + ") - reading its prompt again");
914                        slot_drop(k);
915                    }
916                    m.reset();
917                    held.clear();
918                    scr_pads.clear();
919                    state_pads.clear();
920                }
921            }
922        }
923        // the state's tokens as the matchers see them: the same tokens with another picture (or none) do not share the
924        // state from that picture's span on
925        std::vector<int32_t> skey = ps::keyed(m.tokens(), spans_of(held));
926        if (scr) {   // (the pads an earlier splice read, put back: the prompt's pictures move with them)
927            std::vector<int> physical;
928            scr_pads = strata::core::scr_carry(pkey, skey, scr_pads, 201, physical);
929            if (!scr_pads.empty()) {
930                const std::vector<int64_t> map = ps::insert_map(r.ids.size(), scr_pads);
931                for (Pic& q : pics) q.start = map[(size_t) q.start];
932                pkey.swap(physical);
933                r.ids.assign(pkey.begin(), pkey.end());
934                for (int& id : r.ids) if (id < 0) id = img_tok;
935            }
936        }
937        const auto& st = m.tokens();
938        const size_t n_state = st.size();
939        size_t c = 0;
940        while (c < n_state && c < r.ids.size() && skey[c] == pkey[c]) ++c;
941        size_t from = 0;
942        bool took = false, continued = false;   // (continued: the conversation goes on - its anchor stays)
943        // the conversation continues, reused in place - a conversation has to be in the model first: a fresh engine
944        // (the start of a run, so every restart) holds 0 tokens, and every prompt "continues" that to token 0; taken
945        // as a continuation, the take below would never run for the folder's conversations, the case they are for
946        bool spliced = false;
947        int64_t scr_cached = 0, scr_moved = 0;   // (an SCR request's prompt: kept exactly, moved; the rest is read)
948        if (scr && reuse && c < n_state && r.ids.size() > 2) {
949            // (score=N: the scored tokens are read fresh after the plan's prompt, never moved)
950            const size_t sn = std::min<size_t>((size_t) r.score, r.ids.size() - 2);
951            const std::vector<int> head(pkey.begin(), pkey.end() - (long) sn);
952            auto plan = strata::ds4::scr_plan(skey, head);
953            static const int64_t band = std::max<int64_t>(2, env_num("DS4_SCR_BAND", 128)) / 2 * 2;
954            static const int64_t exact_max = (int64_t) env_num("DS4_SCR_EXACT_MAX", 8192);
955            // (no moved run, but a long shared start the model holds no checkpoint near - another agent behind the same
956            //  system prompt: the start is kept and joined like a run's end, with a junction band)
957            const bool start_only = plan.empty() && plan.n_prefix >= std::max<int64_t>(256, band + 2) &&
958                                    plan.n_prefix - std::max<int64_t>(0, m.restorable(plan.n_prefix)) > exact_max;
959            if (start_only) plan.restore = plan.n_prefix / 2 * 2;
960            // (pictures: a run moves a picture's span whole or leaves it to be read, never half of it)
961            if (!pics.empty()) ps::whole_spans(plan, spans_of(pics), band, std::max<int64_t>(256, band + 2));
962            if (!plan.empty() || start_only) {
963                auto pkeys = strata::core::scr_padded(head, plan, 201);   // (as the matchers see it)
964                pkeys.insert(pkeys.end(), pkey.end() - (long) sn, pkey.end());
965                std::vector<int> physical = pkeys;
966                for (int& id : physical) if (id < 0) id = img_tok;
967                bool fits = (int64_t) physical.size() + std::max(0LL, r.max_new) <= m.max_context() &&
968                    std::all_of(physical.begin(), physical.end(), [&](int id) { return id >= 0 && id < m.vocab(); });
969                std::vector<strata::ds4::Model::ScrMove> moves;
970                for (const auto& run : plan.runs) {
971                    fits = fits && run.n >= std::max<int64_t>(256, band + 2) && run.old_start >= 0 && run.at >= plan.restore &&
972                        run.old_start + run.n <= (int64_t) st.size() &&
973                        run.at + run.n + 2 <= (int64_t) physical.size() &&
974                        ((run.at | run.old_start | run.n) & 1) == 0 &&
975                        std::equal(skey.begin() + run.old_start, skey.begin() + run.old_start + run.n,
976                                   pkeys.begin() + run.at);
977                    moves.push_back({run.old_start, run.at, run.n});
978                }
979                // the pictures where the padded prompt has them; the ones this splice reads (not in the exact prefix
980                // it goes back to, nor in a run's kept part) are encoded and in place before anything moves
981                std::vector<Pic> pphys = pics;
982                {
983                    const std::vector<int64_t> map = ps::insert_map(r.ids.size(), strata::core::scr_pad_positions(plan));
984                    for (Pic& q : pphys) q.start = map[(size_t) q.start];
985                }
986                const std::vector<std::pair<int64_t, int64_t>> pranges = ranges_of(spans_of(pphys));
987                if (fits && !pphys.empty()) {
988                    const int64_t p0 = plan.restore, rs = m.restorable(p0);
989                    const int64_t lo = rs >= 0 && p0 - rs <= exact_max ? rs : std::max<int64_t>(0, p0 - band);
990                    std::vector<strata::ds4::Image> imgs;
991                    std::string ie;
992                    for (const Pic& q : pphys) {
993                        const int64_t s = q.start, e = q.start + (int64_t) q.len;
994                        bool kept = e <= lo;
995                        for (const auto& run : plan.runs) kept = kept || (s >= run.at && e <= run.at + run.n - band);
996                        if (kept) continue;
997                        std::shared_ptr<const std::vector<uint16_t>> rows = spans.get(m, q, ie);
998                        if (!rows || rows->size() / (size_t) m.dim() != q.len) {
999                            fits = false;   // (the read below meets it again, and says why)
1000                            break;
1001                        }
1002                        imgs.push_back({q.start, rows});
1003                    }
1004                    if (fits) m.set_images(std::move(imgs));
1005                }
1006                std::string se;
1007                const double tr0 = now_ms();
1008                int moved = !fits ? 0 : moves.empty() ? 1 : m.scr_relocate(moves, se);
1009                std::string seg_ms = "relocate " + std::to_string((int) (now_ms() - tr0)) + " ms";
1010                if (moved == 0) m.set_images({});
1011                // (an SCR jump takes the tokens back without their rows: the pictures among them are marked again)
1012                const auto jump = [&](int64_t at) {
1013                    const bool ok = m.scr_jump(physical, at, se, plan.n_prefix);
1014                    if (ok && !pranges.empty()) m.mark_images(pranges);
1015                    return ok;
1016                };
1017                if (moved != 0) {
1018                    bool good = moved > 0;
1019                    // the exact prefix: back to a checkpoint at or before its end when one is near enough (read on
1020                    // exactly from there), else a junction band at its end
1021                    const int64_t p0 = plan.restore, rs = m.restorable(p0);
1022                    int64_t cur = 0;
1023                    if (good && rs >= 0 && p0 - rs <= exact_max && m.restore(p0)) cur = m.pos();
1024                    else if (good) {
1025                        cur = p0 >= band ? p0 - band : 0;
1026                        good = jump(cur);
1027                    }
1028                    scr_cached = cur;
1029                    seg_ms += ", prefix " + std::to_string((int) (now_ms() - tr0)) + " ms";
1030                    auto read_to = [&](int64_t to) {   // (in the engine's feed units)
1031                        const double ts = now_ms();
1032                        const int64_t c0 = cur;
1033                        while (good && cur < to) {
1034                            int64_t n = std::min<int64_t>(m.feed_unit(), to - cur);
1035                            if (r.pin > cur && r.pin < cur + n) n = r.pin - cur;   // (pin=N: its checkpoint on the way)
1036                            good = m.feed(physical.data() + cur, (int) n, 0, se);
1037                            cur += n;
1038                            if (good && cur == r.pin) m.checkpoint(3);
1039                        }
1040                        if (to > c0) seg_ms += ", read " + std::to_string(to - c0) + " in " + std::to_string((int) (now_ms() - ts)) + " ms";
1041                    };
1042                    for (const auto& run : plan.runs) {
1043                        read_to(run.at);
1044                        const int64_t at = run.at + run.n - band;
1045                        if (good) good = jump(at);
1046                        cur = at;
1047                        scr_moved += run.n - band;
1048                    }
1049                    if (!good) {
1050                        m.reset();
1051                        m.set_images({});
1052                        held.clear();
1053                        scr_pads.clear();
1054                        std::printf("ERR SCR splice failed: %s\n", se.c_str());
1055                        std::printf("DONE 0 %zu 0.0 0.0 cancel 0 0 0 0 0\n", r.ids.size());
1056                        std::fflush(stdout);
1057                        continue;
1058                    }
1059                    auto inserted = strata::core::scr_pad_positions(plan);
1060                    // Existing pad positions shift when new pads are inserted before them.
1061                    for (auto& at : scr_pads) {
1062                        const int64_t original = at;
1063                        for (const auto& run : plan.runs) if (run.new_start <= original) at += run.pad;
1064                    }
1065                    scr_pads.insert(scr_pads.end(), inserted.begin(), inserted.end());
1066                    std::sort(scr_pads.begin(), scr_pads.end());
1067                    r.ids.swap(physical);
1068                    pkey.swap(pkeys);
1069                    for (size_t k = 0; k < pics.size(); ++k) pics[k].start = pphys[k].start;
1070                    from = (size_t) m.pos();
1071                    spliced = true;
1072                    std::fprintf(stderr, "ds4 SCR: %s; prompt %zu = cached %lld + scr %lld + prefilled %lld; %zu junctions (band %lld); %s\n",
1073                                 plan.str().c_str(), r.ids.size(), (long long) scr_cached, (long long) scr_moved,
1074                                 (long long) r.ids.size() - scr_cached - scr_moved, plan.runs.size(), (long long) band, seg_ms.c_str());
1075                }
1076            }
1077        }
1078        if (spliced) {
1079            continued = false;
1080        } else if ((n_state > 0 || slot_max <= 0) && c == n_state && n_state < r.ids.size()) {   // (slots off: as before)
1081            from = n_state;
1082            continued = true;
1083        }
1084        else {
1085            // CONVERSATION SLOTS: this prompt does not continue the conversation in the model - that one is set aside
1086            // first (another one takes the model, and its state is lost otherwise), then the kept conversation this
1087            // prompt does continue is taken back - if it goes further back than the checkpoints the state itself holds
1088            slot_put("");
1089            const int64_t limit = (int64_t) std::min(c, r.ids.size() - 1);
1090            const int64_t rs = m.restorable(limit);
1091            bool whole = false;
1092            // (SCR: the kept conversations were weighed above, by what SCR reuses)
1093            const size_t back = !scr ? slot_take(pkey, rs > 0 ? (size_t) rs : 0, whole) : 0;
1094            if (back > 0) {
1095                from = back;
1096                took = true;
1097                continued = whole;
1098            } else if (rs >= 0 && m.restore(limit))
1099                from = (size_t) m.pos();
1100            else m.reset();
1101        }
1102        if (!took && from == 0) held.clear();   // (a slot taken back brings its pictures: slot_take)
1103        if ((int64_t) r.ids.size() + std::max(0LL, r.max_new) > m.max_context()) {
1104            std::printf("ERR the prompt (%zu tokens) and max_new %lld are more than the context %lld\n", r.ids.size(),
1105                        r.max_new, (long long) m.max_context());
1106            std::fflush(stdout);
1107            continue;
1108        }
1109        std::string err;
1110        bool ok = true;
1111        // the pictures whose spans the prompt reads (the rest the state holds): encoded (or the cache's), checked
1112        if (!pics.empty()) {
1113            std::vector<strata::ds4::Image> imgs;
1114            const double te = now_ms();
1115            int encoded = 0;
1116            for (Pic& q : pics) {
1117                for (const Pic& x : held)
1118                    if (x.start == q.start && x.hash == q.hash) q.len = x.len;
1119                if (q.len > 0 && (size_t) q.start + q.len <= from) continue;
1120                std::shared_ptr<const std::vector<uint16_t>> rows = spans.get(m, q, err);
1121                if (!rows) {
1122                    ok = false;
1123                    break;
1124                }
1125                ++encoded;
1126                q.len = rows->size() / (size_t) m.dim();
1127                bool fits = (size_t) q.start + q.len <= r.ids.size() - 1;
1128                for (size_t i = 0; fits && i < q.len; ++i) fits = r.ids[(size_t) q.start + i] == img_tok;
1129                if (!fits) {
1130                    err = "a picture's span (" + std::to_string(q.len) + " tokens at " + std::to_string(q.start) +
1131                          ") is not a run of image tokens in the prompt";
1132                    ok = false;
1133                    break;
1134                }
1135                imgs.push_back({q.start, rows});
1136            }
1137            if (ok) {
1138                m.set_images(std::move(imgs));
1139                std::fprintf(stderr, "maya ds4 serve: %zu pictures, %d read (%.0f ms)\n", pics.size(), encoded,
1140                             now_ms() - te);
1141            }
1142            for (Pic& q : pics) q.rgb = {};   // (only the start, hash and span stay)
1143        }
1144        // the prompt in windows (PP <read> <total> <ms> <tok/s> <reuse> every 64 tokens), a checkpoint before its last
1145        // token and one after it: the next turn re-renders this one, and shares its start up to one of them
1146        const size_t n_score = std::min<size_t>((size_t) r.score, r.ids.size() > from + 2 ? r.ids.size() - from - 2 : 0);
1147        const size_t total = r.ids.size() - n_score;   // (score=N: the last N read after, in windows of 8)
1148        size_t done = from, next_pp = from + 64;
1149        m.set_progress([&](int64_t d) {   // (a run of chunks: each one through every layer)
1150            const double ms = now_ms() - t0;
1151            std::printf("PP %zu %zu %.1f %.1f %zu\n", done + (size_t) d, r.ids.size(), ms,
1152                        ms > 0 ? 1000.0 * (double) (done + (size_t) d - from) / ms : 0.0, from);
1153            std::fflush(stdout);
1154        });
1155        // (DS4_LAST_WINDOW=1: the last token in a window of its own after the checkpoint, as before - for A/B runs)
1156        static const bool last_window = std::getenv("DS4_LAST_WINDOW") != nullptr;
1157        // (pin=N: the read stops at N for a checkpoint of the shared start; only when this read crosses N, and N leaves
1158        //  the prompt's last token to the usual end)
1159        const size_t pin_at = (r.pin >= 256 && (size_t) r.pin + 1 < total) ? (size_t) r.pin : 0;
1160        // a STOP while the prompt is read ends it there (the engine's run of chunks at a layer or chunk, windows between
1161        // feeds) and goes back to the state before this prompt - kept here first, in checkpoint 1, which the prompt's
1162        // own end overwrites as before - so the next request still shares the conversation up to it
1163        if (from > 0 && from < total) m.checkpoint(1);
1164        m.set_cancel([&in] { return in.stop.load(); });
1165        bool stopped = false;
1166        while (ok && done < total) {
1167            if (in.stop.load()) {
1168                stopped = true;
1169                break;
1170            }
1171            size_t n = std::min<size_t>((size_t) m.feed_unit(), total - done);
1172            if (pin_at > done && pin_at < done + n) n = pin_at - done;
1173            // (the prompt's end: the last token in the same run, the checkpoint before it kept on the way)
1174            const bool fin = done + n == total;
1175            if (fin && last_window) {
1176                ok = (n < 2 || m.feed(r.ids.data() + done, (int) n - 1, 0, err));
1177                if (ok) m.checkpoint(1);
1178                ok = ok && m.feed(r.ids.data() + done + n - 1, 1, 1, err);
1179            } else
1180                ok = fin ? m.feed_mark(r.ids.data() + done, (int) n, 1, 1, err)
1181                         : m.feed(r.ids.data() + done, (int) n, 0, err);
1182            done += n;
1183            if (ok && pin_at != 0 && done == pin_at) m.checkpoint(3);
1184            if (ok && (done >= next_pp || done == total)) {
1185                const double ms = now_ms() - t0;
1186                std::printf("PP %zu %zu %.1f %.1f %zu\n", done, r.ids.size(), ms,
1187                            ms > 0 ? 1000.0 * (double) (done - from) / ms : 0.0, from);
1188                std::fflush(stdout);
1189                next_pp = done + 64;
1190            }
1191        }
1192        m.set_cancel(nullptr);
1193        m.set_images({});
1194        if (stopped || (!ok && m.cancelled())) {
1195            const bool back = from > 0 && m.restore((int64_t) from) && (size_t) m.pos() == from;
1196            if (!back) {
1197                m.reset();
1198                held.clear();
1199            }
1200            std::fprintf(stderr, "ds4 serve: stopped while reading the prompt of %zu tokens, after %.0f ms%s\n",
1201                         total, now_ms() - t0, back ? "; the conversation before it is kept" : "");
1202            std::printf("DONE 0 %zu %.1f 0.0 cancel 0 0 %zu 0 0\n", r.ids.size(), now_ms() - t0, back ? from : (size_t) 0);
1203            std::fflush(stdout);
1204            continue;
1205        }
1206        if (!ok) {
1207            std::fprintf(stderr, "ds4: %s\n", err.c_str());
1208            std::printf("ERR %s\n", err.c_str());
1209            std::printf("DONE 0 %zu 0.0 0.0 cancel 0 0 0 0 0\n", r.ids.size());
1210            std::fflush(stdout);
1211            m.reset();
1212            held.clear();
1213            continue;
1214        }
1215        if (n_score > 0) {   // score=N: teacher-forced rows for the prompt's last N tokens (quant_quality.py's format)
1216            std::FILE* so = r.score_out.empty() ? nullptr : std::fopen(r.score_out.c_str(), "wb");
1217            const int V = m.vocab(), eos_id = eos.empty() ? -1 : eos[0];
1218            std::vector<float> lg;
1219            std::vector<int> order((size_t) V);
1220            for (size_t a = total; ok && a + 1 < r.ids.size();) {
1221                const int T = (int) std::min<size_t>(8, r.ids.size() - 1 - a);
1222                ok = m.feed(r.ids.data() + a, T, T, err) && m.logits(lg) && lg.size() >= (size_t) T * (size_t) V;
1223                for (int t = 0; ok && so != nullptr && t < T; ++t) {
1224                    const float* row = lg.data() + (size_t) t * (size_t) V;
1225                    float mx = row[0];
1226                    for (int v = 1; v < V; ++v) mx = std::max(mx, row[v]);
1227                    double z = 0.0;
1228                    for (int v = 0; v < V; ++v) z += std::exp((double) (row[v] - mx));
1229                    const double lz = std::log(z) + (double) mx;
1230                    std::iota(order.begin(), order.end(), 0);
1231                    std::partial_sort(order.begin(), order.begin() + 64, order.end(),
1232                                      [&](int x, int y) { return row[x] > row[y] || (row[x] == row[y] && x < y); });
1233                    const int tgt = r.ids[a + (size_t) t + 1];
1234                    const double lt = (double) row[tgt] - lz, la = (double) row[order[0]] - lz;
1235                    const double le = eos_id >= 0 && eos_id < V ? (double) row[eos_id] - lz : -1e30;
1236                    const double lt_ne = tgt == eos_id ? lt : std::log(std::max(1e-300, std::exp(lt) / std::max(1e-300, 1.0 - std::exp(le))));
1237                    std::fprintf(so, "%zu\t%d\t%.6f\t%d\t%.6f\t%d\t%.6f\t%.6f", a + (size_t) t, tgt, lt, order[0], la,
1238                                 order[0] == tgt ? 1 : 0, le, lt_ne);
1239                    for (int q = 0; q < 64; ++q) std::fprintf(so, "\t%d:%.6f", order[(size_t) q], (double) row[order[(size_t) q]] - lz);
1240                    std::fprintf(so, "\n");
1241                }
1242                a += (size_t) T;
1243            }
1244            if (so != nullptr) std::fclose(so);
1245            ok = ok && m.feed(r.ids.data() + r.ids.size() - 1, 1, 1, err);
1246            if (!ok) {
1247                std::printf("ERR %s\n", err.c_str());
1248                std::printf("DONE 0 %zu 0.0 0.0 cancel 0 0 0 0 0\n", r.ids.size());
1249                std::fflush(stdout);
1250                m.reset();
1251                held.clear();
1252                continue;
1253            }
1254        }
1255        if (const char* path = std::getenv("STRATA_DUMP_FIRST_LOGITS"); path != nullptr && *path != '\0') {
1256            static unsigned long long dump_counter = 0;
1257            std::vector<float> logits;
1258            const std::string name = std::string(path) + "." + std::to_string(dump_counter++);
1259            std::FILE* f = std::fopen(name.c_str(), "wb");
1260            if (f != nullptr) {
1261                if (m.logits(logits)) std::fwrite(logits.data(), sizeof(float), logits.size(), f);
1262                std::fclose(f);
1263            }
1264        }
1265        held = std::move(pics);
1266        m.checkpoint(0);
1267        if (!continued && slot_max > 0) m.pin();   // (a new run of prompts: where it may be rendered again from)
1268        const double t1 = now_ms();
1269        long long produced = 0;
1270        const char* finish = "length";
1271        const long long limit = r.max_new > 0 ? r.max_new : m.max_context() - (long long) r.ids.size();
1272        long long d_off = 0, d_acc = 0;
1273        bool cool = false;
1274        int tok = m.sample(r.temperature, r.top_p, r.top_k, r.min_p, r.seed, counter++);
1275        std::vector<int> got;
1276        // STAT for the Monitor every 8 tokens and at the end, over this answer so far: the GLM engine's keys (speed, the
1277        // VRAM hit, promotions a token) and DeepSeek's own - experts a token on the CPU lane, MB a token the storage
1278        // read (Linux), the n-gram memory's (Engram) read time a token, the drafts' acceptance
1279        const strata::ds4::Stats s_dec = m.stats();
1280        const long long io_dec = io_read_bytes();
1281        auto stat_line = [&]() {
1282            const strata::ds4::Stats& s = m.stats();
1283            const double ms = now_ms() - t1;
1284            const double fed = (double) std::max<int64_t>(1, s.tokens - s_dec.tokens);
1285            const double ex = (double) (s.experts - s_dec.experts), cx = (double) (s.cpu_experts - s_dec.cpu_experts);
1286            std::string out = "STAT";
1287            char b[160];
1288            std::snprintf(b, sizeof b, " tok_s=%.2f ms_tok=%.2f vram_hit=%.4f cpu=%.3f ram=%.3f promo=%.3f engram_ms=%.3f",
1289                          ms > 0 ? 1000.0 * (double) produced / ms : 0.0, produced > 0 ? ms / (double) produced : 0.0,
1290                          ex > 0 ? 1.0 - cx / ex : 1.0, cx / fed, (double) (s.ram_experts - s_dec.ram_experts) / fed,
1291                          (double) (s.swaps - s_dec.swaps) / fed, (s.engram_ms - s_dec.engram_ms) / fed);
1292            out += b;
1293            const long long io = io_read_bytes();
1294            if (io >= 0 && io_dec >= 0) {
1295                std::snprintf(b, sizeof b, " disk_mb=%.3f", (double) (io - io_dec) / 1e6 / fed);
1296                out += b;
1297            }
1298            if (d_off > 0) {
1299                std::snprintf(b, sizeof b, " drafts=%.3f", (double) d_acc / (double) d_off);
1300                out += b;
1301            }
1302            if (s.skipped > s_dec.skipped) {   // (STRATA_DS4_DISK_SKIP_W: experts left out a token)
1303                std::snprintf(b, sizeof b, " skipped=%.3f", (double) (s.skipped - s_dec.skipped) / fed);
1304                out += b;
1305            }
1306            std::printf("%s\n", out.c_str());
1307        };
1308        for (;;) {
1309            if (in.stop.load()) {
1310                finish = "cancel";
1311                break;
1312            }
1313            std::printf("T %d\n", tok);
1314            ++produced;
1315            if (produced % 8 == 0) stat_line();
1316            std::fflush(stdout);
1317            bool end = false;
1318            for (int e : eos) end = end || tok == e;
1319            if (end) {
1320                finish = "stop";
1321                break;
1322            }
1323            if (produced >= limit || m.pos() >= m.max_context()) break;
1324            if (got.empty()) {   // the next round: the drafts (if any) and the token after them
1325                const int room = (int) std::min<long long>(limit - produced, m.max_context() - m.pos());
1326                int off = 0, acc = 0;
1327                // a round whose drafts were all below the confidence floor: the next one does without the drafter
1328                // (a request's spec / dspark_conf keys over the engine's: the speed calibration measures both ways)
1329                const bool try_spec = (r.spec < 0 ? spec : r.spec != 0) && !cool;
1330                if (!round(m, tok, room, try_spec, r.conf >= 0 ? r.conf : conf_min, r.temperature, r.top_p, r.top_k,
1331                           r.min_p, r.seed, counter, got,
1332                           off, acc, err, r.cum, r.spec != 0)) {
1333                    std::fprintf(stderr, "ds4: %s\n", err.c_str());
1334                    finish = "cancel";
1335                    break;
1336                }
1337                d_off += off;
1338                d_acc += acc;
1339                cool = try_spec && off == 0;
1340                std::reverse(got.begin(), got.end());
1341            }
1342            tok = got.back();
1343            got.pop_back();
1344        }
1345        // (a stop within accepted drafts leaves the state past it: the next prompt shares less with it, and goes back to
1346        //  the checkpoint at this prompt's end)
1347        stat_line();
1348        const double t2 = now_ms();
1349        // (reused: the tokens not read again - an SCR request's exact prefix and moved runs, not its resume point; with
1350        //  SCR on, the fields up to the prompt tokens read, then cached / scr / prefilled)
1351        const size_t reused = spliced ? (size_t) (scr_cached + scr_moved) : from;
1352        if (scr)
1353            std::printf("DONE %lld %zu %.1f %.1f %s %lld %lld %zu 0 0 0 0 0 %zu 0 cached=%zu scr=%lld prefilled=%zu\n", produced,
1354                        r.ids.size(), t1 - t0, t2 - t1, finish, d_acc, d_off, reused, r.ids.size() - reused,
1355                        spliced ? (size_t) scr_cached : from, (long long) scr_moved, r.ids.size() - reused);
1356        else
1357            std::printf("DONE %lld %zu %.1f %.1f %s %lld %lld %zu 0 0\n", produced, r.ids.size(), t1 - t0, t2 - t1, finish,
1358                        d_acc, d_off, from);
1359        std::fflush(stdout);
1360        const auto& s = m.stats();
1361        std::fprintf(stderr,
1362                     "maya ds4 serve: prompt %zu tokens = %zu reused + %zu read in %.0f ms (%.1f tok/s), %lld generated "
1363                     "in %.0f ms (%.2f tok/s); CPU lane %.1f%% of the experts\n",
1364                     r.ids.size(), reused, r.ids.size() - reused, t1 - t0,
1365                     t1 > t0 ? 1000.0 * (double) (r.ids.size() - reused) / (t1 - t0) : 0.0, produced, t2 - t1,
1366                     t2 > t1 ? 1000.0 * (double) produced / (t2 - t1) : 0.0,
1367                     s.experts ? 100.0 * (double) s.cpu_experts / (double) s.experts : 0.0);
1368        if (scr)   // (the server's request line, and /metrics: Bonsai's cached / scr / prefilled split)
1369            std::fprintf(stderr, "maya ds4 serve: SCR cached %zu scr %lld prefilled %zu of %zu\n", spliced ? (size_t) scr_cached : from,
1370                         (long long) scr_moved, r.ids.size() - reused, r.ids.size());
1371        if (d_off > 0) std::fprintf(stderr, "maya ds4 serve: drafts %lld of %lld kept; %s\n", d_acc, d_off,
1372                                    per_position(s_dec, s).c_str());
1373        m.save_profile();
1374    }
1375    // the engine ends (QUIT or the end of its input): the conversation in the model is set aside, and every one in
1376    // RAM is written to the folder, so the next run reads on from them
1377    if (slot_max > 0) {
1378        state_pads = scr_pads;
1379        slot_put(" as the engine ended");
1380        size_t written = 0;
1381        while (true) {   // (a write can take the folder's least recently used conversation away: the list is asked again)
1382            size_t i = SIZE_MAX;
1383            for (size_t k = 0; k < slots.size(); ++k)
1384                if (slots[k].data) {
1385                    i = k;
1386                    break;
1387                }
1388            if (i == SIZE_MAX) break;
1389            if (slot_write_file(slots[i])) ++written;
1390            else slot_drop(i);   // (its state could not be written: there is nothing more to do at the engine's end)
1391        }
1392        if (written > 0) {
1393            int ram = 0, disk = 0;
1394            slot_count(ram, disk);
1395            char msg[256];
1396            std::snprintf(msg, sizeof msg, "wrote %zu conversation(s) to %s; %d there in all", written,
1397                          slot_dir.string().c_str(), disk);
1398            note(msg);
1399        }
1400    }
1401    m.save_profile();
1402    return 0;
1403}
1404
1405
1406// ---- Strata addition: teacher-forced scoring (the quality gate) -------------------------------------------------
1407// --score IDS.json --score-out RUN.tsv: every segment of a tools/quant_quality.py ids file (name + ids) is read through
1408// the model from a fresh state; per position the log-probability of the text's next token and the 64 most likely
1409// tokens go out in the STRATA_LOGPOS row format that `quant_quality.py compare` reads (natural logs, full-vocabulary
1410// log-softmax in double).  RUN.tsv.seg.json lists each segment's first line and size.
1411struct ScoreSeg {
1412    std::string name;
1413    std::vector<int> ids;
1414};
1415
1416bool read_score_ids(const std::string& path, std::vector<ScoreSeg>& segs, std::string& err) {
1417    std::FILE* f = std::fopen(path.c_str(), "rb");
1418    if (f == nullptr) {
1419        err = path + ": cannot open";
1420        return false;
1421    }
1422    std::string s;
1423    char buf[1 << 16];
1424    size_t k;
1425    while ((k = std::fread(buf, 1, sizeof buf, f)) > 0) s.append(buf, k);
1426    std::fclose(f);
1427    size_t p = 0;
1428    for (;;) {
1429        const size_t n0 = s.find("\"name\"", p);
1430        if (n0 == std::string::npos) break;
1431        const size_t q0 = s.find('"', s.find(':', n0) + 1);
1432        const size_t q1 = s.find('"', q0 + 1);
1433        const size_t i0 = s.find("\"ids\"", q1);
1434        if (q0 == std::string::npos || q1 == std::string::npos || i0 == std::string::npos) break;
1435        const size_t b0 = s.find('[', i0), b1 = s.find(']', b0);
1436        if (b0 == std::string::npos || b1 == std::string::npos) break;
1437        ScoreSeg g;
1438        g.name = s.substr(q0 + 1, q1 - q0 - 1);
1439        g.ids = parse_ids(s.substr(b0 + 1, b1 - b0 - 1));
1440        segs.push_back(std::move(g));
1441        p = b1;
1442    }
1443    if (segs.empty()) {
1444        err = path + ": no segments (expected quant_quality.py's ids file)";
1445        return false;
1446    }
1447    return true;
1448}
1449
1450int score(strata::ds4::Model& m, const std::string& ids_path, const std::string& out_path, int window, int eos) {
1451    std::vector<ScoreSeg> segs;
1452    std::string err;
1453    if (!read_score_ids(ids_path, segs, err)) {
1454        std::fprintf(stderr, "strata-dsv41: %s\n", err.c_str());
1455        return 1;
1456    }
1457    // DS4_SCORE_PREFIX=N (a test of the long-prompt layer skip): the segments are joined into one stream, its first N
1458    // tokens are read as one prompt (logits of the last row only: the path a long prompt takes, where the skip applies)
1459    // and only the positions after them are scored, in windows
1460    const long long prefix_n = std::getenv("DS4_SCORE_PREFIX") ? std::atoll(std::getenv("DS4_SCORE_PREFIX")) : 0;
1461    // (DS4_SCORE_PREFIX_EACH=1: each segment its own prompt of N tokens, then its own scored positions)
1462    const bool prefix_each = std::getenv("DS4_SCORE_PREFIX_EACH") != nullptr && std::atoi(std::getenv("DS4_SCORE_PREFIX_EACH")) != 0;
1463    if (prefix_n > 0 && segs.size() > 1 && !prefix_each) {
1464        ScoreSeg all;
1465        all.name = "concat";
1466        for (const ScoreSeg& sg : segs) all.ids.insert(all.ids.end(), sg.ids.begin(), sg.ids.end());
1467        segs.assign(1, all);
1468    }
1469    std::FILE* out = std::fopen(out_path.c_str(), "wb");
1470    std::FILE* sj = std::fopen((out_path + ".seg.json").c_str(), "wb");
1471    if (out == nullptr || sj == nullptr) {
1472        std::fprintf(stderr, "strata-dsv41: cannot write %s\n", out_path.c_str());
1473        return 1;
1474    }
1475    std::fprintf(sj, "{\"segments\": [");
1476    const int V = m.vocab();
1477    long long line = 0;
1478    std::vector<float> lg;
1479    std::vector<int> order;
1480    const double t0 = now_ms();
1481    for (size_t si = 0; si < segs.size(); ++si) {
1482        const std::vector<int>& ids = segs[si].ids;
1483        m.reset();
1484        const long long first = line;
1485        double sum_nll = 0.0;
1486        long long top1 = 0, cnt = 0;
1487        size_t a0 = 0;
1488        if (prefix_n > 0 && (size_t) prefix_n + 1 < ids.size()) {
1489            a0 = (size_t) prefix_n;
1490            if (!m.feed(ids.data(), (int) a0, 1, err)) {
1491                std::fprintf(stderr, "strata-dsv41: %s\n", err.c_str());
1492                return 1;
1493            }
1494        }
1495        for (size_t a = a0; a + 1 < ids.size();) {
1496            const int T = (int) std::min<size_t>((size_t) window, ids.size() - 1 - a);   // (positions a .. a+T-1 are scored)
1497            if (!m.feed(ids.data() + a, T, T, err) || !m.logits(lg) || lg.size() < (size_t) T * (size_t) V) {
1498                std::fprintf(stderr, "strata-dsv41: %s\n", err.empty() ? "no logits" : err.c_str());
1499                return 1;
1500            }
1501            for (int t = 0; t < T; ++t) {
1502                const float* r = lg.data() + (size_t) t * (size_t) V;
1503                float mx = r[0];
1504                for (int v = 1; v < V; ++v) mx = std::max(mx, r[v]);
1505                double z = 0.0;
1506                for (int v = 0; v < V; ++v) z += std::exp((double) (r[v] - mx));
1507                const double lz = std::log(z) + (double) mx;
1508                order.resize((size_t) V);
1509                std::iota(order.begin(), order.end(), 0);
1510                std::partial_sort(order.begin(), order.begin() + 64, order.end(), [&](int x, int y) {
1511                    return r[x] > r[y] || (r[x] == r[y] && x < y);
1512                });
1513                const int tgt = ids[a + (size_t) t + 1];
1514                const double lt = (double) r[tgt] - lz;
1515                const double la = (double) r[order[0]] - lz;
1516                const double le = eos >= 0 && eos < V ? (double) r[eos] - lz : -1e30;
1517                // logp(target) with the end token left out of the distribution, as the engine's row has it
1518                const double lt_ne = tgt == eos ? lt : std::log(std::max(1e-300, std::exp(lt) / std::max(1e-300, 1.0 - std::exp(le))));
1519                std::fprintf(out, "%zu\t%d\t%.6f\t%d\t%.6f\t%d\t%.6f\t%.6f", a + (size_t) t, tgt, lt, order[0], la,
1520                             order[0] == tgt ? 1 : 0, le, lt_ne);
1521                for (int j = 0; j < 64; ++j) std::fprintf(out, "\t%d:%.6f", order[(size_t) j], (double) r[order[(size_t) j]] - lz);
1522                std::fprintf(out, "\n");
1523                ++line;
1524                ++cnt;
1525                top1 += order[0] == tgt;
1526                sum_nll -= lt;
1527            }
1528            a += (size_t) T;
1529        }
1530        std::fprintf(sj, "%s{\"name\": \"%s\", \"first_line\": %lld, \"end_line\": %lld, \"n\": %lld, \"ppl\": %.6f, \"top1\": %.6f}", si ? ", " : "",
1531                     segs[si].name.c_str(), first, first + cnt, cnt, std::exp(sum_nll / (double) std::max(1LL, cnt)),
1532                     (double) top1 / (double) std::max(1LL, cnt));
1533        std::fprintf(stderr, "score %s: %lld positions, ppl %.4f, top-1 %.4f (%.0f s)\n", segs[si].name.c_str(), cnt,
1534                     std::exp(sum_nll / (double) std::max(1LL, cnt)), (double) top1 / (double) std::max(1LL, cnt),
1535                     (now_ms() - t0) / 1000.0);
1536        std::fflush(out);
1537    }
1538    std::fprintf(sj, "]}\n");
1539    std::fclose(sj);
1540    std::fclose(out);
1541    return 0;
1542}
1543// ---- Strata H100 addition: profile run -------------------------------------------------------------------------
1544// --profile-run IDS.json: every segment is fed through the model from a fresh state (no logits); the engine's expert
1545// profile (--expert-profile FILE, counts a layer and expert) and DS4_TRACE collect the routing.  The profile is saved
1546// every 10 segments.  --window sets the chunk (a chunked prompt path above 16).
1547int profile_run(strata::ds4::Model& m, const std::string& ids_path, int window) {
1548    std::vector<ScoreSeg> segs;
1549    std::string err;
1550    if (!read_score_ids(ids_path, segs, err)) {
1551        std::fprintf(stderr, "strata-dsv41: %s\n", err.c_str());
1552        return 1;
1553    }
1554    const double t0 = now_ms();
1555    long long tot = 0;
1556    for (size_t si = 0; si < segs.size(); ++si) {
1557        const std::vector<int>& ids = segs[si].ids;
1558        m.reset();
1559        for (size_t a = 0; a < ids.size();) {
1560            const int T = (int) std::min<size_t>((size_t) window, ids.size() - a);
1561            if (!m.feed(ids.data() + a, T, 0, err)) {
1562                std::fprintf(stderr, "strata-dsv41: %s\n", err.c_str());
1563                return 1;
1564            }
1565            a += (size_t) T;
1566        }
1567        tot += (long long) ids.size();
1568        std::fprintf(stderr, "profile-run %zu/%zu %s: %zu tokens, %lld in all, %.0f s, %.1f tok/s\n", si + 1, segs.size(),
1569                     segs[si].name.c_str(), ids.size(), tot, (now_ms() - t0) / 1000.0, 1000.0 * (double) tot / (now_ms() - t0));
1570        if ((si + 1) % 10 == 0) m.save_profile();
1571    }
1572    m.save_profile();
1573    return 0;
1574}
1575// ---- Strata H100 addition: DSpark acceptance log ---------------------------------------------------------------
1576// --spec-eval IDS.json --n N: each segment is a prompt: fed from reset, then N greedy tokens decoded with the drafter, every
1577// draft verified (--dspark-conf 0); DS4_ROUND_LOG=file gets a line a round (segment name, drafts, accepted, confidences).
1578int spec_eval(strata::ds4::Model& m, const std::string& ids_path, int n, int window, float conf_min, bool spec) {
1579    std::vector<ScoreSeg> segs;
1580    std::string err;
1581    if (!read_score_ids(ids_path, segs, err)) {
1582        std::fprintf(stderr, "strata-dsv41: %s\n", err.c_str());
1583        return 1;
1584    }
1585    if (const char* f = std::getenv("DS4_ROUND_LOG")) g_round_log = std::fopen(f, "wb");
1586    const double t0 = now_ms();
1587    for (size_t si = 0; si < segs.size(); ++si) {
1588        const std::vector<int>& ids = segs[si].ids;
1589        g_round_tag = segs[si].name;
1590        m.reset();
1591        for (size_t a = 0; a < ids.size();) {
1592            const int T = (int) std::min<size_t>((size_t) window, ids.size() - a);
1593            const bool last = a + (size_t) T == ids.size();
1594            if (!m.feed(ids.data() + a, T, last ? 1 : 0, err)) {
1595                std::fprintf(stderr, "strata-dsv41: %s\n", err.c_str());
1596                return 1;
1597            }
1598            a += (size_t) T;
1599        }
1600        unsigned long long counter = 0;
1601        int tok = m.sample(0.0f, 1.0f, 1, 0.0f, 1, counter++);
1602        std::vector<int> got;
1603        int emitted = 1;
1604        long long rounds = 0, acc_all = 0;
1605        bool stop = false;
1606        while (emitted < n && !stop) {
1607            int off = 0, acc = 0;
1608            if (!round(m, tok, n - emitted, spec, conf_min, 0.0f, 1.0f, 1, 0.0f, 1, counter, got, off, acc, err)) {
1609                std::fprintf(stderr, "strata-dsv41: %s\n", err.c_str());
1610                return 1;
1611            }
1612            ++rounds;
1613            acc_all += acc;
1614            for (int t : got) {
1615                ++emitted;
1616                if (t == 1) stop = true;
1617            }
1618            tok = got.back();
1619        }
1620        std::fprintf(stderr, "spec-eval %zu/%zu %s: prompt %zu, %d tokens, %lld rounds, %.2f tokens a round, accepted %lld (%.0f s)\n", si + 1,
1621                     segs.size(), segs[si].name.c_str(), ids.size(), emitted, rounds, (double) (emitted - 1) / (double) std::max(1LL, rounds),
1622                     acc_all, (now_ms() - t0) / 1000.0);
1623        if (g_round_log != nullptr) std::fflush(g_round_log);
1624    }
1625    return 0;
1626}
1627}  // namespace
1628
1629#ifndef DS4_BUILD_ID
1630#define DS4_BUILD_ID "unknown"
1631#endif
1632
1633int main(int argc, char** argv) {
1634    strata::ds4::os::fine_timer();
1635    strata::ds4::Options o;
1636    std::string ids_s, dump, eos = "1";
1637    int n = 0, window = 0;   // (0: the model's feed unit - a whole prompt on the chunked path; 16 for the scoring runs)
1638    bool spec = true;
1639    float temp = 0.0f;   // the CLI's sampling (0: greedy)
1640    unsigned long long cli_seed = 1;
1641    bool serve_mode = false;
1642    bool pack_info_mode = false;
1643    std::string images, enc_rgb, enc_out;
1644    std::string score_ids, score_out, prof_ids, spec_ids;
1645    int enc_w = 0, enc_h = 0;
1646    for (int i = 1; i < argc; ++i) {
1647        const std::string a = argv[i];
1648        auto val = [&](const char* what) -> std::string {
1649            if (i + 1 >= argc) {
1650                std::fprintf(stderr, "%s needs a value\n", what);
1651                std::exit(2);
1652            }
1653            return argv[++i];
1654        };
1655        if (a == "--pack") o.pack = val("--pack");
1656        else if (a == "--gpus") {
1657            for (int g : parse_ids(val("--gpus"))) o.gpus.push_back(g);
1658        } else if (a == "--max-context") o.max_context = std::atoll(val("--max-context").c_str());
1659        else if (a == "--reserve-mib") o.reserve_mib = std::atoll(val("--reserve-mib").c_str());
1660        else if (a == "--vram-experts") o.vram_experts = std::atof(val("--vram-experts").c_str());
1661        else if (a == "--cpu-threads") o.cpu_threads = std::atoi(val("--cpu-threads").c_str());
1662        else if (a == "--expert-profile") o.profile = val("--expert-profile");
1663        else if (a == "--ssd-cache") o.ssd_cache_gb = std::atof(val("--ssd-cache").c_str());
1664        else if (a == "--ssd-policy") {
1665            const std::string v = val("--ssd-policy");
1666            o.ssd_policy = v == "lfu" ? 1 : v == "lfulru" ? 2 : 0;
1667        }
1668        else if (a == "--eos") eos = val("--eos");
1669        else if (a == "--no-expert-cache") o.expert_cache = false;
1670        else if (a == "--dspark") {
1671            const std::string v = val("--dspark");
1672            spec = v != "off";
1673            o.dspark = v != "none";   // none: not even loaded
1674            o.dspark_auto = v == "auto";
1675        } else if (a == "--dspark-conf") o.dspark_conf = (float) std::atof(val("--dspark-conf").c_str());
1676        else if (a == "--experts") {
1677            const std::string v = val("--experts");
1678            o.experts = v == "auto" ? -1 : std::max(1, std::atoi(v.c_str()));
1679        }
1680        else if (a == "--dspark-block") o.dspark_block = std::max(0, std::atoi(val("--dspark-block").c_str()));
1681        else if (a == "--tp") o.tp = std::max(1, std::atoi(val("--tp").c_str()));
1682        else if (a == "--prefill-chunk") o.prefill_chunk = std::max(0, std::atoi(val("--prefill-chunk").c_str()));
1683        else if (a == "--threads") o.threads = val("--threads") != "off";
1684        else if (a == "--vision") o.vision = val("--vision") != "off";
1685        else if (a == "--mmap-experts") {
1686            const std::string v = val("--mmap-experts");
1687            o.mmap_experts = v == "on" ? 1 : v == "off" ? 0 : -1;
1688        } else if (a == "--images") images = val("--images");
1689        else if (a == "--encode-image") enc_rgb = val("--encode-image");
1690        else if (a == "--dump-image") enc_out = val("--dump-image");
1691        else if (a == "--size") {
1692            const std::string v = val("--size");
1693            enc_w = std::atoi(v.c_str());
1694            enc_h = v.find('x') != std::string::npos ? std::atoi(v.c_str() + v.find('x') + 1) : 0;
1695        }
1696        else if (a == "--temperature") temp = (float) std::atof(val("--temperature").c_str());
1697        else if (a == "--seed") cli_seed = std::strtoull(val("--seed").c_str(), nullptr, 10);
1698        else if (a == "--verbose" || a == "-v") {
1699            o.verbose = true;
1700            std::fprintf(stderr, "ds4: build %s (%s)\n", DS4_BUILD_ID, STRATA_VERSION);
1701        } else if (a == "--version") {
1702            std::printf("strata-dsv41 %s build %s\n", STRATA_VERSION, DS4_BUILD_ID);
1703            return 0;
1704        }
1705        else if (a == "--ids") ids_s = val("--ids");
1706        else if (a == "--n") n = std::atoi(val("--n").c_str());
1707        else if (a == "--window") window = std::max(1, std::atoi(val("--window").c_str()));   // (> 16: the chunked prompt path)
1708        else if (a == "--dump-logits") dump = val("--dump-logits");
1709        else if (a == "--score") score_ids = val("--score");
1710        else if (a == "--score-out") score_out = val("--score-out");
1711        else if (a == "--profile-run") prof_ids = val("--profile-run");
1712        else if (a == "--spec-eval") spec_ids = val("--spec-eval");
1713        else if (a == "--serve") serve_mode = true;
1714        else if (a == "--pack-info") pack_info_mode = true;
1715        else if (a == "--layer-split") (void) val("--layer-split");   // the server's (this engine balances its own split)
1716        else if (a == "--help" || a == "-h") {
1717            usage();
1718            return 0;
1719        } else {
1720            std::fprintf(stderr, "unknown option %s\n", a.c_str());
1721            usage();
1722            return 2;
1723        }
1724    }
1725    if (pack_info_mode) {   // the pack's description only: no device, no weights, no lock
1726        if (o.pack.empty()) {
1727            usage();
1728            return 2;
1729        }
1730        return strata::ds4::pack_info(o.pack, stdout);
1731    }
1732    if (o.pack.empty() || (!serve_mode && ids_s.empty() && enc_rgb.empty() && score_ids.empty() && prof_ids.empty() && spec_ids.empty())) {
1733        usage();
1734        return 2;
1735    }
1736    if (o.profile.empty()) o.profile = o.pack + "/expert-profile.bin";   // "none": no profile
1737    if (o.profile == "none") o.profile.clear();
1738    o.vision_only = !enc_rgb.empty();
1739    SuffixDrafter suffix;
1740    if (const char* e = std::getenv("DS4_SUFFIX_DRAFT"); e != nullptr && std::atoi(e) > 0) {
1741        // a window of more than DS4_ASYNC_T (8) rows takes the host-routed path: no Cache-Prior, no lookahead - 9 rows cost 8 tokens'
1742        // time here, and their routing is not decode's
1743        const char* at = std::getenv("DS4_ASYNC_T");
1744        suffix.kmax = std::max(1, std::min(std::atoi(e), (at != nullptr ? std::atoi(at) : 8) - 1));
1745        if (const char* f = std::getenv("DS4_SUFFIX_MIN")) suffix.nmin = suffix.floor_ = std::max(2, std::atoi(f));
1746        g_suffix = &suffix;
1747        o.spec_buffers = true;
1748    }
1749    strata::ds4::Model m;
1750    std::string err;
1751    if (!m.load(o, err)) {
1752        std::fprintf(stderr, "maya-ds4: %s\n", err.c_str());
1753        return 1;
1754    }
1755    if (!o.vision_only) std::fprintf(stderr, "%s", m.describe().c_str());
1756    if (const char* idle = std::getenv("DS4_TEST_IDLE_MS")) std::this_thread::sleep_for(std::chrono::milliseconds(std::atoi(idle)));   // (tests: a person typing)
1757    if (serve_mode) {
1758        // QUIT: everything that outlives the engine is written by now (the profile after every request, the kept
1759        // conversations as serve ends), so it exits at once.  A normal exit flushed every stdio stream, stdin too,
1760        // whose lock the stdin reader thread holds while it waits for a line: the engine hung after QUIT until its
1761        // input closed.
1762        const int rc = serve(m, eos, spec, o.dspark_conf, o.pack);
1763        std::fflush(stdout);
1764        std::fflush(stderr);
1765        std::_Exit(rc);
1766    }
1767    const int window_given = window;
1768    if (window == 0) window = 16;   // (the scoring / profiling runs; the plain run below takes the model's feed unit)
1769    if (!prof_ids.empty()) return profile_run(m, prof_ids, window);
1770    if (!spec_ids.empty()) return spec_eval(m, spec_ids, n, window, o.dspark_conf, spec);
1771    if (!score_ids.empty()) return score(m, score_ids, score_out.empty() ? score_ids + ".tsv" : score_out, window, std::atoi(eos.c_str()));
1772
1773    if (!enc_rgb.empty()) {   // the vision tower alone: a picture's span rows (BF16 [rows][dim]) into --dump-image
1774        std::vector<uint8_t> px((size_t) std::max(0, enc_w) * std::max(0, enc_h) * 3);
1775        std::FILE* f = std::fopen(enc_rgb.c_str(), "rb");
1776        const bool got = f != nullptr && !px.empty() && std::fread(px.data(), 1, px.size(), f) == px.size();
1777        if (f != nullptr) std::fclose(f);
1778        if (!got) {
1779            std::fprintf(stderr, "maya-ds4: %s: expected %d x %d RGB bytes (--size WxH)\n", enc_rgb.c_str(), enc_w, enc_h);
1780            return 1;
1781        }
1782        std::vector<uint16_t> span;
1783        for (int k = 0; k < 2; ++k) {   // (the second: warm)
1784            const double te = now_ms();
1785            if (!m.encode_image(px.data(), enc_w, enc_h, span, err)) {
1786                std::fprintf(stderr, "maya-ds4: %s\n", err.c_str());
1787                return 1;
1788            }
1789            std::fprintf(stderr, "vision: %d x %d pixels -> a span of %zu rows in %.0f ms\n", enc_w, enc_h,
1790                         span.size() / (size_t) m.dim(), now_ms() - te);
1791        }
1792        std::FILE* o2 = enc_out.empty() ? nullptr : std::fopen(enc_out.c_str(), "wb");
1793        if (o2 != nullptr) {
1794            std::fwrite(span.data(), 2, span.size(), o2);
1795            std::fclose(o2);
1796        }
1797        return 0;
1798    }
1799    if (!ids_s.empty() && ids_s[0] == '@') {   // --ids @file: the ids in a file (a command line is 32 KB on Windows)
1800        std::ifstream idf(ids_s.substr(1));
1801        std::stringstream ss;
1802        ss << idf.rdbuf();
1803        ids_s = ss.str();
1804    }
1805    const std::vector<int> ids = parse_ids(ids_s);
1806    if (!images.empty()) {   // --images: a GENI file's pictures, for the prompt's spans
1807        std::vector<Pic> pics;
1808        if (!read_pics(images, pics, err)) {
1809            std::fprintf(stderr, "maya-ds4: %s\n", err.c_str());
1810            return 1;
1811        }
1812        std::vector<strata::ds4::Image> imgs;
1813        for (const Pic& q : pics) {
1814            auto rows = std::make_shared<std::vector<uint16_t>>();
1815            const double te = now_ms();
1816            if (!m.encode_image(q.rgb.data(), q.width, q.height, *rows, err)) {
1817                std::fprintf(stderr, "maya-ds4: %s\n", err.c_str());
1818                return 1;
1819            }
1820            std::fprintf(stderr, "picture at %lld: %d x %d pixels, %zu tokens, %.0f ms\n", (long long) q.start, q.width,
1821                         q.height, rows->size() / (size_t) m.dim(), now_ms() - te);
1822            imgs.push_back({q.start, rows});
1823        }
1824        m.set_images(std::move(imgs));
1825    }
1826    std::FILE* df = dump.empty() ? nullptr : std::fopen(dump.c_str(), "wb");
1827    std::vector<float> lg;
1828    if (window_given == 0) window = df != nullptr ? 16 : std::max(16, std::min(m.feed_unit(), 1 << 30));
1829    const double t0 = now_ms();
1830    for (size_t a = 0; a < ids.size();) {
1831        const int T = (int) std::min<size_t>((size_t) window, ids.size() - a);
1832        const bool last = a + (size_t) T == ids.size();
1833        const double tf0 = now_ms();
1834        if (!m.feed(ids.data() + a, T, df != nullptr ? T : (last ? 1 : 0), err)) {
1835            std::fprintf(stderr, "maya-ds4: %s\n", err.c_str());
1836            return 1;
1837        }
1838        if (std::getenv("DS4_FEEDLOG") != nullptr)   // each feed's time: the incremental turn (--window W: a long prefix, then a short one)
1839            std::fprintf(stderr, "feed at %zu: %d tokens in %.0f ms (%.1f tok/s)\n", a, T, now_ms() - tf0, 1000.0 * T / (now_ms() - tf0));
1840        if (df != nullptr && m.logits(lg)) std::fwrite(lg.data(), 4, lg.size(), df);
1841        a += (size_t) T;
1842    }
1843    m.set_images({});
1844    const double t1 = now_ms();
1845    std::fprintf(stderr, "prompt: %zu tokens in %.0f ms (%.2f tok/s, windows of %d)\n", ids.size(), t1 - t0,
1846                 1000.0 * (double) ids.size() / (t1 - t0), window);
1847    const strata::ds4::Stats s0 = m.stats();
1848    const char* tier_path = std::getenv("DS4_TIERDUMP");
1849    if (tier_path != nullptr) m.tier_dump(std::string(tier_path) + ".pre");
1850    if (s0.eg_rows > 0)
1851        std::fprintf(stderr, "prompt's Engram rows: %lld, %.1f%% without a read (repeats and the row cache), %lld read\n",
1852                     (long long) s0.eg_rows, 100.0 * (double) s0.eg_hits / (double) s0.eg_rows, (long long) s0.eg_reads);
1853    const long long io0 = io_read_bytes();
1854    std::vector<int> out;
1855    std::vector<double> tok_ms;   // (DS4_TOKLOG: each token's time since the one before - the latency ledger)
1856    double t_prev = t1;
1857    unsigned long long counter = 0;
1858    long long d_off = 0, d_acc = 0, rounds = 0;
1859    bool cool = false;
1860    if (n > 0) {
1861        int tok = m.sample(temp, 1.0f, temp > 0 ? 64 : 1, 0.0f, cli_seed, counter++);
1862        std::vector<int> got;
1863        for (;;) {
1864            out.push_back(tok);
1865            {
1866                const double tn = now_ms();
1867                tok_ms.push_back(tn - t_prev);
1868                t_prev = tn;
1869            }
1870            std::printf("%d,", tok);
1871            std::fflush(stdout);
1872            if ((tok == 1 && std::getenv("DS4_NO_EOS") == nullptr) || (int) out.size() >= n) break;   // (DS4_NO_EOS: decode n tokens whatever)
1873            if (got.empty()) {
1874                int off = 0, acc = 0;
1875                const bool try_spec = spec && !cool;
1876                if (!round(m, tok, n - (int) out.size(), try_spec, o.dspark_conf, temp, 1.0f, temp > 0 ? 64 : 1, 0.0f,
1877                           cli_seed, counter, got, off, acc, err)) {
1878                    std::fprintf(stderr, "maya-ds4: %s\n", err.c_str());
1879                    return 1;
1880                }
1881                d_off += off;
1882                d_acc += acc;
1883                ++rounds;
1884                cool = try_spec && off == 0;
1885                std::reverse(got.begin(), got.end());
1886            }
1887            tok = got.back();
1888            got.pop_back();
1889        }
1890        std::printf("\n");
1891        if (df != nullptr && m.logits(lg)) std::fwrite(lg.data(), 4, lg.size(), df);
1892    }
1893    if (spec && rounds > 0) {
1894        const auto& s1 = m.stats();
1895        const double nv = (double) std::max<int64_t>(1, s1.drafts_rounds - s0.drafts_rounds);
1896        std::fprintf(stderr, "dspark: %lld rounds, %lld drafts offered, %lld accepted (%.2f tokens a round); drafting "
1897                             "%.2f ms a round, verifying %.1f ms in all (%lld windows)\n",
1898                     rounds, d_off, d_acc, (double) out.size() / (double) rounds, (s1.draft_ms - s0.draft_ms) / nv,
1899                     s1.verify_ms - s0.verify_ms, (long long) (s1.drafts_offered > 0 ? 0 : 0));
1900        std::fprintf(stderr, "dspark %s\n", per_position(s0, s1).c_str());
1901    }
1902    if (g_suffix != nullptr && rounds > 0)
1903        std::fprintf(stderr, "suffix: %lld rounds, %lld verified %lld drafts, %lld accepted (%.0f%%), %lld looked up without "
1904                             "a match; %.2f tokens a round\n",
1905                     rounds, g_suffix->rounds, g_suffix->offered, g_suffix->accepted,
1906                     100.0 * (double) g_suffix->accepted / (double) std::max(1LL, g_suffix->offered), g_suffix->tried,
1907                     (double) out.size() / (double) rounds);
1908    if (std::getenv("DS4_TOKLOG") != nullptr && tok_ms.size() > 8) {   // the decode's tokens after the first (which carries the prompt's tail)
1909        std::vector<double> v(tok_ms.begin() + 1, tok_ms.end());
1910        std::sort(v.begin(), v.end());
1911        std::fprintf(stderr, "token latency ms: p50 %.0f p95 %.0f p99 %.0f max %.0f mean %.0f (%zu tokens)\n", v[v.size() / 2],
1912                     v[(size_t) ((double) v.size() * 0.95)], v[(size_t) ((double) v.size() * 0.99)], v.back(),
1913                     std::accumulate(v.begin(), v.end(), 0.0) / (double) v.size(), v.size());
1914        const size_t n20 = std::min<size_t>(21, tok_ms.size());   // (tokens 2..21: what a long read leaves behind)
1915        if (tok_ms.size() > 30)
1916            std::fprintf(stderr, "token latency ms: first20 mean %.0f, after mean %.0f\n",
1917                         std::accumulate(tok_ms.begin() + 1, tok_ms.begin() + (long) n20, 0.0) / (double) (n20 - 1),
1918                         std::accumulate(tok_ms.begin() + (long) n20, tok_ms.end(), 0.0) / (double) (tok_ms.size() - n20));
1919    }
1920    const double t2 = now_ms();
1921    const auto& s = m.stats();
1922    const double nt = std::max<double>(1.0, (double) (s.tokens - s0.tokens));
1923    if (s.aux_experts > s0.aux_experts)
1924        std::fprintf(stderr, "decode: the expert GPU computed %.1f experts a token; %lld moved onto it\n",
1925                     (double) (s.aux_experts - s0.aux_experts) / nt, (long long) (s.aux_swaps - s0.aux_swaps));
1926    std::fprintf(stderr, "decode: %zu tokens in %.0f ms (%.2f tok/s); CPU lane: %lld of %lld experts; the cache moved %lld "
1927                         "(%lld in all)\n", out.size(), t2 - t1,
1928                 out.size() > 1 ? 1000.0 * (double) (out.size() - 1) / (t2 - t1) : 0.0,
1929                 (long long) (s.cpu_experts - s0.cpu_experts), (long long) (s.experts - s0.experts),
1930                 (long long) (s.swaps - s0.swaps), (long long) s.swaps);
1931    std::fprintf(stderr, "decode per token: layers %.2f ms (of it: routing waits %.2f, CPU lane %.2f, the rest host launches), "
1932                         "head wait %.2f, Engram reads %.2f\n",
1933                 (s.layer_ms - s0.layer_ms) / nt, (s.gpu_wait_ms - s0.gpu_wait_ms) / nt, (s.cpu_ms - s0.cpu_ms) / nt,
1934                 (s.head_ms - s0.head_ms) / nt, (s.engram_ms - s0.engram_ms) / nt);
1935    if (s.eg_rows > s0.eg_rows) {   // the Engram rows: how many the row cache served, the reads' time behind the layers
1936        const double rows = (double) (s.eg_rows - s0.eg_rows);
1937        std::fprintf(stderr, "Engram per token: %.0f rows, %.1f%% without a read (the row cache holds %lld of %lld), "
1938                             "%.1f read, the reads %.2f ms from asking to the last one (left to wait: %.2f)\n",
1939                     rows / nt, 100.0 * (double) (s.eg_hits - s0.eg_hits) / rows, (long long) s.eg_cached,
1940                     (long long) s.eg_cache_cap, (double) (s.eg_reads - s0.eg_reads) / nt, (s.eg_io_ms - s0.eg_io_ms) / nt,
1941                     (s.engram_ms - s0.engram_ms) / nt);
1942    }
1943    const long long io1 = io_read_bytes();
1944    if (io0 >= 0 && io1 >= 0)
1945        std::fprintf(stderr, "decode reads from the disk: %.1f MB a token\n", (double) (io1 - io0) / 1e6 / nt);
1946    if (s.skipped > s0.skipped)   // STRATA_DS4_DISK_SKIP_W
1947        std::fprintf(stderr, "decode left out %.1f experts a token not in RAM (%.1f%% of the routed)\n",
1948                     (double) (s.skipped - s0.skipped) / nt,
1949                     100.0 * (double) (s.skipped - s0.skipped) / std::max<double>(1.0, (double) (s.experts - s0.experts)));
1950    if (s.store_slots_max > 0) {   // --ssd-cache
1951        const double h = (double) (s.store_hits - s0.store_hits), m = (double) (s.store_misses - s0.store_misses);
1952        std::fprintf(stderr,
1953                     "store: %.1f%% of the CPU lane's experts were in RAM (%.1f hits, %.1f misses a token); read %.1f MB a token "
1954                     "(demand and guesses), the CPU lane waited %.1f ms a token for them; %lld prefetched, %lld used, %lld given up "
1955                     "unused; slots %lld of %lld, %lld evictions, %lld failed reads; the GPU computed %.1f experts a token from the store "
1956                     "(%lld slots visible)\n",
1957                     100.0 * h / std::max(1.0, h + m), h / nt, m / nt, (double) (s.store_bytes - s0.store_bytes) / 1e6 / nt,
1958                     (s.store_wait_ms - s0.store_wait_ms) / nt, (long long) (s.store_prefetched - s0.store_prefetched),
1959                     (long long) (s.store_pf_used - s0.store_pf_used), (long long) (s.store_pf_wasted - s0.store_pf_wasted),
1960                     (long long) s.store_slots, (long long) s.store_slots_max, (long long) (s.store_evictions - s0.store_evictions),
1961                     (long long) (s.store_fails - s0.store_fails), (double) (s.store_zc - s0.store_zc) / nt,
1962                     (long long) s.store_zc_visible);
1963    }
1964    if (s.ahead_picks > s0.ahead_picks) {   // lookahead
1965        const double p = (double) (s.ahead_picks - s0.ahead_picks), c = (double) (s.ahead_cold - s0.ahead_cold);
1966        std::fprintf(stderr, "lookahead: the guesses a layer before held %.1f%% of the picks (their top k %.1f%%, two layers "
1967                             "before %.1f%%); file-read picks asked for early %.1f%% (%lld of %lld); %.1f experts asked "
1968                             "for early a token\n",
1969                     100.0 * (double) (s.ahead_hit - s0.ahead_hit) / p, 100.0 * (double) (s.ahead_hit_k - s0.ahead_hit_k) / p,
1970                     100.0 * (double) (s.ahead_hit2 - s0.ahead_hit2) / p,
1971                     c > 0 ? 100.0 * (double) (s.ahead_cold_hit - s0.ahead_cold_hit) / c : 0.0,
1972                     (long long) (s.ahead_cold_hit - s0.ahead_cold_hit), (long long) (s.ahead_cold - s0.ahead_cold),
1973                     (double) (s.ahead_pf - s0.ahead_pf) / nt);
1974        std::string rk = "lookahead: picked by the guess's rank (1 ..):";
1975        for (int i = 0; i < 16; ++i) {
1976            const long long n = (long long) (s.ahead_rank_n[i] - s0.ahead_rank_n[i]);
1977            if (n <= 0) break;
1978            char b[24];
1979            std::snprintf(b, sizeof b, " %.0f%%", 100.0 * (double) (s.ahead_rank_hit[i] - s0.ahead_rank_hit[i]) / (double) n);
1980            rk += b;
1981        }
1982        std::fprintf(stderr, "%s\n", rk.c_str());
1983    }
1984    {
1985        double tt[6], all = 0;
1986        for (int i = 0; i < 6; ++i) all += tt[i] = (double) (s.tier[i] - s0.tier[i]);
1987        if (all > 0)
1988            std::fprintf(stderr, "decode picks a token by tier: VRAM %.1f, expert GPU %.1f, store GPU-visible %.1f, store ready %.1f, "
1989                                 "store in flight %.1f, no slot %.1f (%.1f in all)\n",
1990                         tt[0] / nt, tt[1] / nt, tt[2] / nt, tt[3] / nt, tt[4] / nt, tt[5] / nt, all / nt);
1991    }
1992    if (tier_path != nullptr) m.tier_dump(std::string(tier_path) + ".post");
1993    if (s.prof_tokens > s0.prof_tokens) {   // DS4_PROF
1994        const double pt = (double) (s.prof_tokens - s0.prof_tokens);
1995        double sum = 0;
1996        for (int i = 0; i < 6; ++i) sum += (s.prof_ms[i] - s0.prof_ms[i]) / pt;
1997        std::fprintf(stderr, "GPU per token (DS4_PROF): %.2f ms - between layers %.2f, attention %.2f, routing + shared "
1998                             "expert %.2f, experts gate/up %.2f, waiting for the CPU lane %.2f, down + post %.2f\n", sum,
1999                     (s.prof_ms[0] - s0.prof_ms[0]) / pt, (s.prof_ms[1] - s0.prof_ms[1]) / pt,
2000                     (s.prof_ms[2] - s0.prof_ms[2]) / pt, (s.prof_ms[3] - s0.prof_ms[3]) / pt,
2001                     (s.prof_ms[4] - s0.prof_ms[4]) / pt, (s.prof_ms[5] - s0.prof_ms[5]) / pt);
2002    }
2003    if (df != nullptr) std::fclose(df);
2004    m.save_profile();
2005    return 0;
2006}