okami.mom/strata

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

Niko1221split: DFlash2 as the draft source of the all-cards split engine (--draft dflash2 --draft-model PACK, FNX_DRAFT=dflash2). One drafter a lane on card 0 through df2_bridge (src/core/dflash2.cpp with bind() compiled out); the window graphs tap layers 5/15/25/35/45 on card 0 (df2_tap_gr), the prompt path taps each card's own rows into a host ring per lane; Session and BatchDecoder take the drafts after the commit. Greedy 6.4K and 27K answers identical to no drafter and to the draft layer (UD-Q4, 2 x A6000)c850b979b

main
58.2 KiB1166 linesraw
1// sFNX engine process for its front end (front/, Strata's line protocol): the engine half on stdin/stdout (token ids
2// only; the server tokenizes, applies the chat template, matches stop strings and parses tools).
3//
4//   sfnx --serve --native MODEL.gguf --mtp RT_DIR --draft-vocab VOCAB.bin [--max-context N] [--spec K] [--lookup K]
5//        [--conversation-cache-mib M] [--batch SLOTS]
6//
7// One request alone: GEN <max_new> [key=value ...] <ids>, answered with PP <done> <total> per prompt chunk, RESUME
8// <reused>, T <id> per token (speculative: the draft layer's chain and n-gram lookups, verified a window at a time),
9// DONE <generated> <prompt_tokens> <prompt_ms> <decode_ms> <finish> <drafts_accepted> <drafts_offered> <reused>, or ERR
10// (prompt_tokens: the prompt's tokens the lane holds, reused ones included; on a cancelled read as far as it got).
11// STOP any time ends it. BYIELD <slot> during its prompt read ends the read at the next chunk, the part read left in
12// that (free) slot for a BGEN there to go on from: YIELDED <slot> <read>, then DONE ... cancel. With --batch (INFO
13// batch_slots): BGEN <slot> <max_new> ... reads a prompt into a slot (each slot a lane) between the decoding slots'
14// windows, answers its first token as T + DONE, then BADM <slot> 1 if it goes on; decoding slots share windows (a row
15// each and their drafts: src/batch.hpp; one row each with FNX_BATCH_DRAFTS=0) and stream BT <slot> <id> ... BDONE <slot>
16// <produced> <finish> <ms> <drafts_accepted> <drafts_offered> <rounds> (the batched windows after its first token;
17// drafts 0 with FNX_BATCH_DRAFTS=0). BSTOP <slot> ends a decoding slot, or its prompt read at the next chunk (DONE ...
18// cancel, then BADM <slot> 0), and so does a STOP for the request decoding in a slot; BYIELD <slot> ends its prompt
19// read at the next chunk (YIELDED <slot> <read>). STOP, BSTOP and BYIELD act on the requests whose lines came before
20// them (sfnx_input.hpp).
21#include <algorithm>
22#include <atomic>
23#include <chrono>
24#include <cmath>
25#include <condition_variable>
26#include <cstdint>
27#include <cstdio>
28#include <cstdlib>
29#include <cstring>
30#include <deque>
31#include <functional>
32#include <iostream>
33#include <memory>
34#include <mutex>
35#include <optional>
36#include <random>
37#include <set>
38#include <sstream>
39#include <stdexcept>
40#include <string>
41#include <thread>
42#include <vector>
43
44#include "../src/batch.hpp"
45#include "../src/engine.hpp"
46#include "../src/env.hpp"
47#include "../src/session.hpp"
48#include "sfnx_input.hpp"
49
50namespace {
51
52using sfnx::Input;
53using sfnx::MAX_SLOTS;
54using sfnx::Running;
55const std::vector<int> EOS{248044, 248046};
56
57std::mutex out_mu;
58void say(const std::string& line) {
59    std::lock_guard<std::mutex> lk(out_mu);
60    std::fwrite(line.data(), 1, line.size(), stdout);
61    std::fputc('\n', stdout);
62    std::fflush(stdout);
63}
64
65struct Args {
66    std::string gguf, mtp_dir, draft_vocab;
67    std::string draft = "mtp", draft_model;   // --draft mtp|dflash2 (FNX_DRAFT), --draft-model PACK: DFlash2's runtime pack (tools/dflash2_pack.py)
68    int max_ctx = 262144, K = 6, lookup = 15, batch = 1;
69    long cache_mib = 0;   // checkpoints and parked conversations in host memory (0: none)
70    bool vision = false;  // GENI / BGENI: prompts with images (embeddings from sfnx-vision)
71};
72
73Args parse_args(int argc, char** argv) {
74    Args a;
75    bool serve = false;
76    for (int i = 1; i < argc; ++i) {
77        const std::string k = argv[i];
78        auto val = [&]() -> std::string {
79            if (i + 1 >= argc) throw std::runtime_error(k + " needs a value");
80            return argv[++i];
81        };
82        if (k == "--serve") serve = true;
83        else if (k == "--native") a.gguf = val();
84        else if (k == "--mtp") a.mtp_dir = val();
85        else if (k == "--draft-vocab") a.draft_vocab = val();
86        else if (k == "--draft") a.draft = val();
87        else if (k == "--draft-model") a.draft_model = val();
88        else if (k == "--max-context") a.max_ctx = std::stoi(val());
89        else if (k == "--spec") a.K = std::stoi(val());
90        else if (k == "--lookup") a.lookup = std::stoi(val());
91        else if (k == "--conversation-cache-mib") a.cache_mib = std::stol(val());
92        else if (k == "--batch") a.batch = std::stoi(val());
93        else if (k == "--layer-split") val();   // Strata's layer split; sFNX splits every layer across the cards
94        else if (k == "--rope-scale") {   // YaRN for a longer context: the engine reads it as FNX_ROPE_SCALE
95            const std::string s = val();
96            if (const char* e = std::getenv("FNX_ROPE_SCALE"); e && s != e)
97                throw std::runtime_error("--rope-scale " + s + " and FNX_ROPE_SCALE=" + e + " disagree");
98            ::setenv("FNX_ROPE_SCALE", s.c_str(), 1);
99        }
100        else if (k == "--vision") a.vision = true;
101        else throw std::runtime_error("unknown argument " + k);
102    }
103    if (!serve) throw std::runtime_error("sfnx runs as --serve");
104    if (const char* e = std::getenv("FNX_DRAFT"); e && e[0]) a.draft = e;
105    if (a.draft != "mtp" && a.draft != "dflash2") throw std::runtime_error("--draft takes mtp or dflash2");
106    if (a.draft == "dflash2") {
107        if (a.gguf.empty() || a.draft_model.empty() || (a.draft_vocab.empty() && a.mtp_dir.empty()))
108            throw std::runtime_error("--draft dflash2 needs --native, --draft-model PACK and --draft-vocab FILE (or --mtp DIR for DIR/draft_vocab.bin)");
109        if (a.draft_vocab.empty()) a.draft_vocab = a.mtp_dir + "/draft_vocab.bin";
110    } else if (a.gguf.empty() || a.mtp_dir.empty()) throw std::runtime_error("--native and --mtp are required");
111    if (a.batch < 1 || a.batch > MAX_SLOTS) throw std::runtime_error("--batch must be 1.." + std::to_string(MAX_SLOTS));
112    fnx::rope_scale();   // a bad scale stops here, not after the minute of loading (the context's limit needs the model)
113    return a;
114}
115
116// GEN <max_new> [key=value ...] <ids csv>, BGEN <slot> <max_new> ...; with images GENI / BGENI, the embeddings file
117// (sfnx-vision records) before the ids
118struct GenReq {
119    long seq = 0;   // its number among the request lines (Input)
120    int slot = -1;
121    int max_new = 0;
122    fnx::Sampling s;
123    fnx::ReadHints hints;
124    std::vector<int> ids;
125    std::vector<float> img_rows;   // every image's rows, in prompt order (hints.images point into it)
126    GenReq() = default;
127    GenReq(GenReq&&) = default;   // a vector's move keeps its buffer, so hints.images stay valid
128    GenReq& operator=(GenReq&&) = default;
129    GenReq(const GenReq&) = delete;   // a copy's hints.images would point into the original's img_rows
130    GenReq& operator=(const GenReq&) = delete;
131};
132
133uint64_t mix64(uint64_t x) {   // splitmix64's finalizer
134    x ^= x >> 30;
135    x *= 0xbf58476d1ce4e5b9ull;
136    x ^= x >> 27;
137    x *= 0x94d049bb133111ebull;
138    return x ^ (x >> 31);
139}
140
141uint64_t fnv1a(const void* p, size_t n, uint64_t h = 0xcbf29ce484222325ull) {
142    const unsigned char* b = (const unsigned char*) p;
143    for (size_t i = 0; i < n; ++i) h = (h ^ b[i]) * 0x100000001b3ull;
144    return h;
145}
146
147// the images of a GENI prompt: the file's records (int32 'SVE1', n, nx, ny, n_embd, then n x n_embd floats) in prompt
148// order, each on its run of n image-pad tokens. Each picture's cells get ids of their own from its key (the server's
149// hash of the picture, else its rows') and grid, so the conversation cache matches a picture by what it is
150void attach_images(GenReq& r, const std::string& path, const std::vector<uint64_t>& keys, int pad) {
151    struct Rec {
152        int n, nx, ny;
153        size_t off;
154    };
155    std::vector<Rec> recs;
156    std::FILE* f = std::fopen(path.c_str(), "rb");
157    if (!f) throw std::runtime_error("GENI: cannot open " + path);
158    for (;;) {
159        int32_t h[5];
160        const size_t got = std::fread(h, 4, 5, f);
161        if (got == 0) break;
162        if (got != 5 || h[0] != 0x31455653 || h[1] < 1 || h[2] < 1 || h[3] < 1 || (int64_t) h[2] * h[3] != h[1] || h[4] != fnx::N) {
163            std::fclose(f);
164            throw std::runtime_error("GENI: bad embeddings file (expected sfnx-vision records of width " + std::to_string(fnx::N) + ")");
165        }
166        const size_t off = r.img_rows.size(), cnt = (size_t) h[1] * fnx::N;
167        r.img_rows.resize(off + cnt);
168        if (std::fread(r.img_rows.data() + off, 4, cnt, f) != cnt) {
169            std::fclose(f);
170            throw std::runtime_error("GENI: short embeddings file");
171        }
172        recs.push_back({h[1], h[2], h[3], off});
173    }
174    std::fclose(f);
175    if (!keys.empty() && keys.size() != recs.size()) throw std::runtime_error("GENI: img_keys and the file's images differ in number");
176    size_t k = 0;
177    for (size_t i = 0; i < r.ids.size();) {
178        if (r.ids[i] != pad) {
179            ++i;
180            continue;
181        }
182        if (k >= recs.size()) throw std::runtime_error("GENI: the prompt has more images than the embeddings file");
183        const Rec& im = recs[k];
184        const int64_t grid[3] = {im.n, im.nx, im.ny};
185        uint64_t key = fnv1a(grid, sizeof grid);
186        key = keys.empty() ? fnv1a(r.img_rows.data() + im.off, (size_t) im.n * fnx::N * 4, key) : fnv1a(&keys[k], 8, key);
187        for (int j = 0; j < im.n; ++j) {
188            if (i + j >= r.ids.size() || r.ids[i + j] != pad)
189                throw std::runtime_error("GENI: image " + std::to_string(k + 1) + " has " + std::to_string(im.n) + " rows but fewer image-pad tokens");
190            r.ids[i + j] = fnx::Engine::IMAGE_TOK | (int) (mix64(key + (uint64_t) j) & (fnx::Engine::IMAGE_TOK - 1));
191        }
192        r.hints.images.push_back(fnx::Engine::Image{(int) i, im.n, im.nx, im.ny, nullptr});
193        i += im.n;
194        ++k;
195    }
196    if (k != recs.size()) throw std::runtime_error("GENI: the embeddings file has more images than the prompt");
197    if (r.ids.back() >= fnx::Engine::IMAGE_TOK) throw std::runtime_error("GENI: the prompt cannot end in an image");
198    for (size_t j = 0; j < recs.size(); ++j) r.hints.images[j].rows = r.img_rows.data() + recs[j].off;
199}
200
201// a request line's fields, each parsed whole (the field named in the error): an int, a float, a 64-bit hex key
202int field_int(const std::string& cmd, const std::string& key, const std::string& v) {
203    long long x = 0;
204    if (!fnx::parse_whole(v.c_str(), x) || x < INT32_MIN || x > INT32_MAX)
205        throw std::runtime_error(cmd + ": " + key + "=" + v + " is not a whole number");
206    return (int) x;
207}
208
209float field_float(const std::string& cmd, const std::string& key, const std::string& v) {
210    double x = 0;
211    if (!fnx::parse_number(v.c_str(), x) || !std::isfinite((float) x)) throw std::runtime_error(cmd + ": " + key + "=" + v + " is not a number");
212    return (float) x;
213}
214
215uint64_t field_hex64(const std::string& cmd, const std::string& key, const std::string& v) {
216    if (v.empty() || v.size() > 16 || v.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos)
217        throw std::runtime_error(cmd + ": " + key + " holds '" + v + "', not 1 to 16 hex digits");
218    return std::stoull(v, nullptr, 16);
219}
220
221// a comma-separated list's items, empty ones included ("1,,2" has three; "" has one, empty)
222std::vector<std::string> split_commas(const std::string& s) {
223    std::vector<std::string> out(1);
224    for (char ch : s) {
225        if (ch == ',') out.emplace_back();
226        else out.back() += ch;
227    }
228    return out;
229}
230
231GenReq parse_gen(const std::string& line, int vocab, int pad, bool batch, bool images) {
232    std::istringstream is(line);
233    std::string cmd, word;
234    GenReq r;
235    is >> cmd;
236    if (batch) {
237        if (!(is >> word)) throw std::runtime_error(cmd + ": no slot");
238        r.slot = field_int(cmd, "slot", word);
239    }
240    if (!(is >> word)) throw std::runtime_error(cmd + ": no max_new");
241    r.max_new = field_int(cmd, "max_new", word);
242    if (r.max_new < 1) throw std::runtime_error(cmd + ": max_new must be a number >= 1");
243    std::string ids, emb_path;
244    std::vector<uint64_t> img_keys;
245    while (is >> word) {
246        const size_t eq = word.find('=');
247        if (eq == std::string::npos) {
248            if (images && emb_path.empty()) {
249                emb_path = word;
250                continue;
251            }
252            ids = word;
253            break;
254        }
255        const std::string k = word.substr(0, eq), v = word.substr(eq + 1);
256        if (k == "img_keys") {
257            for (const std::string& h : split_commas(v)) img_keys.push_back(field_hex64(cmd, k, h));
258            continue;
259        }
260        if (k == "temperature") r.s.temperature = field_float(cmd, k, v);
261        else if (k == "top_p") r.s.top_p = field_float(cmd, k, v);
262        else if (k == "top_k") r.s.top_k = field_int(cmd, k, v);
263        else if (k == "min_p") r.s.min_p = field_float(cmd, k, v);
264        else if (k == "penalty_repeat") r.s.pen_repeat = field_float(cmd, k, v);
265        else if (k == "penalty_freq") r.s.pen_freq = field_float(cmd, k, v);
266        else if (k == "penalty_present") r.s.pen_present = field_float(cmd, k, v);
267        else if (k == "penalty_last_n") r.s.pen_last_n = field_int(cmd, k, v);
268        else if (k == "seed") {   // 0 to 2^64-1; no seed= draws one from std::random_device
269            if (v.empty() || v.size() > 20 || v.find_first_not_of("0123456789") != std::string::npos ||
270                (v.size() == 20 && v > "18446744073709551615"))
271                throw std::runtime_error(cmd + ": seed=" + v + " is not a whole number from 0 to 2^64-1");
272            r.s.seed = std::stoull(v);
273        }
274        else if (k == "logit_bias") throw std::runtime_error(cmd + ": logit_bias is not supported");
275        else if (k == "keep") r.hints.keep = field_int(cmd, k, v);
276        else if (k == "ckpt") {
277            if (v != "0" && v != "1") throw std::runtime_error(cmd + ": ckpt=" + v + " is not 0 or 1");
278            r.hints.cache = v == "1";
279        }
280        else if (k == "pin") {   // a client's strata_prefix: sFNX's cache has no pinned checkpoints
281            static bool said = false;
282            if (!said) std::fprintf(stderr, "sfnx: pin= (a client's strata_prefix) is not supported: such requests go on without it\n");
283            said = true;
284        }
285        // Strata's per-request engine tuning (strata_tune) and its control vector: nothing in sFNX to set
286        else if (k == "pcie_frac" || k == "spec_min_p" || k == "pipe" || k == "aux_cpus" || k == "cvec") {
287            static std::set<std::string> said;
288            if (said.insert(k).second)
289                std::fprintf(stderr, "sfnx: %s= (Strata's per-request engine tuning or control vector) has nothing to set in sfnx: "
290                                     "such requests go on without it\n", k.c_str());
291        }
292        else throw std::runtime_error(cmd + ": unknown key " + k);
293    }
294    if (is >> word) throw std::runtime_error(cmd + ": text after the token ids");
295    if (ids.empty()) throw std::runtime_error(cmd + ": no token ids");
296    try {
297        fnx::check_sampling(r.s);
298    } catch (const std::runtime_error& ex) {
299        throw std::runtime_error(cmd + ": " + ex.what());
300    }
301    for (const std::string& t : split_commas(ids)) {
302        long long v = 0;
303        if (!fnx::parse_whole(t.c_str(), v)) throw std::runtime_error(cmd + ": token id '" + t + "' is not a whole number");
304        if (v < 0 || v >= vocab) throw std::runtime_error(cmd + ": token id " + t + " outside the vocabulary");
305        r.ids.push_back((int) v);
306    }
307    if (images) attach_images(r, emb_path, img_keys, pad);
308    // SFNX_TEST_PROMPT=FILE.bin with SFNX_TEST_PROMPT_CONFIRM=1 (measurements only; check_test_prompt at start): a text
309    // request's ids replaced by the file's, so a request through the front end reads exactly the tokens fnx_run reads
310    if (const char* tp = std::getenv("SFNX_TEST_PROMPT"); tp && !images) {
311        std::FILE* f = std::fopen(tp, "rb");
312        if (!f) throw std::runtime_error(std::string("SFNX_TEST_PROMPT: cannot open ") + tp);
313        uint32_t nl = 0, nd = 0;
314        int64_t ne = 0;
315        const bool head = std::fread(&nl, 4, 1, f) == 1 && std::fseek(f, nl, SEEK_CUR) == 0 && std::fread(&nd, 4, 1, f) == 1 &&
316                          std::fread(&ne, 8, 1, f) == 1;
317        if (!head || ne < 1 || ne > 0x7fffffffLL) {
318            std::fclose(f);
319            throw std::runtime_error(std::string("SFNX_TEST_PROMPT: ") + tp + " has no valid tokens header");
320        }
321        std::vector<float> v((size_t) ne);
322        const bool full = std::fread(v.data(), 4, v.size(), f) == v.size();
323        std::fclose(f);
324        if (!full) throw std::runtime_error("SFNX_TEST_PROMPT: short file");
325        r.ids.clear();
326        for (float x : v) {
327            if (!(x >= 0.f && x < (float) vocab) || x != (float) (int) x)
328                throw std::runtime_error(std::string("SFNX_TEST_PROMPT: ") + tp + " holds a value that is not a token id");
329            r.ids.push_back((int) x);
330        }
331        std::fprintf(stderr, "sfnx: SFNX_TEST_PROMPT: the request reads %s (%zu tokens) instead\n", tp, r.ids.size());
332    }
333    return r;
334}
335
336struct Interrupted {   // a prompt read ended at a chunk boundary (BYIELD, STOP)
337    int read;
338};
339
340bool is_eos(int t) {
341    for (int e : EOS)
342        if (t == e) return true;
343    return false;
344}
345
346std::vector<int> tail(const std::vector<int>& v, int n) {
347    return std::vector<int>(v.size() > (size_t) n ? v.end() - n : v.begin(), v.end());
348}
349
350// a slot: a lane with its conversation, and when decoding in the batch its request's state
351struct Slot {
352    int lane = -1;
353    std::unique_ptr<fnx::Session> sess;
354    bool decoding = false;
355    long seq = 0;   // the request it reads or decodes for (Input's number: BSTOP and BYIELD for it)
356    int max_new = 0, produced = 0, x = -1;
357    int rounds = 0;   // batched windows it was in (after its first token's)
358    fnx::Sampling s;
359    std::mt19937_64 rng;
360    std::vector<int> recent;   // the tokens before the next pick (the penalty window's)
361    std::chrono::steady_clock::time_point t0;
362    long used = 0;   // last admission or finish, for choosing which idle lane to park
363    std::chrono::steady_clock::time_point idle_since;   // its last reply's end (an arena's idle lanes park after IDLE_PARK)
364    // a decoding slot whose conversation was taken off its lane because the pool ran out (every decoding lane needed
365    // a page): its request state stays, and so does its lane (never dealt to another slot meanwhile); it resumes from
366    // `held` (its conversation, x not among it; kept here, not in the conversation cache, so nothing evicts it) once
367    // there is room for it again
368    bool paused = false;
369    std::shared_ptr<fnx::Engine::SeqState> held;
370    int sat_out = 0;   // windows in a row it was left out of for want of a free page
371    fnx::BatchLane bl;   // with FNX_BATCH_DRAFTS: its next row, drafts and sampler (x and recent are not used)
372    bool free() const { return !decoding && !paused; }
373};
374
375constexpr int pages_for(int n_pos) { return n_pos / fnx::KVP_POS + 1; }
376// pages of growth each decoding lane gets before a paused slot resumes (16: ~3k tokens)
377constexpr int RESUME_ROOM = 16;
378// an admission waits until the prompt and this much of its reply (or all of max_new, if less) fit the pool
379constexpr int ADMIT_REPLY = 2048;
380// FNX_ARENA: while experts are lent to the K/V pool, a lane idle this long has its conversation parked to host memory
381// (an agent between tool calls comes back within seconds; an ended conversation never does), so the pages free and
382// the slots go back to the experts; the upkeep runs at most this often
383constexpr std::chrono::seconds IDLE_PARK{120}, UPKEEP{5};
384
385struct Server {
386    Args a;
387    fnx::Model& m;
388    fnx::Engine& e;
389    Input& in;
390    std::shared_ptr<fnx::ConvCache> cache;
391    std::vector<Slot> slots;
392    long clock = 0;
393    int reading = -1;   // the slot whose prompt is being read (its lane is never parked for room)
394    std::unique_ptr<fnx::BatchDecoder> dec;   // FNX_BATCH_DRAFTS: the batched windows carry drafts
395
396    // slot i's request is ended by BSTOP <i>, or by a STOP that came while it was the latest request line (STOP acts on
397    // the latest request, which here decodes in a slot)
398    bool slot_stopped(int i) const {
399        const long n = slots[(size_t) i].seq;
400        return in.bstopped(i, n) || in.stop_upto.load() == n;
401    }
402
403    // free pool pages until `need` are free: the idle lanes' conversations to host memory, least recently used first
404    // (never slot `keep`'s); false when the idle lanes do not hold enough
405    bool make_room(int need, int keep) {
406        while (e.free_pages() < need) {
407            int k = -1;
408            for (int i = 0; i < (int) slots.size(); ++i) {
409                const Slot& s = slots[(size_t) i];
410                if (i == keep || i == reading || s.decoding || s.paused || s.lane < 0 || e.lane_pages(s.lane) == 0) continue;
411                if (k < 0 || s.used < slots[(size_t) k].used) k = i;
412            }
413            if (k < 0) return false;
414            const int was = e.lane();
415            std::fprintf(stderr, "sfnx: K/V pool short (%d pages free, %d wanted): slot %d's conversation parked\n", e.free_pages(), need, k);
416            slots[(size_t) k].sess->park();
417            e.use_lane(was);
418        }
419        return true;
420    }
421
422    // FNX_ARENA, while experts are lent: idle lanes past IDLE_PARK parked, then the slots the freed pages allow given
423    // back (Engine::arena_reclaim: not within its hold after a lend)
424    std::chrono::steady_clock::time_point last_upkeep;
425    void upkeep() {
426        const auto now = std::chrono::steady_clock::now();
427        if (now - last_upkeep < UPKEEP) return;
428        last_upkeep = now;
429        bool lent = false;
430        for (int v : e.arena_lent()) lent = lent || v > 0;
431        if (!lent) return;
432        const int was = e.lane();
433        for (int i = 0; i < (int) slots.size(); ++i) {
434            Slot& s = slots[(size_t) i];
435            if (!s.free() || i == reading || s.lane < 0 || e.lane_pages(s.lane) == 0 || now - s.idle_since < IDLE_PARK) continue;
436            std::fprintf(stderr, "sfnx: slot %d idle %.0f s while experts are lent: its conversation parked\n", i,
437                         std::chrono::duration<double>(now - s.idle_since).count());
438            s.sess->park();
439        }
440        e.use_lane(was);
441        e.arena_reclaim();
442    }
443
444    Server(const Args& args, fnx::Model& model, fnx::Engine& eng, Input& input) : a(args), m(model), e(eng), in(input) {
445        cache = std::make_shared<fnx::ConvCache>();
446        cache->budget = (size_t) a.cache_mib << 20;
447        slots.resize((size_t) a.batch);
448        slots[0].lane = 0;
449        slots[0].sess = std::make_unique<fnx::Session>(e, a.K, a.lookup, EOS, 248045, cache, 0);
450        // every lane and every window graph now: what they take, taken before the first request
451        for (int i = 1; i < a.batch; ++i) lane_for(i);
452        if (a.batch > 1 && fnx::batch_drafts() != fnx::BatchDrafts::off)
453            dec = std::make_unique<fnx::BatchDecoder>(e, a.K, a.lookup, EOS, fnx::batch_drafts());
454        e.warm_graphs();
455    }
456
457    // the slot's lane and session, made on first use (lane 0 is slot 0's from the start, but lanes move between
458    // slots, so any slot may be the one without; a new lane takes pool pages)
459    fnx::Session& lane_for(int slot) {
460        Slot& sl = slots[(size_t) slot];
461        if (sl.lane < 0) {
462            sl.lane = e.add_lane();
463            sl.sess = std::make_unique<fnx::Session>(e, a.K, a.lookup, EOS, 248045, cache, sl.lane);
464        }
465        return *sl.sess;
466    }
467
468    bool any_decoding() const {
469        for (const Slot& s : slots)
470            if (s.decoding || s.paused) return true;
471        return false;
472    }
473
474    // the K/V pool is out of pages for every decoding lane and no idle lane can give any: the most recently admitted
475    // decoding slot's conversation goes to host memory (its pages back to the pool) and the slot waits, request intact
476    void pause_one(const std::vector<int>& rows) {
477        int k = rows[0];
478        for (int i : rows)
479            if (slots[(size_t) i].t0 > slots[(size_t) k].t0) k = i;
480        Slot& sl = slots[(size_t) k];
481        const int was = e.lane();
482        const auto t_p = std::chrono::steady_clock::now();
483        sl.held = sl.sess->unload();
484        e.use_lane(was);
485        sl.decoding = false;
486        sl.sat_out = 0;
487        sl.paused = true;
488        std::fprintf(stderr, "sfnx: K/V pool full: slot %d paused, its %zu tokens held in host memory in %.0f ms (%d pages free)\n", k,
489                     sl.held->tokens.size(), std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t_p).count(),
490                     e.free_pages());
491    }
492
493    // paused slots back, oldest admission first, while there is room for one (idle lanes are parked for it): its
494    // conversation reloaded from the held state (a copy, not a read), then it decodes on from its next token
495    void resume_paused() {
496        if (reading >= 0) return;   // not while a prompt read holds the engine (its progress runs the decoding windows)
497        for (;;) {
498            int k = -1;
499            for (int i = 0; i < (int) slots.size(); ++i)
500                if (slots[(size_t) i].paused && (k < 0 || slots[(size_t) i].t0 < slots[(size_t) k].t0)) k = i;
501            if (k < 0) return;
502            Slot& sl = slots[(size_t) k];
503            // with room for every decoding lane, it included, to grow RESUME_ROOM pages, so it is not paused again at once
504            // (alone, its own pages are enough: a conversation always fits the pool)
505            int others = 0;
506            for (const Slot& o : slots) others += o.decoding;
507            const int need = pages_for((int) sl.held->tokens.size() + fnx::MAXT) + (others ? RESUME_ROOM * (others + 1) : 0) -
508                             e.lane_pages(sl.lane);
509            if (!make_room(need, k)) return;
510            const int was = e.lane();
511            const auto t_r = std::chrono::steady_clock::now();
512            sl.sess->reload(*sl.held);
513            e.use_lane(was);
514            sl.paused = false;
515            sl.decoding = true;
516            const size_t n = sl.held->tokens.size();
517            sl.held.reset();
518            std::fprintf(stderr, "sfnx: slot %d resumed: its %zu tokens reloaded in %.0f ms\n", k, n,
519                         std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t_r).count());
520        }
521    }
522
523    // FNX_ROUTE_COUNT=1 with FNX_ROUTE_FILE=path: the engine's expert tallies to path after every reply (u32
524    // [decode | prompt][NL][NEXP])
525    // FNX_ROUTE_TRACE=M with FNX_ROUTE_TRACE_FILE=path: decode's picks since the last reply appended to path
526    // (check_route_env makes sure of the paths at start). A file that cannot be written ends that measurement, said on
527    // stderr, and the engine serves on
528    size_t traced = 0;
529    bool trace_failed = false, count_failed = false;
530    // v to path (fopen mode `mode`); false with errno set when any step fails
531    static bool write_u32s(const char* path, const char* mode, const std::vector<unsigned>& v) {
532        std::FILE* f = std::fopen(path, mode);
533        if (!f) return false;
534        const bool wrote = std::fwrite(v.data(), sizeof(unsigned), v.size(), f) == v.size();
535        const int werr = errno;
536        if (std::fclose(f) != 0) return false;
537        errno = werr;
538        return wrote;
539    }
540    void save_routes() {
541        if (!trace_failed)
542            if (const std::vector<unsigned> t = e.route_trace(traced); !t.empty()) {
543                const char* tpath = std::getenv("FNX_ROUTE_TRACE_FILE");
544                if (write_u32s(tpath, traced ? "ab" : "wb", t)) {
545                    traced += t.size();
546                } else {
547                    std::fprintf(stderr, "sfnx: FNX_ROUTE_TRACE_FILE: cannot write %s (%s): route tracing stopped after %zu picks\n", tpath,
548                                 std::strerror(errno), traced);
549                    trace_failed = true;
550                }
551            }
552        if (count_failed) return;
553        const std::vector<unsigned> v = e.route_counts();
554        if (v.empty()) return;
555        const char* path = std::getenv("FNX_ROUTE_FILE");
556        const std::string tmp = std::string(path) + ".tmp";
557        if (!write_u32s(tmp.c_str(), "wb", v) || std::rename(tmp.c_str(), path) != 0) {
558            std::fprintf(stderr, "sfnx: FNX_ROUTE_FILE: cannot write %s (%s): route counting stopped\n", path, std::strerror(errno));
559            count_failed = true;
560        }
561    }
562
563    void finish_slot(int i, fnx::Finish f) {
564        Slot& sl = slots[(size_t) i];
565        const double ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - sl.t0).count();
566        char buf[128];
567        std::snprintf(buf, sizeof buf, "BDONE %d %d %s %.1f %ld %ld %d", i, sl.produced, fnx::finish_name(f), ms, dec ? sl.bl.accepted : 0L,
568                      dec ? sl.bl.offered : 0L, sl.rounds);
569        say(buf);
570        sl.decoding = false;
571        sl.sat_out = 0;
572        sl.used = ++clock;
573        sl.idle_since = std::chrono::steady_clock::now();
574        int busy = 0;
575        for (const Slot& o : slots) busy += o.decoding;
576        std::fprintf(stderr, "sfnx: slot %d done: %d tokens in %.0f ms (%s), %d slots decoding%s\n", i, sl.produced, ms, fnx::finish_name(f), busy,
577                     dec ? (", drafts " + std::to_string(sl.bl.accepted) + " of " + std::to_string(sl.bl.offered)).c_str() : "");
578        save_routes();
579    }
580
581    // one window for every decoding slot: a row each
582    void decode_step() {
583        for (int i = 0; i < (int) slots.size(); ++i)
584            if (slots[(size_t) i].paused && slot_stopped(i)) {
585                slots[(size_t) i].paused = false;
586                slots[(size_t) i].held.reset();
587                finish_slot(i, fnx::Finish::cancel);
588            }
589        resume_paused();
590        std::vector<int> rows;
591        for (int i = 0; i < (int) slots.size(); ++i) {
592            if (!slots[(size_t) i].decoding) continue;
593            if (slot_stopped(i)) {
594                finish_slot(i, fnx::Finish::cancel);
595                continue;
596            }
597            rows.push_back(i);
598        }
599        // with drafts, a lane's rows: within the window's MAXT, then their pages if idle lanes can give them, else its
600        // drafts cut to the pages it holds (at least its first row, which the loop below sees to as without drafts)
601        if (dec && !rows.empty()) {
602            std::vector<fnx::BatchLane*> ls;
603            for (int i : rows) ls.push_back(&slots[(size_t) i].bl);
604            fnx::BatchDecoder::fit(ls);
605            int want = 0;
606            for (int i : rows) {
607                const int lane = slots[(size_t) i].lane;
608                want += std::max(0, pages_for(e.lane_pos(lane) + slots[(size_t) i].bl.rows()) - e.lane_pages(lane));
609            }
610            if (want > 0 && !make_room(want, -1))
611                for (int i : rows) {
612                    const int lane = slots[(size_t) i].lane;
613                    slots[(size_t) i].bl.cut(std::max(1, e.lane_pages(lane) * fnx::KVP_POS - 1 - e.lane_pos(lane)));
614                }
615        }
616        auto rows_of = [&](int i) { return dec ? slots[(size_t) i].bl.rows() : 1; };
617        // a lane that crosses into a new page needs one free: idle lanes are parked for it, else it sits this window out;
618        // when that leaves no lane to run, a decoding slot is paused (its conversation parked) for the others' pages
619        for (;;) {
620            if (rows.empty()) return;
621            int grow = 0;
622            for (int i : rows) grow += e.lane_pages(slots[(size_t) i].lane) < pages_for(e.lane_pos(slots[(size_t) i].lane) + rows_of(i));
623            if (grow == 0 || make_room(grow, -1)) break;
624            std::vector<int> fit;
625            int left = e.free_pages();
626            for (int i : rows) {
627                const int lane = slots[(size_t) i].lane;
628                const bool needs = e.lane_pages(lane) < pages_for(e.lane_pos(lane) + rows_of(i));
629                if (!needs || left > 0) {
630                    fit.push_back(i);
631                    left -= needs;
632                }
633            }
634            if (!fit.empty()) {
635                for (int i : rows)
636                    if (std::find(fit.begin(), fit.end(), i) == fit.end() && slots[(size_t) i].sat_out++ == 0)
637                        std::fprintf(stderr, "sfnx: K/V pool short (%d pages free): slot %d waits for a page while %zu slot(s) decode\n",
638                                     e.free_pages(), i, fit.size());
639                rows = fit;
640                break;
641            }
642            if (rows.size() == 1)
643                throw std::runtime_error("the K/V pool is full with one lane decoding: its conversation outgrew the pool");
644            pause_one(rows);
645            std::vector<int> still;
646            for (int i : rows)
647                if (slots[(size_t) i].decoding) still.push_back(i);
648            rows = still;
649        }
650        for (int i : rows)
651            if (slots[(size_t) i].sat_out > 0) {
652                std::fprintf(stderr, "sfnx: slot %d decodes again after waiting %d window(s) for a page\n", i, slots[(size_t) i].sat_out);
653                slots[(size_t) i].sat_out = 0;
654            }
655        if (dec) {
656            std::vector<fnx::BatchLane*> ls;
657            std::vector<int> limit;
658            for (int i : rows) {
659                ls.push_back(&slots[(size_t) i].bl);
660                limit.push_back(slots[(size_t) i].max_new - slots[(size_t) i].produced);
661            }
662            for (int i : rows) ++slots[(size_t) i].rounds;
663            // FNX_BATCH_STATS=1: where a window cycle goes on the host, per 100 windows: the batch decoder's window (verify, draft layer and chain, the rest of it) and what runs
664            // between two windows (this loop: upkeep, request polling, page rooms, finishing slots)
665            static const bool wstats = fnx::env_flag("FNX_BATCH_STATS");
666            static std::chrono::steady_clock::time_point t_prev_end{};
667            static double acc_out = 0, acc_win = 0, acc_ver = 0, acc_dr = 0, acc_say = 0;
668            static int nwin = 0;
669            const auto tw0 = std::chrono::steady_clock::now();
670            if (wstats && t_prev_end.time_since_epoch().count() != 0) {
671                const double gap = std::chrono::duration<double, std::milli>(tw0 - t_prev_end).count();
672                if (gap < 400.0) acc_out += gap;
673            }
674            const auto got = dec->window(ls, limit, [&](int r, int tok) {
675                say("BT " + std::to_string(rows[(size_t) r]) + " " + std::to_string(tok));
676                ++slots[(size_t) rows[(size_t) r]].produced;
677            });
678            if (wstats) {
679                t_prev_end = std::chrono::steady_clock::now();
680                acc_win += std::chrono::duration<double, std::milli>(t_prev_end - tw0).count();
681                acc_ver += dec->last_verify_ms;
682                acc_dr += dec->last_draft_ms;
683                if (++nwin == 100) {
684                    std::fprintf(stderr, "fnx: window cycle (100 windows, means in ms): between windows %.1f, window() %.1f = verify_rows %.1f + draft_next %.1f + the rest %.1f\n", acc_out / nwin,
685                                 acc_win / nwin, acc_ver / nwin, acc_dr / nwin, (acc_win - acc_ver - acc_dr) / nwin);
686                    acc_out = acc_win = acc_ver = acc_dr = acc_say = 0;
687                    nwin = 0;
688                }
689            }
690            for (size_t r = 0; r < rows.size(); ++r) {
691                const int i = rows[r];
692                if (got[r].eos) finish_slot(i, fnx::Finish::stop);
693                else if (slots[(size_t) i].produced >= slots[(size_t) i].max_new) finish_slot(i, slot_stopped(i) ? fnx::Finish::cancel : fnx::Finish::length);
694            }
695            return;
696        }
697        std::vector<int> lanes, xs;
698        bool sample = false;
699        for (int i : rows) {
700            lanes.push_back(slots[(size_t) i].lane);
701            xs.push_back(slots[(size_t) i].x);
702            sample = sample || slots[(size_t) i].s.temperature > 0.f;
703        }
704        const std::vector<int> o = e.step(lanes, xs);
705        for (int i : rows) ++slots[(size_t) i].rounds;
706        std::vector<std::vector<std::pair<float, int>>> cand;
707        if (sample) {
708            fnx::Engine::Penalties pen;
709            bool any_pen = false;
710            for (int i : rows) any_pen = any_pen || fnx::penalizes(slots[(size_t) i].s);
711            if (any_pen)
712                for (int i : rows) {
713                    const Slot& sl = slots[(size_t) i];
714                    pen.rows.push_back(fnx::penalizes(sl.s) ? fnx::penalty_row(sl.recent, sl.s) : fnx::Engine::Penalties::Row{});
715                }
716            cand = e.top_tokens((int) rows.size(), pen);
717        }
718        for (size_t r = 0; r < rows.size(); ++r) {
719            const int i = rows[r];
720            Slot& sl = slots[(size_t) i];
721            const int tok = sl.s.temperature > 0.f ? fnx::sample_token(cand[r], sl.s, sl.rng) : o[r];
722            say("BT " + std::to_string(i) + " " + std::to_string(tok));
723            ++sl.produced;
724            sl.x = tok;
725            sl.recent.push_back(tok);
726            if ((int) sl.recent.size() > 2 * fnx::Engine::PEN_CAP) sl.recent = tail(sl.recent, fnx::Engine::PEN_CAP);
727            if (is_eos(tok)) finish_slot(i, fnx::Finish::stop);
728            else if (sl.produced >= sl.max_new) finish_slot(i, in.bstopped(i, sl.seq) ? fnx::Finish::cancel : fnx::Finish::length);
729        }
730    }
731
732    // a prompt read's progress for request seq: PP, the end of the read on STOP, on BYIELD or BSTOP for this slot (a
733    // batch read; slot -1, a solo read, ends on a BYIELD it can give way to), the decoding slots' windows. A decoding
734    // window that finds no room is no failure of the read's request: it ends the engine, as it does outside a read
735    std::function<void(int, int)> progress(int slot, long seq) {
736        return [this, slot, seq](int done, int total) {
737            say("PP " + std::to_string(done) + " " + std::to_string(total));
738            if (in.stop_now) throw Interrupted{done};
739            if (slot >= 0 ? in.yielded(slot, seq) || in.bstopped(slot, seq) : solo_yield_to(seq) >= 0) throw Interrupted{done};
740            if (!any_decoding()) return;
741            try {
742                decode_step();
743            } catch (const fnx::Refused& ex) {
744                throw std::runtime_error(std::string("a decoding window during a prompt read: ") + ex.what());
745            }
746        };
747    }
748
749    // the idle slot whose lane holds the longest prefix of the prompt (prefer on a tie; -1: no idle slot)
750    int best_slot(const std::vector<int>& ids, int prefer) {
751        int best = -1;
752        size_t best_n = 0;
753        const int was = e.lane();
754        for (int i = 0; i < (int) slots.size(); ++i) {
755            if (!slots[(size_t) i].free()) continue;
756            size_t k = 0;
757            if (slots[(size_t) i].lane >= 0) {
758                e.use_lane(slots[(size_t) i].lane);
759                const std::vector<int>& h = e.history();
760                while (k < h.size() && k < ids.size() && h[k] == ids[k]) ++k;
761            }
762            if (best < 0 || k > best_n || (k == best_n && i == prefer)) {
763                best_n = k;
764                best = i;
765            }
766        }
767        e.use_lane(was);
768        return best;
769    }
770
771    void done_line(const fnx::GenStats& st, fnx::Finish f) {
772        char buf[256];
773        std::snprintf(buf, sizeof buf, "DONE %d %d %.1f %.1f %s %ld %ld %d", st.generated, st.prompt_tokens, st.prompt_ms, st.decode_ms,
774                      fnx::finish_name(f), st.drafts_accepted, st.drafts_offered, st.reused);
775        say(buf);
776    }
777
778    // a prompt read the engine had no room for (fnx::Refused): ERR for the request, and no DONE (the front end reads
779    // an ERR as the request's end). The message never starts "BGEN:", which the front end takes for a refused slot with
780    // nothing read and sends again; this lane holds what was read, and the next request on it reuses that or parks it
781    void read_refused(int slot, const fnx::Refused& ex, const char* cmd) {
782        Slot& sl = slots[(size_t) slot];
783        sl.idle_since = std::chrono::steady_clock::now();
784        std::fprintf(stderr, "sfnx: slot %d: the prompt read failed (%s); its lane holds %d tokens, %d pages free\n", slot, ex.what(),
785                     e.lane_pos(sl.lane), e.free_pages());
786        say(std::string("ERR prompt read (") + cmd + " slot " + std::to_string(slot) + "): " + ex.what());
787    }
788
789    // a BYIELD for solo request seq names the slot its part read is to wait in (the front end holds that slot for it
790    // and sends BGEN there after the shorter request): that slot, when it can take the lane (said once if not), else -1
791    bool yield_said = false;
792    int solo_yield_to(long seq) {
793        const int to = in.solo_yield(seq);
794        if (to < 0) return -1;
795        if (to < (int) slots.size() && slots[(size_t) to].free()) return to;
796        if (!yield_said)
797            std::fprintf(stderr, "sfnx: BYIELD %d during a solo read: no free slot %d to leave the part read in; the read goes on\n", to, to);
798        yield_said = true;
799        return -1;
800    }
801
802    void solo(const GenReq& r) {
803        const Running running(in, r.seq);
804        yield_said = false;
805        int slot = best_slot(r.ids, 0);
806        if (slot < 0) {   // the front end sends GEN only when no slot decodes
807            say("ERR GEN: every slot is decoding");
808            return;
809        }
810        fnx::Session& s = lane_for(slot);
811        slots[(size_t) slot].used = ++clock;
812        // the prompt and the start of its reply, as an admission takes (idle lanes parked for them now); later pages as
813        // the reply grows, idle lanes parked for them then (on_pool_short below), so a request that sets no max_tokens
814        // (max_new: the rest of the context) does not empty every idle lane before its first token
815        const int need = pages_for((int) r.ids.size() + std::min(r.max_new, ADMIT_REPLY) + fnx::MAXT) - e.lane_pages(slots[(size_t) slot].lane);
816        if (!make_room(need, slot)) {
817            say("ERR GEN: the K/V pool is full: the request needs " + std::to_string(need) + " more pages, " +
818                std::to_string(e.free_pages()) + " are free");
819            return;
820        }
821        fnx::GenStats st;
822        try {
823            reading = slot;
824            e.set_pass_rows(any_decoding() ? 8192 : 0);   // other requests decode: they run between passes, so a pass stays at most 8192 rows (what 2 chunks of 4096 were)
825            s.read(r.ids, st, progress(-1, r.seq), r.hints);
826            reading = -1;
827        } catch (const Interrupted& it) {
828            reading = -1;
829            st.prompt_tokens = it.read;   // as far as the read got (st.reused of them reused), not the whole prompt
830            // given way (not stopped): the lane with the part read goes to the slot the BYIELD named, which the front
831            // end's BGEN for the rest of this prompt will name
832            if (const int to = in.stop_now ? -1 : solo_yield_to(r.seq); to >= 0) {
833                if (to != slot) {
834                    std::swap(slots[(size_t) slot].lane, slots[(size_t) to].lane);
835                    std::swap(slots[(size_t) slot].sess, slots[(size_t) to].sess);
836                    slot = to;
837                }
838                slots[(size_t) slot].idle_since = std::chrono::steady_clock::now();
839                std::fprintf(stderr, "sfnx: solo read gave way after %d of %zu tokens; slot %d holds them\n", it.read, r.ids.size(), slot);
840                say("YIELDED " + std::to_string(slot) + " " + std::to_string(it.read));
841            }
842            done_line(st, fnx::Finish::cancel);
843            return;
844        } catch (const fnx::Refused& ex) {   // no room for the read: this request fails, the lane keeps what was read
845            reading = -1;
846            read_refused(slot, ex, "GEN");
847            return;
848        }
849        say("RESUME " + std::to_string(st.reused));
850        // the reply's pages beyond what was made room for: idle lanes parked as it needs them (nothing else decodes)
851        struct PoolShort {
852            fnx::Engine& e;
853            ~PoolShort() { e.on_pool_short = nullptr; }
854        } pool_short{e};
855        e.on_pool_short = [this, slot](int, int pages) { make_room(e.free_pages() + pages, slot); };
856        const fnx::Finish f = s.generate(r.max_new, r.s, [&](int t) { say("T " + std::to_string(t)); }, &in.stop_now, st);
857        done_line(st, f);
858        std::fprintf(stderr, "sfnx: slot %d: prompt %d tokens = %d reused + %d read in %.0f ms, %d generated in %.0f ms (%.1f tok/s), "
859                             "drafts %ld of %ld, %d rounds (%d with lookup drafts, %.2f ms a round)\n",
860                     slot, st.prompt_tokens, st.reused, st.prompt_tokens - st.reused, st.prompt_ms, st.generated, st.decode_ms,
861                     st.generated * 1000.0 / std::max(1.0, st.decode_ms), st.drafts_accepted, st.drafts_offered, st.rounds, st.lookup_rounds,
862                     st.decode_ms / std::max(1, st.rounds));
863        slots[(size_t) slot].idle_since = std::chrono::steady_clock::now();
864        save_routes();
865    }
866
867    void admit(const GenReq& r) {
868        if (r.slot < 0 || r.slot >= (int) slots.size() || !slots[(size_t) r.slot].free()) {
869            say("ERR BGEN: no such free slot " + std::to_string(r.slot) + " (--batch " + std::to_string(slots.size()) + ")");
870            return;
871        }
872        const Running running(in, r.seq);
873        const int i = r.slot;
874        // the slot takes the idle lane that holds most of the prompt (the front end picks slots by what it believes they
875        // hold; the lanes are sFNX's to deal)
876        const int k = best_slot(r.ids, i);
877        if (k >= 0 && k != i && slots[(size_t) k].lane >= 0) {
878            std::swap(slots[(size_t) i].lane, slots[(size_t) k].lane);
879            std::swap(slots[(size_t) i].sess, slots[(size_t) k].sess);
880        }
881        fnx::Session& s = lane_for(i);
882        Slot& sl = slots[(size_t) i];
883        sl.used = ++clock;
884        sl.seq = r.seq;
885        // the prompt's pages and the first ADMIT_REPLY tokens of its reply (the lane's own count: it may restart), and
886        // room for the decoding slots to grow while it reads; short of that, the decoding slots go on until enough of
887        // them end
888        for (;;) {
889            int growing = 0;
890            for (const Slot& o : slots) growing += o.decoding;
891            const int need = pages_for((int) r.ids.size() + std::min(r.max_new, ADMIT_REPLY) + fnx::MAXT) + 2 * growing -
892                             e.lane_pages(sl.lane);
893            if (make_room(need, i)) break;
894            if (!any_decoding()) {
895                say("ERR BGEN: the K/V pool is full: the prompt needs " + std::to_string(need) + " more pages, " +
896                    std::to_string(e.free_pages()) + " are free");
897                return;
898            }
899            if (in.yielded(i, r.seq) || in.bstopped(i, r.seq) || in.stop_now) {
900                if (in.yielded(i, r.seq)) say("YIELDED " + std::to_string(i) + " 0");
901                fnx::GenStats st;   // nothing read: prompt_tokens 0
902                done_line(st, fnx::Finish::cancel);
903                say("BADM " + std::to_string(i) + " 0");
904                return;
905            }
906            decode_step();
907        }
908        fnx::GenStats st;
909        try {
910            reading = i;
911            e.set_pass_rows(any_decoding() ? 8192 : 0);
912            s.read(r.ids, st, progress(i, r.seq), r.hints);
913            reading = -1;
914        } catch (const Interrupted& it) {
915            reading = -1;
916            if (in.yielded(i, r.seq)) say("YIELDED " + std::to_string(i) + " " + std::to_string(it.read));
917            st.prompt_tokens = it.read;
918            done_line(st, fnx::Finish::cancel);
919            say("BADM " + std::to_string(i) + " 0");
920            return;
921        } catch (const fnx::Refused& ex) {
922            reading = -1;
923            read_refused(i, ex, "BGEN");
924            return;
925        }
926        if (in.bstopped(i, r.seq)) {   // BSTOP after the last chunk (or a prompt with nothing to read): cancelled before its first token
927            done_line(st, fnx::Finish::cancel);
928            say("BADM " + std::to_string(i) + " 0");
929            sl.idle_since = std::chrono::steady_clock::now();
930            return;
931        }
932        // the first token: the prompt's last through a window of this lane alone
933        const auto t1 = std::chrono::steady_clock::now();
934        const std::vector<int> o = e.step({sl.lane}, {r.ids.back()});
935        sl.s = r.s;
936        sl.rng.seed(r.s.seed ? *r.s.seed : std::random_device{}());
937        sl.recent = tail(r.ids, std::max(1, r.s.pen_last_n));
938        int tok = o[0];
939        if (r.s.temperature > 0.f) {
940            fnx::Engine::Penalties pen;
941            if (fnx::penalizes(r.s)) pen.rows.push_back(fnx::penalty_row(sl.recent, r.s));
942            tok = fnx::sample_token(e.top_tokens(1, pen)[0], r.s, sl.rng);
943        }
944        say("T " + std::to_string(tok));
945        st.generated = 1;
946        st.decode_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t1).count();
947        const bool more = !is_eos(tok) && r.max_new > 1;
948        done_line(st, is_eos(tok) ? fnx::Finish::stop : fnx::Finish::length);
949        say("BADM " + std::to_string(i) + (more ? " 1" : " 0"));
950        if (!more) {
951            sl.idle_since = std::chrono::steady_clock::now();
952            return;
953        }
954        sl.decoding = true;
955        sl.max_new = r.max_new;
956        sl.produced = 1;
957        sl.rounds = 0;
958        sl.x = tok;
959        sl.recent.push_back(tok);
960        if (dec) {
961            std::vector<int> ctx(r.ids);
962            ctx.push_back(tok);
963            sl.bl.start(sl.lane, r.s, sl.rng, std::move(ctx));
964        }
965        sl.t0 = t1;
966        int busy = 0;
967        for (const Slot& o : slots) busy += o.decoding;
968        std::fprintf(stderr, "sfnx: slot %d (lane %d) admitted: prompt %d = %d reused + %d read in %.0f ms; %d slots decoding\n", i, sl.lane,
969                     st.prompt_tokens, st.reused, st.prompt_tokens - st.reused, st.prompt_ms, busy);
970    }
971
972    void run() {
973        std::string line;
974        long seq = 0;
975        for (;;) {
976            // requests first; the decoding slots' window when none is waiting
977            upkeep();
978            if (!in.next(line, seq, !any_decoding(), std::chrono::duration_cast<std::chrono::milliseconds>(UPKEEP))) {
979                if (in.closed()) return;
980                decode_step();
981                continue;
982            }
983            if (line.empty()) continue;
984            const std::string cmd = line.substr(0, line.find(' '));
985            if (cmd == "QUIT") return;
986            if (cmd != "GEN" && cmd != "BGEN" && cmd != "GENI" && cmd != "BGENI") {
987                say("ERR " + cmd + ": not supported by sfnx");
988                continue;
989            }
990            const bool batch = cmd[0] == 'B', images = cmd.back() == 'I';
991            if (batch && a.batch < 2) {
992                say("ERR " + cmd + ": sfnx runs without --batch");
993                continue;
994            }
995            if (images && !a.vision) {
996                say("ERR this engine was started without --vision");
997                continue;
998            }
999            GenReq r;
1000            try {
1001                r = parse_gen(line, m.vocab, (int) m.ple_image, batch, images);
1002                if ((long) r.ids.size() + r.max_new + 8 > a.max_ctx) throw std::runtime_error(cmd + ": prompt + max_new exceed the context");
1003                r.seq = seq;
1004            } catch (const std::exception& ex) {
1005                say(std::string("ERR ") + ex.what());
1006                continue;
1007            }
1008            if (batch) admit(r);
1009            else solo(r);
1010            // FNX_ADMIT_INTERLEAVE=1 (default off): a request read takes the engine for 0.2-0.5 s even for a few tokens; the slots already decoding run one window between two
1011            // admissions instead of waiting for all of them (8 users that start together: the first ones decode while the last are read)
1012            if (batch && interleave_ && any_decoding()) decode_step();
1013        }
1014    }
1015    const bool interleave_ = fnx::env_int("FNX_ADMIT_INTERLEAVE", 0) != 0;   // off: measured no gain on 4 x R9700 (RESULTS-HIP.md section 8)
1016};
1017
1018// FNX_ROUTE_COUNT and FNX_ROUTE_TRACE (measurements) each need their file's path: checked before the model loads, not
1019// at the first reply
1020void check_route_env() {
1021    if (fnx::env_flag("FNX_ROUTE_COUNT") && !std::getenv("FNX_ROUTE_FILE")) throw std::runtime_error("FNX_ROUTE_COUNT needs FNX_ROUTE_FILE");
1022    if (fnx::env_int("FNX_ROUTE_TRACE", 0) > 0 && !std::getenv("FNX_ROUTE_TRACE_FILE"))
1023        throw std::runtime_error("FNX_ROUTE_TRACE needs FNX_ROUTE_TRACE_FILE");
1024}
1025
1026// SFNX_TEST_PROMPT replaces every text request's tokens: it starts only beside SFNX_TEST_PROMPT_CONFIRM=1, so the one
1027// variable leaking into a service's environment cannot turn every answer into the test prompt's
1028void check_test_prompt() {
1029    const char* tp = std::getenv("SFNX_TEST_PROMPT");
1030    if (!tp) return;
1031    const char* ok = std::getenv("SFNX_TEST_PROMPT_CONFIRM");
1032    if (!ok || std::string(ok) != "1")
1033        throw std::runtime_error(std::string("SFNX_TEST_PROMPT=") + tp + " replaces every text request's tokens (measurements only): set "
1034                                 "SFNX_TEST_PROMPT_CONFIRM=1 beside it, or unset it");
1035    std::fprintf(stderr, "sfnx: SFNX_TEST_PROMPT: every text request reads %s instead of its own tokens\n", tp);
1036}
1037
1038float half_bits_to_float(uint16_t h) {
1039    const uint32_t sign = (uint32_t) (h & 0x8000u) << 16;
1040    uint32_t e = (h >> 10) & 0x1f, mant = h & 0x3ffu, bits;
1041    if (e == 0) {
1042        if (mant == 0) bits = sign;
1043        else {   // subnormal
1044            e = 127 - 15 + 1;
1045            while (!(mant & 0x400u)) mant <<= 1, --e;
1046            bits = sign | (e << 23) | ((mant & 0x3ffu) << 13);
1047        }
1048    } else if (e == 31) bits = sign | 0x7f800000u | (mant << 13);
1049    else bits = sign | ((e + 127 - 15) << 23) | (mant << 13);
1050    float f;
1051    std::memcpy(&f, &bits, 4);
1052    return f;
1053}
1054
1055// DFlash2 (src/df2_bridge.hpp): the pack, the draft vocabulary's rows of output.weight and the embedding of a token (the model's Q8_0 rows, dequantized as
1056// Engine::embed_token does) handed to the bridge, which puts them on the first card
1057void load_dflash2(fnx::df2::Bridge& br, const fnx::Model& m, const Args& a) {
1058    std::vector<int32_t> vocab;
1059    {
1060        std::FILE* f = std::fopen(a.draft_vocab.c_str(), "rb");
1061        if (!f) throw std::runtime_error("dflash2: cannot open the draft vocabulary " + a.draft_vocab);
1062        int32_t id;
1063        while (std::fread(&id, 4, 1, f) == 1) vocab.push_back(id);
1064        std::fclose(f);
1065        if (vocab.empty()) throw std::runtime_error("dflash2: " + a.draft_vocab + " is empty");
1066        for (int32_t t : vocab)
1067            if (t < 0 || t >= m.vocab) throw std::runtime_error("dflash2: " + a.draft_vocab + " holds a token outside the vocabulary");
1068    }
1069    const fnx::Tensor* out = m.g.find("output.weight");
1070    if (!out || out->type != fnx::T_Q8_0) throw std::runtime_error("dflash2: output.weight is not Q8_0");
1071    const size_t rb = out->row_bytes();
1072    std::vector<uint8_t> rows(vocab.size() * rb);
1073    for (size_t i = 0; i < vocab.size(); ++i) std::memcpy(rows.data() + i * rb, out->data + (size_t) vocab[i] * rb, rb);
1074    const fnx::Tensor* te = m.tok_embd;
1075    auto embed = [te, &m](int tok, float* o) {
1076        if (tok < 0 || tok >= m.vocab) throw std::runtime_error("dflash2: embedding of token " + std::to_string(tok));
1077        const uint8_t* row = te->data + (size_t) tok * te->row_bytes();
1078        for (int b = 0; b < fnx::N / 32; ++b) {
1079            uint16_t dh;
1080            std::memcpy(&dh, row + b * 34, 2);
1081            const float d = half_bits_to_float(dh);
1082            for (int j = 0; j < 32; ++j) o[b * 32 + j] = d * (float) (int8_t) row[b * 34 + 2 + j];
1083        }
1084    };
1085    std::string err;
1086    if (!br.load(a.draft_model, m.cards[0].dev, a.batch, vocab, rows.data(), rb, 8, embed, err)) throw std::runtime_error(err);
1087    std::fprintf(stderr, "sfnx: DFlash2 on card 0: %zu draft tokens, %d drafter(s), %.0f MiB of VRAM\n", vocab.size(), br.lanes(), (double) br.vram_bytes() / 1048576.0);
1088}
1089
1090// the engine state after a failure part way is unknown: say why and _exit at once (the front end starts it again). No
1091// destructors: freeing the conversation cache's pinned memory takes minutes, and the stdin reader thread keeps the
1092// process up, while the front end waits for the ERR line or EOF
1093[[noreturn]] void fail(const std::exception& ex) {
1094    say(std::string("ERR ") + ex.what());
1095    std::fprintf(stderr, "sfnx: failed: %s\n", ex.what());
1096    std::fflush(stdout);
1097    std::fflush(stderr);
1098    std::_Exit(1);
1099}
1100
1101}  // namespace
1102
1103int main(int argc, char** argv) {
1104    Args a;
1105    try {
1106        a = parse_args(argc, argv);
1107        check_route_env();
1108        check_test_prompt();
1109    } catch (const std::exception& e) {
1110        std::fprintf(stderr, "sfnx: %s\n", e.what());
1111        return 2;
1112    }
1113    const auto t_load = std::chrono::steady_clock::now();
1114    // made in place and failed like the rest, so a card or link refused at load ends with its reason too
1115    std::optional<fnx::Model> m;
1116    std::optional<fnx::Mtp> mtp;
1117    std::optional<fnx::df2::Bridge> df2;
1118    std::optional<fnx::Engine> e;
1119    try {
1120        m.emplace(a.gguf.c_str());
1121        if (a.draft == "dflash2") {
1122            df2.emplace();
1123            load_dflash2(*df2, *m, a);   // before the Engine: it sizes its K/V pool from what is left on the cards
1124        } else {
1125            mtp.emplace(*m, a.mtp_dir, a.draft_vocab);
1126        }
1127        e.emplace(*m, a.max_ctx, a.batch);
1128        if (mtp) e->mtp_attach(*mtp);
1129        else e->df2_attach(*df2);
1130    } catch (const std::exception& ex) {
1131        fail(ex);
1132    }
1133    Input in;
1134    try {
1135        Server srv(a, *m, *e, in);
1136        std::string vfree;   // each card's, "a / b / c"
1137        for (const long v : e->free_vram_mib()) vfree += (vfree.empty() ? "" : " / ") + std::to_string(v);
1138        std::fprintf(stderr,
1139                     "sfnx: loaded in %.1f s, context %d, MTP K=%d, lookup %d, %d slot(s); %d cards, sums between them %s; K/V pool "
1140                     "(%s) %d positions free; VRAM free %s MiB\n",
1141                     std::chrono::duration<double>(std::chrono::steady_clock::now() - t_load).count(), a.max_ctx, a.K, a.lookup, a.batch,
1142                     fnx::NCARD, fnx::ring_f32() ? "fp32" : "fp16",
1143#if FNX_27B
1144                     "f16", e->free_pages() * fnx::S27_PP, vfree.c_str());
1145#else
1146                     fnx::kv_q8() ? "int8" : "f16", e->free_pages() * fnx::KVP_POS, vfree.c_str());
1147#endif
1148        if (fnx::NCARD > 3)
1149            std::fprintf(stderr, "sfnx: %d cards builds and passes the CPU checks but has not been validated on hardware "
1150                                 "(docs/verification.md, \"Other card counts\")\n", fnx::NCARD);
1151        say("INFO engine=sfnx version=0.2 spec=" + std::to_string(a.K) + " conversation_cache_mib=" + std::to_string(a.cache_mib) +
1152            (a.batch > 1 ? " batch_slots=" + std::to_string(a.batch) + " slot_cache=1" : ""));
1153        say("READY " + std::to_string(a.max_ctx) + " stop");
1154        std::thread reader([&] { in.run(); });
1155        reader.detach();
1156        try {
1157            srv.run();
1158        } catch (const std::exception& ex) {
1159            fail(ex);
1160        }
1161    } catch (const std::exception& ex) {
1162        fail(ex);
1163    }
1164    std::fflush(stdout);
1165    std::_Exit(0);
1166}