okami.mom/strata

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

waveringanadsv41: conversation slots and SCR keep conversations with pictures - spans matched by picture hash (picspans::keyed), a slot's pictures in a .pics file, SCR moves or reads a picture's span whole24d897c06

main
15.8 KiB218 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_model.hpp - DeepSeek-V4.1-Flash on Maya: an EXL3 model (tools/ds4/pack.py's pack beside its files) over
4// the machine's GPUs, layer-split, with the routed experts that do not fit in VRAM on the CPU lane.
5//
6// Windows of up to 16 tokens through every layer (a prompt in windows, a decode step a window of one): each query of a
7// window sees exactly what the reference's decode path gives it (DeepSeek's inference/model.py at start_pos > 0) -
8// its own 128-token window, the compressed groups completed by its position.  The state a token leaves is the
9// 128-token window ring of every layer, the compressors' partial groups, the compressed KV and index keys of the KV
10// source layers (append-only), and the Engram n-gram history; checkpoint() / restore() keep the first two (the rest is
11// truncated by position) so a conversation can go back to the end of its last prompt.  A conversation that leaves the
12// model altogether (another chat answered in between) is a slot: slot_save / slot_load take the same state - the
13// compressed KV and index keys included, which a checkpoint leaves in place - through a file or a host buffer.
14#pragma once
15
16#include <cstddef>
17#include <cstdint>
18#include <functional>
19#include <memory>
20#include <string>
21#include <vector>
22
23namespace strata::ds4 {
24
25struct Options {
26    std::string pack;                 // <model>/maya-ds4
27    int64_t max_context = 32768;
28    std::vector<int> gpus;            // empty: every visible GPU
29    int64_t reserve_mib = 600;        // VRAM left free on each GPU
30    double vram_experts = 1.0;        // the share of the expert budget to use (tests: less, so the CPU lane works)
31    int cpu_threads = 0;              // 0: the physical cores
32    std::string profile;              // expert hit counts (read to place the hottest experts in VRAM, written back)
33    bool expert_cache = true;         // experts move between VRAM and the CPU lane as they are used
34    // the CPU lane's experts read in place from the model's files, the page cache keeping what fits, instead of
35    // copied into RAM: 1 on, 0 off, -1 (auto) where the RAM this process can get does not hold them
36    int mmap_experts = -1;
37    // the experts the VRAM leaves over are cached in RAM by a store of their own (ds4_store.hpp): whole experts read unbuffered into
38    // slots, a replacement policy (0 lru, 1 lfu, 2 lfu then lru), filled on demand and by the lookahead's guesses.  GB of RAM at
39    // most (never past the RAM the process can still get less 8 GB); 0: off, the OS page cache as before
40    double ssd_cache_gb = -1.0;   // < 0: auto (the RAM the process can get less a floor, at most 48 GB; off below 4 GB), 0: off
41    int ssd_policy = 0;
42    // dspark_auto: the drafter is loaded only where the routed experts fit the GPUs (more than 1.5x what they have, the verify rounds
43    // read 3.3x the bytes of a token and measured no faster than plain decoding, and the drafter's 7 GB of experts take the VRAM the
44    // trunk's hottest would have had); --dspark on / off / none says it outright
45    // experts a word takes: -1 the rule (5 where the cards hold 16 GiB or less in all, else the model's 6), N the router's top N with
46    // their weights renormalised (--experts 6: full quality); ds4_experts_rule.hpp
47    int experts = -1;
48    bool dspark_auto = true;
49    bool dspark = true;              // load the DSpark drafter (the checkpoint's mtp.* blocks) for speculative decoding
50    int dspark_block = 0;             // at most this many drafts a round (--dspark-block N; 0: the pack's block size)
51    float dspark_conf = 0.5f;         // a draft is verified while its confidence (sigmoid) is at least this
52    // verify() without the drafter: the window backups a verification rolls back from (drafts from elsewhere, DS4_SUFFIX_DRAFT)
53    bool spec_buffers = false;
54    // tensor parallelism: runs of tp GPUs of one kind (the same memory) take the same layers, each a share of the
55    // heads, of the output projection and of every expert's FFN, summed through host-mapped memory (a GPU unlike the
56    // next stays alone); tp > 1 runs with threads (--tp 1 --threads off: one host thread, layer split only)
57    int tp = 2;
58    bool threads = false;             // a host thread per GPU enqueues its layers (the hand-offs host-mapped)
59    // prompts in chunks of this many tokens through each layer at once (threads): the GEMMs on the tensor cores, the
60    // CPU lane's experts streamed to the GPUs a chunk at a time instead of computed on the host; 0: windows of 16;
61    // -1: 2048, or 8192 with the experts read in place (every chunk streams them all from the files)
62    int prefill_chunk = -1;
63    bool vision = true;               // the vision tower (the checkpoint's vision.* / aligner.*), when it has one
64    bool vision_only = false;         // (tests) load the vision tower alone: encode_image() and nothing else
65    bool verbose = false;
66};
67
68/// A picture in the prompt: its span's rows (every position of the span carries the image token), BF16 [span][dim]
69struct Image {
70    int64_t start = 0;
71    std::shared_ptr<const std::vector<uint16_t>> rows;
72};
73
74struct Stats {
75    int64_t tokens = 0;
76    int64_t experts = 0, cpu_experts = 0;   // routed experts run, and how many of them on the CPU lane
77    int64_t aux_experts = 0;                // (DS4_AUX_GPU) of the CPU lane's picks, the expert GPU's
78    int64_t aux_swaps = 0;                  // (DS4_AUX_CACHE) experts moved onto the expert GPU
79    double cpu_ms = 0.0, gpu_wait_ms = 0.0;   // the CPU lane's time; the host's waits for the routing
80    double layer_ms = 0.0, head_ms = 0.0, engram_ms = 0.0;   // the layers' host time in all; the head's wait; Engram reads
81    int64_t eg_rows = 0, eg_hits = 0, eg_reads = 0;   // Engram rows asked for, served without a read, read from the files
82    double eg_io_ms = 0.0;                            // the windows' Engram reads, issue to last done (mostly hidden)
83    int64_t eg_cached = 0, eg_cache_cap = 0;          // the row cache's rows held, its capacity
84    int64_t swaps = 0;                // experts the cache moved into VRAM
85    int64_t skipped = 0;              // routed experts STRATA_DS4_DISK_SKIP_W left out (light, not in RAM)
86    int64_t ram_experts = 0, ram_moves = 0;   // CPU-lane experts read from the RAM tier; experts moved into it
87    double prof_ms[6] = {};          // DS4_PROF: the GPU's time in decode by stage (between layers, attention, routing +
88    int64_t prof_tokens = 0;         // shared expert, experts' gate / up, the wait for the CPU lane, down + post)
89    // lookahead (decode windows of one): the picks of layers guessed a layer before (the next layer's gate on this
90    // layer's FFN input), of them in the guess's top k / in all its guesses / in the guess two layers before; the picks
91    // read from the files, of them prefetched early; experts prefetched early
92    int64_t ahead_picks = 0, ahead_hit_k = 0, ahead_hit = 0, ahead_hit2 = 0;
93    int64_t ahead_cold = 0, ahead_cold_hit = 0, ahead_pf = 0;
94    int64_t ahead_rank_n[16] = {}, ahead_rank_hit[16] = {};   // the next-layer guesses by rank, and how many were picked
95    // the RAM store (--ssd-cache), totals since the load: reads asked for and found there (hits), missed (misses), started ahead
96    // of use (prefetched) of which used / given up unused, slots given up, bytes read, ms the CPU lane waited for the reads
97    int64_t store_hits = 0, store_misses = 0, store_prefetched = 0, store_pf_used = 0, store_pf_wasted = 0, store_evictions = 0;
98    int64_t store_bytes = 0, store_fails = 0;
99    int64_t store_zc = 0, store_zc_visible = 0;   // experts the GPU computed from the store (zero-copy over PCIe); slots it may read
100    double store_wait_ms = 0.0, store_busy_ms = 0.0;
101    // decode picks by where the expert was: VRAM, the expert GPU, the store's GPU-visible slot, the CPU lane from a ready store
102    // slot, from a store read in flight (a guess not landed yet), from no slot (a read now)
103    int64_t tier[6] = {};
104    int64_t store_slots = 0, store_slots_max = 0;
105    int64_t drafts_offered = 0, drafts_accepted = 0, drafts_rounds = 0;
106    // per draft position (the 1st .. 8th of a round): verified with all the drafts before it accepted, and accepted
107    int64_t draft_reached[8] = {}, draft_kept[8] = {};
108    double draft_ms = 0.0, verify_ms = 0.0;   // the drafter's time, the verification windows' time
109};
110
111class Model {
112public:
113    Model();
114    ~Model();
115    bool load(const Options& o, std::string& err);
116
117    /// Feeds `token` at position pos(); with logits, the next token's logits are left on the head's device.
118    bool step(int token, bool logits, std::string& err);
119    /// Feeds n tokens (windows of up to 16, or a long run in chunks of prefill_chunk); the last `logits_rows` of them get
120    /// logits (logits_rows > 16: only a run of one chunk or window).
121    bool feed(const int* tokens, int n, int logits_rows, std::string& err);
122    /// feed() of a prompt's end that also keeps the state before its last token in checkpoint `slot` (a prompt's
123    /// last token then rides along in the run of chunks instead of a window of its own); the same as
124    /// feed(n - 1), checkpoint(slot), feed(1)
125    bool feed_mark(const int* tokens, int n, int logits_rows, int slot, std::string& err);
126    /// The next token from the last feed's last logit row (greedy when temperature <= 0).
127    int sample(float temperature, float top_p, int top_k, float min_p, uint64_t seed, uint64_t counter);
128    /// The last feed's logit rows on the host (rows x vocab floats).
129    bool logits(std::vector<float>& out);
130
131    /// The DSpark drafter (speculative decoding): its block size (0: not loaded), drafts for the positions after `y`
132    /// (y: the token at pos(), not fed yet) with their confidences, and the verification of [y, drafts]: how many of the
133    /// drafts stand and the token after them (the state then holds y and the accepted drafts).  The drafts are the
134    /// drafter's argmax; a sampled request passes its chain (the same temperature / top_p / top_k / min_p / seed /
135    /// counter as its verify()) so that with DS4_DSPARK_SAMPLE=1 they are drawn from the drafter's distribution, as
136    /// DeepSeek's reference does.  verify() keeps a draft d with probability min(1, p(d) / q(d)) over the request's
137    /// chain - the speculative-sampling rule, so every token is still distributed as the model's own draw.
138    int draft_block() const;
139    bool draft(int y, std::vector<int>& drafts, std::vector<float>& conf, std::string& err, float temperature = 0.0f,
140               float top_p = 1.0f, int top_k = 0, float min_p = 0.0f, uint64_t seed = 0, uint64_t counter = 0);
141    bool verify(int y, const std::vector<int>& drafts, float temperature, float top_p, int top_k, float min_p,
142                uint64_t seed, uint64_t counter, int& accepted, int& next, std::string& err);
143
144    /// Tokens a feed call takes at a time to use the chunked prompt path (all of a prompt: its chunks run as a
145    /// pipeline; 16 without it).
146    int feed_unit() const;
147    /// Called from feed() while a run of chunks goes through the layers, with the tokens done so far.
148    void set_progress(std::function<void(int64_t)> f);
149    /// Asked while a run of chunks goes through the layers: true (a Stop) ends it early - one GPU after the layer it is
150    /// on, several at a chunk all of them reach - and feed() returns false with cancelled() true.  The state past the
151    /// prompt's start is then not usable: restore() a checkpoint kept before the feed, or reset().
152    void set_cancel(std::function<bool()> f);
153    bool cancelled() const;   // the last feed() / feed_mark() ended early on a Stop
154    int64_t pos() const;
155    int64_t max_context() const;
156    int vocab() const;
157    int dim() const;
158    const std::vector<int32_t>& tokens() const;   // what the state has consumed, in order
159
160    struct ScrMove { int64_t old_start, at, n; };
161    // 1 moved; 0 refused without mutation; -1 failed after writes (the caller must reset).
162    int scr_relocate(const std::vector<ScrMove>& moves, std::string& err);
163    // Adopt ids up to the even position `at` (its compressed rows in place), empty the window rings and compressor
164    // groups, and keep the window rows before `at` out of the attention (the junction band read next).
165    bool scr_jump(const std::vector<int>& ids, int64_t at, std::string& err, int64_t keep = 0);   // (keep: checkpoints at or before it stay)
166    void reset();
167    /// Keep the state at the current position in checkpoint slot 0 or 1 (the end of a prompt, the position before it);
168    /// restore(limit) goes back to the latest one at or before limit (-1: none).
169    void checkpoint(int slot = 0);
170    bool restore(int64_t limit);
171    int64_t restorable(int64_t limit) const;
172    /// Checkpoint 1 also becomes the anchor (kept until a restore goes before it): the position before the end of the
173    /// first prompt of a run that continued in place, where a re-rendered history (earlier reasoning dropped) splits.
174    void pin();
175    /// The positions restore() can go back to, latest first (a slot keeps them: it can be taken back at any of them).
176    std::vector<int64_t> check_positions() const;
177
178    /// The conversation in the model into `out` (slot_save): its position, its tokens, every window ring (the DSpark
179    /// blocks' included), the compressors' partial groups and each KV source's compressed KV and index keys up to it,
180    /// the pieces the state a prompt continues is made of.  0 and err: nothing was set aside (it holds pictures, there
181    /// is no conversation, or the conversation is already set aside - unchanged since).
182    uint64_t slot_save(std::vector<uint8_t>& out, std::string& err);
183    /// `data` (a slot's bytes) back into the model: the state at the slot's position n_pos, as slot_save took it -
184    /// what a prompt that continues the slot's tokens reads on from (the caller checked the tokens are a prefix).
185    bool slot_load(const uint8_t* data, size_t bytes, int64_t n_pos, std::string& err);
186    /// What a saved conversation must match: this engine's version, this model's geometry and files and the drafter's
187    /// blocks - a slot naming anything else is not this model's state (a file's .meta says so; slot_load refuses).
188    std::string slot_identity() const;
189
190    /// The vision tower: the token every position of an image's span carries (-1: no tower).
191    int image_token() const;
192    /// An image's pixels (RGB rows, width x height, both multiples of the patch size: the server's resize) -> the
193    /// rows of its span, BF16 [n_h * (n_w + 1) + 2][dim]: image_start, n_h rows of (n_w aligner rows, image_newline),
194    /// image_end.
195    bool encode_image(const uint8_t* rgb, int width, int height, std::vector<uint16_t>& span, std::string& err);
196    /// The pictures of the prompt about to be fed ({}: none): positions inside a span read its rows (and route with
197    /// the image bias, and take no part in the Engram n-grams); the rest the embedding table's.
198    void set_images(std::vector<Image> images);
199    /// The state's pictures, (start, length) spans, when its tokens came back without their rows (a kept
200    /// conversation, an SCR jump): their positions take no part in the Engram n-grams, as when they were read.
201    void mark_images(const std::vector<std::pair<int64_t, int64_t>>& spans);
202
203    void save_profile() const;
204    /// DS4_TIERDUMP: each layer's experts by tier into `path` (a line a layer: its index, then a char an expert - V VRAM, A the
205    /// expert GPU, Z a GPU-visible store slot, S a ready store slot, L a store read in flight, . none)
206    void tier_dump(const std::string& path) const;
207    const Stats& stats() const;
208    std::string describe() const;
209    /// INFO / VRAM lines for the server's Monitor.
210    std::vector<std::string> info_lines() const;
211
212    struct Impl;
213
214private:
215    std::unique_ptr<Impl> p_;
216};
217
218}  // namespace strata::ds4