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
584.6 KiB10620 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.cu - DeepSeek-V4.1-Flash on Maya (see ds4_model.hpp).
4//
5// The layer, for one token at position p (DeepSeek's inference/model.py, Block.forward with the lagged pre-mix):
6//   [Engram, layers 1 and 14]  h += gate(h, key) * value from 24 n-gram rows of the FP8 tables
7//   a_pre, a_post, a_comb = hc_mixes(h);  x = rmsnorm(sum_s pre[s] h[s])   (pre: the previous layer's f_pre)
8//   attention(x): q from the low-rank wq_a / wq_b, one shared K = V row per token in a 128-slot window ring, plus
9//                 (compress ratio > 0) up to 512 compressed rows the indexer picks; a learned sink per head; the
10//                 output's rotary part rotated back, rounded to FP8, through the grouped wo_a and wo_b
11//   h = post * attn + comb^T h;  f_* = hc_mixes(h);  x = rmsnorm(sum_s a_pre[s] h[s])
12//   moe(x): 6 of 384 routed experts (sqrt-softplus scores, biased top-k) + the shared expert
13//   h = post * moe + comb^T h;  pre = f_pre
14// and after the last layer logits = head(rmsnorm(sum_s pre[s] h[s])).
15#include "ds4_model.hpp"
16#include "ds4_pick_rule.hpp"
17#include "ds4_experts_rule.hpp"
18#include "ds4_engram_io.hpp"
19
20#include "ds4_gguf.cuh"
21#include "ds4_iq.cuh"
22#include "ds4_gguf_cpu.hpp"
23#include "ds4_kernels.cuh"
24#include "ds4_os.hpp"
25#include "ds4_pool.hpp"
26#include "ds4_store.hpp"
27#include "ds4_vision.cuh"
28#include "strata/dsv41/exl3_cpu.hpp"
29#include "strata/dsv41/exl3.hpp"
30#include "strata/kernels/f16_bits.hpp"
31#include "strata/dsv41/moe_win.hpp"
32#include "strata/dsv41/sampler.hpp"
33
34#include <cublas_v2.h>
35#include <cuda_runtime.h>
36
37#include <algorithm>
38#include <array>
39#include <condition_variable>
40#include <deque>
41#include <atomic>
42#include <chrono>
43#include <climits>
44#include <cmath>
45#include <cstdio>
46#include <cstdlib>
47#include <cstring>
48#include <filesystem>
49#include <fstream>
50#include <functional>
51#include <future>
52#include <map>
53#include <mutex>
54#include <numeric>
55#include <sstream>
56#include <thread>
57#include <unordered_map>
58
59#if defined(_MSC_VER)
60#define strtok_r strtok_s
61#endif
62
63namespace strata::ds4 {
64namespace x3 = strata::dsv41k::exl3;
65namespace kc = strata::dsv41k::cpu;
66namespace gf = strata::dsv41k::glmf;
67namespace gg = strata::ds4::gguf;
68
69#define CK(call)                                                                            \
70    do {                                                                                    \
71        cudaError_t e_ = (call);                                                            \
72        if (e_ != cudaSuccess) {                                                            \
73            err = std::string(#call) + ": " + cudaGetErrorString(e_);                       \
74            return false;                                                                   \
75        }                                                                                   \
76    } while (0)
77
78namespace {
79
80double now_ms() {
81    return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count();
82}
83
84size_t align256(size_t n) { return (n + 255) & ~(size_t) 255; }
85
86// part p of np of `whole` (a multiple of 128) in 128-blocks, as even as they go (whole / 128 % np parts a block more:
87// those from part rot on, cyclically - so a group's layers, each its own rot, even out what each member holds):
88// tensor parallel's columns of an FFN or of the head - an even split is what whole / np gave before
89void split128(int whole, int np, int p, int& off, int& n, int rot = 0) {
90    const int b = whole / 128, q = b / np, r = b % np;
91    auto blocks = [&](int i) { return q + (((i - rot) % np + np) % np < r ? 1 : 0); };
92    int at = 0;
93    for (int i = 0; i < p; ++i) at += blocks(i);
94    off = 128 * at;
95    n = 128 * blocks(p);
96}
97
98std::string read_file(const std::string& p) {
99    std::ifstream f(p);
100    std::stringstream ss;
101    ss << f.rdbuf();
102    return ss.str();
103}
104std::vector<int> cpu_list(const std::string& s) {   // "0-3,8,10-11"
105    std::vector<int> v;
106    std::stringstream ss(s);
107    std::string part;
108    while (std::getline(ss, part, ',')) {
109        if (part.empty() || part == "\n") continue;
110        const size_t dash = part.find('-');
111        const int a = std::atoi(part.c_str());
112        const int b = dash == std::string::npos ? a : std::atoi(part.c_str() + dash + 1);
113        for (int c = a; c <= b; ++c) v.push_back(c);
114    }
115    return v;
116}
117// each NUMA node's physical cores (the first logical CPU of each core), in order
118std::vector<std::vector<int>> node_cores() {
119#if defined(_WIN32)
120    static const bool smt = [] {   // DS4_CPU_SMT=1: the second hardware thread of every core as well (memory-bound rows gain from it)
121        const char* v = std::getenv("DS4_CPU_SMT");
122        return v != nullptr && std::atoi(v) != 0;
123    }();
124    std::vector<std::vector<int>> nodes = os::node_cores(smt);
125#else
126    std::vector<std::vector<int>> nodes;
127    for (int n = 0; n < 64; ++n) {
128        const std::string cl = read_file("/sys/devices/system/node/node" + std::to_string(n) + "/cpulist");
129        if (cl.empty()) break;
130        std::vector<int> cores;
131        for (int c : cpu_list(cl)) {
132            const std::vector<int> sib = cpu_list(
133                read_file("/sys/devices/system/cpu/cpu" + std::to_string(c) + "/topology/thread_siblings_list"));
134            if (sib.empty() || sib[0] == c) cores.push_back(c);
135        }
136        if (!cores.empty()) nodes.push_back(cores);
137    }
138#endif
139    if (nodes.empty()) {
140        std::vector<int> all;
141        for (unsigned c = 0; c < std::max(1u, std::thread::hardware_concurrency() / 2); ++c) all.push_back((int) c);
142        nodes.push_back(all);
143    }
144    return nodes;
145}
146// anonymous memory on one NUMA node (node < 0: wherever the first touch puts it), transparent huge pages
147void* node_map(size_t bytes, int node, int n_nodes) { return os::anon_alloc(bytes, node, n_nodes); }
148void pin_self(int cpu) { os::pin_self(cpu); }
149// the RAM this process can still get: MemAvailable, and below it the tightest cgroup v2 limit on the way to the root
150// (its limit less what is charged, the page cache counted as free: the kernel takes it back); ~0: not known
151uint64_t ram_avail() {
152#if defined(_WIN32)
153    return os::ram_avail();
154#endif
155    uint64_t avail = ~uint64_t{0};
156    {
157        std::istringstream mi(read_file("/proc/meminfo"));
158        std::string k;
159        uint64_t kb = 0;
160        while (mi >> k >> kb) {
161            if (k == "MemAvailable:") avail = kb << 10;
162            mi.ignore(64, '\n');
163        }
164    }
165    std::string cg = read_file("/proc/self/cgroup");   // "0::/user.slice/..."
166    const size_t at = cg.find("0::");
167    if (at == std::string::npos) return avail;
168    cg = cg.substr(at + 3);
169    cg = cg.substr(0, cg.find('\n'));
170    for (;;) {
171        const std::string dir = "/sys/fs/cgroup" + (cg == "/" ? std::string() : cg);
172        const std::string mx = read_file(dir + "/memory.max");
173        if (!mx.empty() && mx.compare(0, 3, "max") != 0) {
174            const uint64_t lim = std::strtoull(mx.c_str(), nullptr, 10);
175            const uint64_t cur = std::strtoull(read_file(dir + "/memory.current").c_str(), nullptr, 10);
176            uint64_t file = 0;
177            std::istringstream st(read_file(dir + "/memory.stat"));
178            std::string k;
179            uint64_t v = 0;
180            while (st >> k >> v)
181                if (k == "file") file = v;
182            const uint64_t used = cur > file ? cur - file : 0;
183            avail = std::min(avail, lim > used ? lim - used : 0);
184        }
185        if (cg.empty() || cg == "/") break;
186        const size_t sl = cg.rfind('/');
187        cg = sl == 0 || sl == std::string::npos ? "/" : cg.substr(0, sl);
188    }
189    return avail;
190}
191
192float bf16_to_f32(uint16_t b) {
193    uint32_t u = (uint32_t) b << 16;
194    float f;
195    std::memcpy(&f, &u, 4);
196    return f;
197}
198float f16_to_f32(uint16_t h) {
199    const uint32_t s = (uint32_t) (h >> 15) << 31, e = (h >> 10) & 0x1f, m = h & 0x3ff;
200    uint32_t u;
201    if (e == 0) {
202        if (m == 0) u = s;
203        else {   // subnormal
204            int ee = -1;
205            uint32_t mm = m;
206            do {
207                ++ee;
208                mm <<= 1;
209            } while ((mm & 0x400) == 0);
210            u = s | (uint32_t) (127 - 15 - ee) << 23 | (mm & 0x3ff) << 13;
211        }
212    } else if (e == 31) u = s | 0x7f800000u | m << 13;
213    else u = s | (e - 15 + 127) << 23 | m << 13;
214    float f;
215    std::memcpy(&f, &u, 4);
216    return f;
217}
218
219// ------------------------------------------------------------------ the pack
220struct Tensor {
221    std::string dtype;
222    int file = -1;
223    uint64_t off = 0, bytes = 0;
224    std::vector<int64_t> shape;
225};
226
227struct Pack {
228    std::string dir, model_dir;
229    std::unordered_map<std::string, std::string> kv;
230    std::vector<std::string> files;
231    std::vector<os::fd_t> fds;
232    std::unordered_map<std::string, Tensor> t;
233    int eg_vocab = 0, eg_layers = 0, eg_ngram = 0, eg_heads = 0, eg_hd = 0, eg_pad = 0;
234    std::vector<int32_t> eg_map;
235    std::vector<int64_t> eg_mult, eg_primes, eg_off;
236    // format gguf (tools/ds4/pack_gguf.py): the files are a GGUF's shards, every one mapped at load (map()) - the
237    // routed experts are always read in place (the OS page cache their RAM tier, the disk the rest)
238    bool gguf = false;
239
240    std::vector<std::pair<uint8_t*, size_t>> maps;   // file -> its read-only mapping (map(): the experts in place)
241    std::vector<os::fd_t> dfds;   // (gguf) file -> unbuffered (os::open_direct; kBadFd: buffered reads only)
242    std::vector<os::fd_t> pfds;   // (gguf) file -> for reads from many threads at once (os::open_par)
243
244    ~Pack() {
245        for (auto& m : maps) os::unmap(m.first, m.second);
246        for (os::fd_t fd : fds) os::close_fd(fd);
247        for (os::fd_t fd : dfds) os::close_fd(fd);
248        for (os::fd_t fd : pfds) os::close_fd(fd);
249    }
250    // file i mapped whole, read-only (once; not thread-safe: called while loading)
251    const uint8_t* map(int file) {
252        if (maps.size() < fds.size()) maps.resize(fds.size(), {nullptr, 0});
253        auto& m = maps[(size_t) file];
254        if (m.first == nullptr) {
255            const uint64_t size = os::file_size(fds[(size_t) file]);
256            void* p = os::map_ro(fds[(size_t) file], size);
257            if (p == nullptr) return nullptr;
258            m = {(uint8_t*) p, (size_t) size};
259        }
260        return m.first;
261    }
262
263    bool load(const std::string& d, std::string& err) {
264        dir = d;
265        {
266            std::ifstream f(d + "/ds4.txt");
267            if (!f) {
268                err = d + "/ds4.txt: not found (run tools/ds4/pack.py --model <model>)";
269                return false;
270            }
271            std::string line;
272            while (std::getline(f, line)) {
273                const size_t sp = line.find(' ');
274                if (sp == std::string::npos) continue;
275                kv[line.substr(0, sp)] = line.substr(sp + 1);
276            }
277        }
278        model_dir = str("model_dir");
279        std::FILE* f = std::fopen((d + "/tensors.txt").c_str(), "r");
280        if (f == nullptr) {
281            err = d + "/tensors.txt: not found";
282            return false;
283        }
284        std::vector<char> buf(1 << 16);
285        while (std::fgets(buf.data(), (int) buf.size(), f) != nullptr) {
286            char* s = buf.data();
287            if (s[0] == 'f') {   // file <i> <name>
288                char name[4096];
289                int i = 0;
290                if (std::sscanf(s, "file %d %4095s", &i, name) == 2) {
291                    if ((int) files.size() <= i) files.resize((size_t) i + 1);
292                    files[(size_t) i] = name;
293                }
294                continue;
295            }
296            if (s[0] != 't') continue;
297            char* save = nullptr;
298            ::strtok_r(s, " \n", &save);
299            const char* name = ::strtok_r(nullptr, " \n", &save);
300            const char* dt = ::strtok_r(nullptr, " \n", &save);
301            const char* fi = ::strtok_r(nullptr, " \n", &save);
302            const char* off = ::strtok_r(nullptr, " \n", &save);
303            const char* nb = ::strtok_r(nullptr, " \n", &save);
304            if (name == nullptr || nb == nullptr) continue;
305            Tensor x;
306            x.dtype = dt;
307            x.file = std::atoi(fi);
308            x.off = std::strtoull(off, nullptr, 10);
309            x.bytes = std::strtoull(nb, nullptr, 10);
310            while (const char* dim = ::strtok_r(nullptr, " \n", &save)) x.shape.push_back(std::atoll(dim));
311            t.emplace(name, std::move(x));
312        }
313        std::fclose(f);
314        for (const std::string& fn : files) {
315            const std::string p = model_dir + "/" + fn;
316            const os::fd_t fd = os::open_ro(p);
317            if (fd == os::kBadFd) {
318                err = p + ": cannot open";
319                return false;
320            }
321            fds.push_back(fd);
322        }
323        gguf = str("format") == "gguf";
324        if (gguf)
325            for (size_t i = 0; i < fds.size(); ++i) {
326                if (map((int) i) == nullptr) {
327                    err = model_dir + "/" + files[i] + ": cannot map";
328                    return false;
329                }
330                dfds.push_back(os::open_direct(model_dir + "/" + files[i]));
331                pfds.push_back(os::open_par(model_dir + "/" + files[i]));
332            }
333        // the Engram tables
334        std::FILE* e = std::fopen((d + "/engram.bin").c_str(), "rb");
335        if (e == nullptr) {
336            err = d + "/engram.bin: not found";
337            return false;
338        }
339        char magic[4];
340        int32_t hdr[6];
341        bool ok = std::fread(magic, 1, 4, e) == 4 && std::memcmp(magic, "DSE1", 4) == 0 &&
342                  std::fread(hdr, 4, 6, e) == 6;
343        if (ok) {
344            eg_vocab = hdr[0], eg_layers = hdr[1], eg_ngram = hdr[2], eg_heads = hdr[3], eg_hd = hdr[4], eg_pad = hdr[5];
345            const int cols = (eg_ngram - 1) * eg_heads;
346            eg_map.resize((size_t) eg_vocab);
347            eg_mult.resize((size_t) eg_layers * eg_ngram);
348            eg_primes.resize((size_t) eg_layers * cols);
349            eg_off.resize((size_t) eg_layers * cols);
350            ok = std::fread(eg_map.data(), 4, eg_map.size(), e) == eg_map.size() &&
351                 std::fread(eg_mult.data(), 8, eg_mult.size(), e) == eg_mult.size() &&
352                 std::fread(eg_primes.data(), 8, eg_primes.size(), e) == eg_primes.size() &&
353                 std::fread(eg_off.data(), 8, eg_off.size(), e) == eg_off.size();
354        }
355        std::fclose(e);
356        if (!ok) {
357            err = d + "/engram.bin: unreadable";
358            return false;
359        }
360        return true;
361    }
362
363    std::string str(const std::string& k, const std::string& def = "") const {
364        auto it = kv.find(k);
365        return it == kv.end() ? def : it->second;
366    }
367    double num(const std::string& k, double def) const {
368        auto it = kv.find(k);
369        return it == kv.end() ? def : std::atof(it->second.c_str());
370    }
371    std::vector<int> list(const std::string& k) const {
372        std::vector<int> v;
373        std::stringstream ss(str(k));
374        std::string x;
375        while (std::getline(ss, x, ','))
376            if (!x.empty()) v.push_back(std::atoi(x.c_str()));
377        return v;
378    }
379    const Tensor* get(const std::string& n) const {
380        auto it = t.find(n);
381        return it == t.end() ? nullptr : &it->second;
382    }
383    bool read_at(int file, uint64_t off, uint64_t n, void* dst) const {   // (any thread; side by side where pfds is)
384        if ((size_t) file < pfds.size() && pfds[(size_t) file] != os::kBadFd)
385            return os::pread_par(pfds[(size_t) file], dst, n, off);
386        return os::pread_full(fds[(size_t) file], dst, n, off);
387    }
388    bool read(const Tensor& x, void* dst) const { return read_at(x.file, x.off, x.bytes, dst); }
389    const uint8_t* at(int file, uint64_t off) const { return maps[(size_t) file].first + off; }   // (gguf: mapped)
390};
391
392// ------------------------------------------------------------------ geometry
393struct Geo {
394    int vocab = 0, dim = 0, nl = 0, heads = 0, hd = 0, rd = 0, q_lora = 0, o_lora = 0, o_groups = 0, n_exp = 0,
395        k_exp = 0, ff = 0, win = 0, hc = 0, sinkhorn = 0, ix_heads = 0, ix_hd = 0, ix_topk = 0, cand_src = -1,
396        cand_topk = 0, cand_blk = 0, orig_ctx = 0, eos = 1;
397    float eps = 1e-20f, hc_eps = 1e-6f, route_scale = 1.0f, lim = 0.0f;
398    double rope_theta = 1e4, comp_theta = 1e4, factor = 1.0, beta_fast = 32, beta_slow = 1;
399    std::vector<int> ratios, kv_src, ix_src, eg_layers;
400    // the DSpark drafter (the checkpoint's mtp.* blocks): a block of [seed, noise x (block - 1)] through n_mtp blocks
401    int n_mtp = 0, d_block = 0, d_noise = 0, d_rank = 0, d_n_exp = 0, d_k = 0;
402    std::vector<int> d_targets;
403
404    void from(const Pack& p) {
405        vocab = (int) p.num("vocab_size", 0), dim = (int) p.num("hidden_size", 0);
406        nl = (int) p.num("num_hidden_layers", 0), heads = (int) p.num("num_attention_heads", 0);
407        hd = (int) p.num("head_dim", 0), rd = (int) p.num("qk_rope_head_dim", 0);
408        q_lora = (int) p.num("q_lora_rank", 0), o_lora = (int) p.num("o_lora_rank", 0);
409        o_groups = (int) p.num("o_groups", 0), n_exp = (int) p.num("n_routed_experts", 0);
410        k_exp = (int) p.num("num_experts_per_tok", 0), ff = (int) p.num("moe_intermediate_size", 0);
411        win = (int) p.num("sliding_window", 0), hc = (int) p.num("hc_mult", 0);
412        sinkhorn = (int) p.num("hc_sinkhorn_iters", 0), ix_heads = (int) p.num("index_n_heads", 0);
413        ix_hd = (int) p.num("index_head_dim", 0), ix_topk = (int) p.num("index_topk", 0);
414        cand_src = (int) p.num("candidate_source_layer_id", -1), cand_topk = (int) p.num("candidate_topk_blocks", 0);
415        cand_blk = (int) p.num("candidate_block_size", 0);
416        orig_ctx = (int) p.num("rope_scaling.original_max_position_embeddings", 0);
417        eos = (int) p.num("eos_token_id", 1);
418        eps = (float) p.num("rms_norm_eps", 1e-20), hc_eps = (float) p.num("hc_eps", 1e-6);
419        route_scale = (float) p.num("routed_scaling_factor", 1.0), lim = (float) p.num("swiglu_limit", 0.0);
420        rope_theta = p.num("rope_theta", 1e4), comp_theta = p.num("compress_rope_theta", 1e4);
421        factor = p.num("rope_scaling.factor", 1.0), beta_fast = p.num("rope_scaling.beta_fast", 32);
422        beta_slow = p.num("rope_scaling.beta_slow", 1);
423        ratios = p.list("compress_ratios"), kv_src = p.list("kv_source_layer_ids");
424        ix_src = p.list("index_source_layer_ids"), eg_layers = p.list("engram_layer_ids");
425        d_block = (int) p.num("dspark_block_size", 0), d_noise = (int) p.num("dspark_noise_token_id", 0);
426        d_rank = (int) p.num("dspark_markov_rank", 0), d_n_exp = (int) p.num("dspark_n_routed_experts", 0);
427        d_k = (int) p.num("dspark_num_experts_per_tok", 0), d_targets = p.list("dspark_target_layer_ids");
428        // the DSpark blocks: an EXL3 pack's, or a GGUF pack's from DeepSeek's checkpoint (tools/ds4/drafter_pack.py)
429        n_mtp = d_block > 0 && (int) ratios.size() > nl &&
430                        (p.get("mtp.0.attn.wq_a.trellis") != nullptr || p.get("mtp.0.attn.wq_a.weight") != nullptr)
431                    ? (int) ratios.size() - nl : 0;
432    }
433};
434
435// DeepSeek's precompute_freqs_cis frequencies (YaRN when original_seq_len > 0), in F32 as torch computes them
436std::vector<float> rope_freqs(int dim, int original, double base, double factor, double beta_fast, double beta_slow) {
437    std::vector<float> f((size_t) dim / 2);
438    for (int i = 0; i < dim / 2; ++i) {
439        const float e = (float) (2 * i) / (float) dim;
440        f[(size_t) i] = 1.0f / std::pow((float) base, e);
441    }
442    if (original > 0) {
443        auto corr = [&](double rot) {
444            return dim * std::log(original / (rot * 2 * 3.14159265358979323846)) / (2 * std::log(base));   // (M_PI: not MSVC's)
445        };
446        const double low = std::max(std::floor(corr(beta_fast)), 0.0);
447        const double high = std::min(std::ceil(corr(beta_slow)), (double) dim - 1);
448        const float den = (float) std::max(high - low, 1e-3);
449        for (int i = 0; i < dim / 2; ++i) {
450            float ramp = ((float) i - (float) low) / den;
451            ramp = std::min(1.0f, std::max(0.0f, ramp));
452            const float smooth = 1.0f - ramp;
453            f[(size_t) i] = f[(size_t) i] / (float) factor * (1.0f - smooth) + f[(size_t) i] * smooth;
454        }
455    }
456    return f;
457}
458
459// ------------------------------------------------------------------ devices, layers
460struct Dev {
461    int id = 0;
462    cudaStream_t st = nullptr;
463    cudaEvent_t ev = nullptr;
464    size_t free0 = 0, total = 0, weights = 0, experts = 0, caches = 0, scratch = 0;
465    std::vector<void*> allocs;
466    // a window's scratch, rows of up to kWin tokens (the routed experts' rows: kWin * kPicks)
467    float *h = nullptr, *h2 = nullptr, *x = nullptr, *qr = nullptr, *q = nullptr, *kvr = nullptr, *ckr = nullptr,
468          *cgr = nullptr, *latent = nullptr, *ikr = nullptr, *iq = nullptr, *iw = nullptr, *scores = nullptr,
469          *bm = nullptr, *o = nullptr, *oa = nullptr, *ao = nullptr, *mix = nullptr, *a_pre = nullptr,
470          *a_post = nullptr, *a_comb = nullptr, *f_pre = nullptr, *f_post = nullptr, *f_comb = nullptr, *pre = nullptr,
471          *glog = nullptr, *rw = nullptr, *moe_out = nullptr, *sg = nullptr, *su = nullptr, *sh = nullptr,
472          *sh_out = nullptr, *cpu_part = nullptr, *eg_x = nullptr, *eg_kv = nullptr, *logits = nullptr,
473          *freqs_win = nullptr, *freqs_comp = nullptr, *xe = nullptr, *xg = nullptr, *xu = nullptr, *xhh = nullptr,
474          *ed = nullptr;
475    float* glog_a = nullptr;   // lookahead: the next two layers' gate logits on this layer's FFN input (rows 1024 apart)
476    int *ridx = nullptr, *topk = nullptr, *cand = nullptr, *tok = nullptr;
477    unsigned long long* plan_ptr = nullptr;           // the decode path's VRAM experts (0: on the CPU lane)
478    uint8_t* eg_rows = nullptr;
479    uint16_t *emb_rows = nullptr, *ext = nullptr;   // the window's embedding rows; the window attention's rows
480    AttnScratch attn_scr;   // a few queries' selected compressed rows decoded (sparse_attn)
481    // the hand-off to the next device through pinned host memory (these cards copy peer to peer only through the
482    // driver's staging, ~1.7 ms a copy): h | pre | topk | cand
483    uint8_t* bounce = nullptr;
484    cudaEvent_t ev_out = nullptr;
485    float* tap = nullptr;   // a window's stream means before a DSpark target layer
486    // threads / tensor parallelism: its group and its index in it, the group's all-reduces it took part in, xfer_put's
487    // block counter, the hand-off to the next group (host-mapped: h | pre | topk | cand, then its flag), the window
488    // MoE's grouping scratch
489    int grp = 0, mi = 0;
490    unsigned ar_seq = 0;
491    unsigned* xcnt = nullptr;
492    unsigned* hccnt = nullptr;   // [kWin] hc_mix_split's per-token block counters (zeroed at allocation, left zero)
493    // the head group's members (the last layer's group): each its columns (split128 of V) of the head and the norms;
494    // logits_part: a member's share of the logits (the lead's: where the others' land before they join its rows)
495    x3::Mat head;
496    float *norm_w = nullptr, *d_norm = nullptr, *logits_part = nullptr;
497    unsigned head_seq = 0;
498    // the drafter's markov bias over the head group (markov_share): this member's rows [mk_v0, mk_v0 + mk_vn) of the
499    // markov head, the previous token's E row, the drafted tokens (the lead's: d_ints)
500    uint16_t *mk_share = nullptr, *mk_erow = nullptr;
501    int* mk_ints = nullptr;
502    int mk_v0 = 0, mk_vn = 0;
503    uint8_t* hand = nullptr;
504    unsigned* hand_flag = nullptr;
505    unsigned long long* grp_ptr = nullptr;
506    int *grp_start = nullptr, *grp_ent = nullptr, *n_groups = nullptr;
507};
508
509// the chunked prompt path's buffers on a device: a chunk of C tokens through a layer at once (the attention in slabs of
510// A queries, the indexer in slabs of AI), its GEMMs through FP16 reconstructions of the weights and cuBLAS
511// DS4_PRED_DUMP: a fixed +-1 random projection of the router input (D -> 256), one block a token
512__global__ void pred_proj_k(const float* x, int D, float* out) {
513    const int t = blockIdx.x, j = threadIdx.x;   // 256 threads
514    const float* xr = x + (size_t) t * D;
515    float a = 0.0f;
516    for (int d = 0; d < D; ++d) {
517        unsigned h = (unsigned) d * 2654435761u ^ ((unsigned) j + 1u) * 40503u;
518        h ^= h >> 15; h *= 2246822519u; h ^= h >> 13; h *= 3266489917u; h ^= h >> 16;
519        a += (h & 1u) ? xr[d] : -xr[d];
520    }
521    out[(size_t) t * 256 + j] = a * rsqrtf((float) D);
522}
523
524struct Chunk {
525    int C = 0, A = 0, AI = 0;
526    float *h = nullptr, *x = nullptr, *acc = nullptr, *qr = nullptr, *kvr = nullptr, *ckr = nullptr, *cgr = nullptr,
527          *latent = nullptr, *ikr = nullptr, *q = nullptr, *o = nullptr, *oa = nullptr, *iq = nullptr, *iw = nullptr,
528          *scores = nullptr, *bm = nullptr, *mix = nullptr, *a_pre = nullptr, *a_post = nullptr, *a_comb = nullptr,
529          *f_pre = nullptr, *f_post = nullptr, *f_comb = nullptr, *pre = nullptr, *glog = nullptr, *rw = nullptr,
530          *sg = nullptr, *su = nullptr, *y = nullptr, *eg_x = nullptr, *eg_kv = nullptr;
531    uint16_t *x16 = nullptr, *qr16 = nullptr, *o16 = nullptr, *oa16 = nullptr, *lat16 = nullptr, *sh16 = nullptr,
532             *h16 = nullptr, *eg_x16 = nullptr, *ext = nullptr, *w16 = nullptr, *emb = nullptr;
533    size_t w16_elems = 0;
534    uint16_t* wc = nullptr;                  // (DS4_ATTN_WCACHE) wq_b | wo_a groups | wo_b in FP16, one layer's
535    const void* wc_tag[18] = {};             // the matrix each part of wc holds
536    int *ridx = nullptr, *topk = nullptr, *cand = nullptr, *bounds = nullptr, *row_tok = nullptr, *pos = nullptr;
537    uint8_t* eg_rows = nullptr;
538    int* bounds_pin = nullptr;   // pinned: the sort's bounds, read back
539    // the CPU lane's experts streamed in: ring_n VRAM slots of ring_stride bytes in kParts parts, a batch a part,
540    // kParts batches in flight on the copy stream (filled / freed: each part's last copy, its last use)
541    static constexpr int kParts = 4;
542    uint8_t* ring = nullptr;
543    size_t ring_stride = 0;
544    int ring_n = 0;
545    cudaStream_t cs = nullptr;
546    cudaEvent_t filled[kParts] = {}, freed[kParts] = {};
547    // in place (file_experts): each streamed expert's file region read into pinned staging (ring_n slots of
548    // stage_stride bytes, a part's slots free again once its `filled` copies are done) by the readers, in parallel,
549    // and DMA'd from there - a copy from the files' pages goes through the driver's staging, one thread at ~1.3 GB/s
550    uint8_t* stage = nullptr;
551    size_t stage_stride = 0;
552    std::unique_ptr<Pool> readers;
553    cublasHandle_t blas = nullptr;
554    // host-mapped: a chunk's hand-off to the next group (h | pre | topk | cand), two in flight (slot = chunk % 2), each
555    // with its flag, and the next group's members' acknowledgements [slot][member] (32 apart)
556    uint8_t* hand[2] = {nullptr, nullptr};
557    unsigned* hand_flag[2] = {nullptr, nullptr};
558    unsigned* hand_ack = nullptr;
559    unsigned arb_seq = 0;        // the group's chunk all-reduces
560    // pinned, two chunks in flight: the embedding rows (the first layer's device), the Engram rows (an Engram layer's)
561    uint16_t* emb_host[2] = {nullptr, nullptr};
562    uint8_t* eg_host[2] = {nullptr, nullptr};
563    cudaEvent_t emb_ev[2] = {nullptr, nullptr}, eg_ev[2] = {nullptr, nullptr};
564    double stream_bytes = 0;     // the experts streamed in, in all
565    // the flow (a GGUF's in-place experts, every layer of the device on it alone; DS4_FLOW=0: the batches above): a
566    // (chunk, layer)'s streamed experts are those it routes to - its likely ones (the profile's chance of a pick by the
567    // chunk's tokens) queued once the layer before it routed, read while that one computes, the rest of its picks once
568    // it routed itself; never an expert no token of the chunk picked unless it was a likely one.  Each item read by io
569    // (unbuffered: the disk straight into its staging slot, every part of every item in flight at once - none waits
570    // for a batch) or taken from its RAM-tier slot as it lies, then DMA'd into the ring in order, item i into slot
571    // i % ring_n; the compute takes the items as they land, in runs of what has.
572    struct Item {
573        int il = 0, k = 0, e = 0, v = 0, stage = -1;   // layer, chunk, expert, virtual slot, staging slot (-1: RAM)
574        int mi = 0;                                    // the device's member index in the layer's group
575        const uint8_t* src[3] = {nullptr, nullptr, nullptr};   // where its gate / up / down (its parts) lie once read
576        const uint8_t* ram = nullptr;                  // its RAM-tier blob, copied into staging (not pinned there)
577        const uint8_t* store_src[3] = {nullptr, nullptr, nullptr};
578        uint8_t* keep = nullptr;                       // (layer-major) its layer-cache slot: what is read kept there
579        int64_t after = -1;                            // (layer-major) the items up to this one read first
580        std::atomic<int> left{0};                      // parts still being read
581        std::atomic<bool> bad{false};
582    };
583    bool flow = false;
584    int dev = -1;                            // the device (index into devs) this chunk state belongs to
585    std::unique_ptr<IoQueue> io;
586    std::deque<Item> items;                  // items[0] is item `base`; the indices below are absolute
587    size_t base = 0, n_read = 0, n_dma = 0, n_comp = 0;
588    uint64_t n_file = 0;                     // file items so far (staging slot = ordinal % S)
589    int S = 0;                               // staging slots, stage_stride apart
590    std::vector<int64_t> stage_item;         // staging slot -> the item last read into it (-1: none)
591    std::vector<cudaEvent_t> stage_ev, ring_fill, ring_free;   // a staging slot's DMA out; a ring slot's DMA in, its use
592    int spec_k = -1, spec_il = -1, n_spec = 0;   // the likely items queued last: (chunk, layer), how many, from where
593    size_t spec_begin = 0;
594    std::vector<int> fl_layers, fl_T;        // the device's trunk layers in order; the run's chunk sizes
595    int fl_yoco = -1, fl_cut_k = 0, fl_cut_r = 0;   // Run::yoco / cut_k / cut_r: what a layer's chunk streams for
596    int bc_n = 0, bc_w = 0;                  // a batch's compacted bounds: bc_n regions of bc_w, by batch count
597    int *bc_pin = nullptr, *bc_dev = nullptr;
598    uint64_t n_batch = 0;
599    double wait_ms = 0;                      // the compute waiting for a read
600    uint64_t it_file = 0, it_ram = 0, it_spec = 0, it_spec_unused = 0;
601    uint64_t it_vram = 0;   // (stats) picked experts the device already held
602    uint64_t io_d0 = 0, io_b0 = 0;           // io's unbuffered / buffered bytes when the run started
603    double io_busy0 = 0, io_any0 = 0;        // io's busy_ms() / any_ms() then
604    uint64_t io_runs0 = 0, io_rj0 = 0;       // io's runs() / run_jobs() then
605    // layer-major (a run of several chunks, every layer on this device): the layers one after another, each through
606    // all the chunks; a chunk's state between its layers (h | pre | topk | cand, chunk k at k chunk_hand_bytes()) in
607    // host memory, and the layer cache - RAM slots where the experts a layer's chunk reads from the files are kept for
608    // its later chunks, so each is read once a run
609    bool lm = false, lm_pinned = false;
610    uint8_t* lm_state = nullptr;
611    size_t lm_state_bytes = 0;
612    uint8_t* lc = nullptr;                   // lc_bytes of slots, a layer's experts' blobs side by side
613    size_t lc_bytes = 0;
614    int lc_il = -1, lc_used = 0, lc_n = 0;   // the layer the cache holds, its slots taken, its slots in all
615    size_t lc_first = 0, lc_chk = 0;         // the layer's first item; the items before lc_chk all read
616    std::vector<int> lc_of;                  // expert -> its slot (-1: none)
617    std::vector<int64_t> lc_writer;          // slot -> the item reading its expert into it
618    uint64_t it_lc = 0;                      // items taken from the layer cache
619};
620
621struct Layer {
622    int il = 0, dev = 0, ratio = 0;
623    // its group (tensor parallel: nm members, each a copy of the device state in mates, member mi's share of the
624    // heads, of wo_a's groups, of wo_b's rows and of the FFNs: gate / up columns, down rows; its part of an expert
625    // laid out as hlay, hblob bytes - the host state, the CPU lane and the full blob layout stay with member 0)
626    int grp = 0, nm = 1, mi = 0;
627    std::vector<Layer> mates;
628    x3::ExpertLayout hlay;
629    size_t hblob = 0;
630    int ff0 = 0, ffn = 0;     // this member's FFN columns [ff0, ff0 + ffn) (split128 of n_ff; the whole one alone)
631    // this member's heads [ah0, ah0 + ahn) and wo_a groups [og0, og0 + ogn) - all of them alone; in a group of more
632    // members than the heads split among evenly (head_members: 9, 7 or 6 over 64 heads), the first ones none: their
633    // attention adds nothing to the sum
634    int ah0 = 0, ahn = 0, og0 = 0, ogn = 0;
635    // the chunked prompt path: each expert's virtual slot (its VRAM slot, or n_slots + its place among the CPU lane's
636    // experts, which a chunk streams in that order) - pinned on member 0, a device copy on each member
637    int* vs_pin = nullptr;
638    int* vs_dev = nullptr;
639    std::vector<int> host_list;
640    std::string name;         // "layers.N." or, for the DSpark drafter's blocks, "mtp.N."
641    int n_exp = 0, k_exp = 0; // routed experts, and how many a token takes (the drafter's: 128, 3)
642    bool mtp = false;         // a DSpark block (index stage = il - n_layers)
643    bool kv_src = false, ix_src = false, owns_k = false, cand_src = false, uses_cand = false;
644    int src = -1;      // the kv source whose compressed KV this layer reads (index into Impl::srcs)
645    int ik_src = -1;   // the kv source whose index keys its indexer reads
646    int eg = -1;       // engram layer index, or -1
647    x3::Mat wq_a, wq_b, wkv, wo_a[16], wo_b, s1, s2, s3, c_wkv, c_wgate, i_wq_b, i_wk, eg_wkv;
648    float *q_norm = nullptr, *kv_norm = nullptr, *attn_norm = nullptr, *ffn_norm = nullptr, *c_norm = nullptr,
649          *ik_norm = nullptr, *sink = nullptr, *hca_fn = nullptr, *hca_scale = nullptr, *hca_base = nullptr,
650          *hcf_fn = nullptr, *hcf_scale = nullptr, *hcf_base = nullptr, *gate_bias = nullptr, *eg_w = nullptr,
651          *gate_bias_vl = nullptr;   // (the image tokens' routing bias, with the vision tower)
652    uint16_t* i_wproj = nullptr;
653    // the lookahead adapter (DS4_AHEAD_ADAPTER): U [D][ad_r], V [ad_r][n_exp] on this layer's device, added to the next
654    // layer's gate on this layer's FFN input; ad_r 0: none (ad_tried: the file was looked at for this layer)
655    unsigned char* res_tab = nullptr;          // DS4_CP_STORE: expert -> 1 when in VRAM or the RAM store (device)
656    std::vector<unsigned char> res_host;
657    float *ad_U = nullptr, *ad_V = nullptr;
658    int ad_r = 0;
659    bool ad_tried = false;
660    float* gate_w = nullptr;   // the router's weights, F32 (DeepSeek's inference computes the gate in F32)
661    uint8_t* win = nullptr;                     // [win] rows of kKvFp8 (kv_row_bytes)
662    float *c_kv = nullptr, *c_score = nullptr;  // the compressor's partial group (ratio > 1)
663    // a run of chunks' mid-run checkpoint (feed_mark): the ring and the partial group as they were before a row
664    uint8_t* snap_win = nullptr;
665    float *snap_kv = nullptr, *snap_sc = nullptr;
666    // routed experts
667    x3::ExpertLayout lay;
668    size_t blob = 0;                            // bytes of one expert's blob
669    int n_vram = 0;
670    bool cpu_only = false;   // a role's type has no device kernel: every expert of this layer is the CPU lane's
671    uint8_t* vram_base = nullptr;
672    std::vector<int> slot;                      // expert -> VRAM slot or -1
673    std::vector<int> ram;                       // expert -> RAM-tier slot or -1 (a GGUF's in-place experts; empty: none)
674    std::vector<uint8_t*> host;                 // expert -> host (non-null: on the CPU lane; its halves in hh)
675    // the CPU lane keeps an expert as NH column parts, part X on NUMA node X: gate / up columns [X n_ff / NH, ..),
676    // down columns [X dim / NH, ..), each a standalone EXL3 matrix (its own trellis, the full suh, its part of svh)
677    struct Half {
678        size_t trellis[3], suh[3], svh[3], bytes;
679        int k[3], n[3];
680    } hl;
681    std::vector<std::array<uint8_t*, 4>> hh;     // expert -> its parts on the nodes
682    // the expert cache: one VRAM slot and one set of host parts kept free, so an expert can move in while the one it
683    // replaces moves out; heat is how much each expert was used lately (the profile's share to start with)
684    int n_slots = 0, spare_vram = -1;
685    std::array<uint8_t*, 4> spare_host = {nullptr, nullptr, nullptr, nullptr};
686    std::vector<float> heat;
687    std::vector<int> cpu_hits;                  // CPU-lane experts used since the cache last looked
688    bool swap_pending = false;
689    unsigned long long* tab_pin = nullptr;      // pinned: the table entries a swap writes
690    // a speculative window's backups (trunk layers): the ring rows it replaced, and a compressor's state before it and
691    // the window's raw rows (kv, then score) to replay the accepted ones
692    uint8_t* ring_bak = nullptr;
693    float *c_snap = nullptr, *c_rows = nullptr;
694    unsigned long long* vram_tab = nullptr;     // device [n_exp]
695    std::vector<uint8_t> zc;                    // (the RAM store) expert -> 1: its store slot is GPU-visible, the device computes it over PCIe
696    unsigned long long* zc_tab = nullptr;       // device [n_exp]: those slots' device addresses (0: none) - the decode token's zc_stage reads it
697    std::vector<std::array<x3::Mat, 3>> vm;     // expert -> its gate, up, down as EXL3 views of its VRAM blob
698    std::vector<int> aux;                       // (DS4_AUX_GPU) expert -> 1: resident on the expert GPU, computed there (empty: none)
699    std::vector<std::array<x3::Mat, 3>> avm;    // those experts' matrices in the expert GPU's arena
700    std::vector<uint64_t> region_off;           // expert -> file region (offset, bytes, file)
701    std::vector<uint64_t> region_bytes;
702    std::vector<int> region_file;
703    size_t piece_src[3][3];                     // part (gate, up, down) x (trellis, suh, svh): offset in the region
704    size_t piece_bytes[3][3];
705    size_t dense_bytes = 0;
706    // a GGUF's MXFP4 experts (lay.fmt == gg::kFmtMXFP4): matrix r (gate, up, down) of expert e lies at mx_off[r] +
707    // e mx_stride[r] in file mx_file[r] - loaded from there, and read in place (the file's mapping) by the CPU lane
708    int mx_file[3] = {-1, -1, -1};
709    uint64_t mx_off[3] = {0, 0, 0}, mx_stride[3] = {0, 0, 0};
710};
711
712struct Src {
713    int layer = 0, ratio = 1;
714    int64_t cap = 0;
715    // per device (nullptr where no layer reads it): rows of kKvFp4 (the compressed KV), kKvFp4p (the index keys)
716    std::vector<uint8_t*> ckv, ik;
717    // Optional F32 pre-RoPE masters, indexed [device][row][rd].
718    std::vector<float*> master, master_ik;
719    std::vector<uint8_t*> master_valid, master_ik_valid;
720    uint8_t *h_ckv = nullptr, *h_ik = nullptr;   // pinned: a window's new rows, on their way to the other devices
721    cudaEvent_t ev_ckv = nullptr, ev_ik = nullptr;
722    // threads: whether devices outside the source's group read it, and the host-mapped hand-off of a window's new rows
723    // (ckv rows, then ik rows at kWin * hd) and its flag
724    bool remote = false;
725    uint8_t* x_stage = nullptr;
726    unsigned* x_flag = nullptr;
727    // pipelined chunks: a second staging slot (slot 1; slot 0 is x_stage), its flag, and the readers' acknowledgements
728    // [slot][device] (32 apart); readers: the devices outside the source's group that read it
729    uint8_t* x_stage1 = nullptr;
730    unsigned* x_flag1 = nullptr;
731    unsigned* x_ack = nullptr;
732    std::vector<int> readers;
733    uint8_t* stage(int slot) const { return slot ? x_stage1 : x_stage; }
734    unsigned* flag(int slot) const { return slot ? x_flag1 : x_flag; }
735};
736
737// a host thread that enqueues one device's work (threads mode)
738struct Worker {
739    std::thread th;
740    std::mutex mu;
741    std::condition_variable cv;
742    std::function<void()> job;
743    bool busy = false, quit = false;
744    void start() {
745        th = std::thread([this] {
746            for (;;) {
747                std::function<void()> j;
748                {
749                    std::unique_lock<std::mutex> lk(mu);
750                    cv.wait(lk, [&] { return quit || job != nullptr; });
751                    if (quit) return;
752                    j = std::move(job);
753                    job = nullptr;
754                }
755                j();
756                {
757                    std::lock_guard<std::mutex> lk(mu);
758                    busy = false;
759                }
760                cv.notify_all();
761            }
762        });
763    }
764    void submit(std::function<void()> f) {
765        {
766            std::lock_guard<std::mutex> lk(mu);
767            job = std::move(f);
768            busy = true;
769        }
770        cv.notify_all();
771    }
772    void wait() {
773        std::unique_lock<std::mutex> lk(mu);
774        cv.wait(lk, [&] { return !busy; });
775    }
776    bool idle() {
777        std::lock_guard<std::mutex> lk(mu);
778        return !busy;
779    }
780    void stop() {
781        {
782            std::lock_guard<std::mutex> lk(mu);
783            quit = true;
784        }
785        cv.notify_all();
786        if (th.joinable()) th.join();
787    }
788};
789
790struct Group {
791    std::vector<int> mem;   // device indices, member order (member 0 the lead)
792    ArGroup ar, arb;        // a window's all-reduces, a chunk's
793    // the head group: the members' logits shares on their way to the lead, two slots (by seq), their flags and the
794    // lead's acknowledgements (host-mapped)
795    float* lg_stage = nullptr;
796    unsigned *lg_flag = nullptr, *lg_ack = nullptr;
797};
798
799constexpr int kMaxL = 64;   // layers (the trunk's and the drafter's) a window plan covers
800
801// what a window's layers need from the host, decided before they run (threads enqueue the layers concurrently): the
802// mailbox seq of each layer (async: the device publishes its routing), the indexer's selection sizes and the candidate
803// blocks as each layer sees them, the window's hand-off seq
804struct WinPlan {
805    bool par = false, async = false;
806    unsigned win = 0;
807    int k = 0;              // (a run of chunks) the chunk's index: its hand-off slot k % 2
808    int snap_t = -1;        // (a run of chunks) the chunk's row whose state before it the layers keep (-1: none)
809    int eg_slot = -1;       // (a run of chunks, layer-major) the Engram rows' slot (-1: k % 2)
810    unsigned vl = 0;        // (a window) bit t: token t is inside a picture's span (routed with the image bias)
811    unsigned seq[kMaxL] = {};
812    int topk[kMaxL][kWin] = {}, cand[kMaxL][kWin] = {};
813};
814
815}  // namespace
816
817// ------------------------------------------------------------------ the model
818struct Model::Impl {
819    Options o;
820    Pack pk;
821    Geo g;
822    std::vector<Dev> devs;
823    std::vector<Layer> L;
824    std::vector<Src> srcs;
825    std::vector<Group> groups;
826    std::vector<std::unique_ptr<Worker>> workers;   // threads mode: one per device
827    bool par = false;                 // threads mode (the windows: decode)
828    bool scr_master = false;           // STRATA_DS4_SCR=1: retain F32 pre-RoPE tails
829    bool prompt_par = false;          // the prompt path's chunks (a thread a GPU), as --tp / --threads asked
830    unsigned win_seq = 0;             // the windows the threads ran (the hand-offs' seq)
831    // the chunked prompt path (threads mode): chunk tokens a pass, runs shorter than chunk_min in windows
832    int chunk = 0, chunk_min = 512;
833    // DS4_LEND=N (one GPU, the flow): prompts of N+ tokens run in chunks of `chunk` whose buffers (and the slabs' and
834    // DS4_ATTN_WCACHE's) are carved out of the VRAM experts' memory (one arena), the experts streamed like the CPU
835    // lane's meanwhile; shorter ones in chunks of chunk_small_ (DS4_LEND_SMALL, 4096) in buffers of their own.  The
836    // VRAM experts come back when the next forward starts (the same ones, into the same slots), then the cache tick
837    // and the settle the prompt left
838    int lend_min_ = 0, chunk_small_ = 0, lend_slab_ = 1024;
839    uint8_t* lend_arena_ = nullptr;
840    size_t lend_bytes_ = 0;
841    bool lent_ = false, lend_due_ = false;
842    int64_t lend_tick_n_ = 0;
843    std::vector<int> lend_nslots_;
844    std::vector<char> lend_of_;                          // [layer] its VRAM experts live in the arena
845    std::vector<std::pair<void**, void*>> lend_saved_;   // the chunk's own buffers while a lent prompt runs
846    int lend_saved_C_ = 0, lend_saved_A_ = 0;
847    static constexpr bool kChunkedPromptDefault = true;   // the layer-major prompt is the default (gate: KL 0.1685 vs 0.1686, 8K prompt 6x, decode within 2% - ds4 notes-dsv41-r97)
848    static constexpr int kFlowChunkMin = 2;   // chunk_min with every device's layers on the flow (see load)
849    // --prefill-chunk at most (route() runs in kVlRows-row slabs).  The default stays kVlRows: a 16384-token chunk
850    // reads a 16K prompt's experts once instead of twice (V100: 461.8 -> 321.3 s, 736 -> 506 GB read) but its buffers
851    // take ~1.9 GB of VRAM experts (745 -> 644 on a 32 GB V100) from every decoded token
852    static constexpr int kMaxChunk = 4 * kVlRows;
853    std::vector<std::unique_ptr<Chunk>> chunks;   // per device
854    size_t eg_cap = kWin;             // tokens h_eg holds
855    int tap_cap = kWin;               // rows h_taps holds (a chunk seeds the drafter with its last 128)
856    static constexpr int kYocoMin = 1024;   // a long prompt's skip (forward_chunks): the fewest rows worth skipping
857    bool logits_all = false;          // the last feed was a chunk with logits for every row (chunk_logits)
858    std::vector<float> chunk_logits;
859    std::function<void(int64_t)> progress;   // a run of chunks: the tokens done so far (the main thread, while it waits)
860    // a Stop while a run of chunks goes through the layers (Model::set_cancel, asked while forward_chunks waits): one
861    // GPU stops after the layer (or the layer's chunk) it is on (halt); several stop at a chunk every one of them
862    // reaches - none starts chunk halt_k or later, halt_k one past the latest any started - so no device waits on a
863    // hand-off that never comes (Project Maya v1.1.20)
864    std::function<bool()> cancel;
865    std::atomic<bool> halt{false};
866    std::mutex halt_mu;
867    int halt_k = INT_MAX, halt_seen = -1;
868    bool halted = false;                      // the last run ended early on a Stop
869    static constexpr const char* kHalted = "stopped";
870    bool chunk_go(int k) {   // chunk k may start on this device (several GPUs)
871        std::lock_guard<std::mutex> lk(halt_mu);
872        if (k >= halt_k) return false;
873        halt_seen = std::max(halt_seen, k);
874        return true;
875    }
876    bool halt_now() const { return devs.size() == 1 && halt.load(std::memory_order_acquire); }
877    // a run's early end on device di: the expert reads still in flight land first (they count down items the next run
878    // clears), then its streams are idle
879    bool halt_end(int di, std::string& err) {
880        Chunk& c = *chunks[(size_t) di];
881        cudaSetDevice(devs[(size_t) di].id);
882        if (c.flow)
883            for (size_t i = c.base; i < c.n_read; ++i)
884                while (fit(c, i).left.load(std::memory_order_acquire) != 0) c.io->wait_any(500);
885        if (c.cs != nullptr) cudaStreamSynchronize(c.cs);
886        cudaStreamSynchronize(devs[(size_t) di].st);
887        err = kHalted;
888        return false;
889    }
890    std::vector<cudaEvent_t> chunk_done;     // on the last layer's device: chunk k through every layer
891    std::unique_ptr<std::atomic<int>[]> chunk_rec;   // chunk k's event recorded
892    // a prompt the flow could take: the flow or windows of 16, whichever this PC runs it faster (pick_path) - this
893    // PC's speeds measured at load (calibrate_paths), each path's predictions scaled by how long it really took
894    struct PathModel {
895        bool on = false;
896        double dma = 0, copy = 0, disk = 0, cpu = 0, cpu_cold = 0;   // bytes/s (disk, cpu_cold 0: not measured)
897        // the flow's taken / predicted so far [0] by the prompt's size class (2-31, 32-127, 128-511, 512 tokens and
898        // more: a short one's fixed costs weigh more), and how many prompts set it ([1] unused)
899        double k[2][4] = {{1, 1, 1, 1}, {1, 1, 1, 1}};
900        int64_t kn[2][4] = {};
901        double win_s = 0;                                              // windows: seconds a window took, so far
902        int64_t win_n = 0;
903        int last_cls = 0, last_nw = 0;                                 // the last pick's size class, its windows
904        double m = 1;                                                  // the picks' spread, against the profile's
905        int64_t n_m = 0;
906        int last = -1;                                                 // the last pick: 1 the flow, 0 windows
907        double last_pred = 0;                                          // its prediction (s, before its k)
908    } pm;
909    static constexpr int kPickMax = 2048;   // (from here on the flow: windows' work grows with every 16 tokens)
910    static constexpr double kPickRes = 0.9;  // (this share of the CPU-lane experts in RAM: windows if predicted faster)
911    std::atomic<int> lm_layers{0};           // (layer-major) the layers every chunk went through
912    WinPlan wplan;
913    int head_dev = 0;
914    x3::Mat head;
915    float* norm_w = nullptr;          // on the head device
916    // the drafter: main_proj / main_norm (on its first block's device), its final norm, the markov head and the
917    // confidence head (on the head device: the drafts' logits come from the trunk's head)
918    x3::Mat d_main_proj;
919    float *d_main_norm = nullptr, *d_norm = nullptr, *d_conf = nullptr;
920    uint16_t *d_mk_embed = nullptr, *d_mk_head = nullptr;   // BF16 [vocab][rank], F16 [vocab][rank]
921    // a head group of two or more: the markov steps over its members (each its rows of the bias and an argmax of its
922    // share, the global one through host-mapped slots [step][member] {value, index, seq}) in place of the lead's whole
923    // rows - E host-mapped (each member reads the picked token's row), a draft's seq in mk_seq
924    bool mk_split = false;
925    uint16_t* h_mk_embed = nullptr;
926    unsigned* mk_slots = nullptr;
927    unsigned mk_seq = 0;
928    int d_dev = 0;                    // the drafter's first block's device
929    bool spec_win = false;            // the window being run is a draft's verification (layer() keeps backups)
930    float* h_taps = nullptr;          // pinned [kWin][targets][dim]: the last window's taps
931    cudaEvent_t ev_seed = nullptr;    // the drafter's seeding read h_taps: the next window's taps wait for it
932    float* d_confv = nullptr;         // on the head device
933    int* d_ints = nullptr;            // on the head device: drafts in, picks out
934    float conf_threshold = std::getenv("DS4_DSPARK_CONF") ? (float) std::atof(std::getenv("DS4_DSPARK_CONF")) : 0.5f;
935    // a sampled round's drafts: the distribution q each one was drawn from (its kept list, on the head device) for
936    // verify()'s rule - a point at the draft for the drafter's argmax; and the chain they were drawn with (verify()
937    // checks it is its own)
938    strata::dsv41k::SpecList* d_specq = nullptr;
939    std::vector<strata::dsv41k::SpecList> h_specq = std::vector<strata::dsv41k::SpecList>(kWin);
940    bool drafts_q = false;
941    float dq_temp = 0.0f, dq_top_p = 1.0f, dq_min_p = 0.0f;
942    int dq_top_k = 0;
943    uint64_t dq_seed = 0, dq_counter = 0;
944    // (tests) DS4_DSPARK_SAMPLE=1: a sampled request's drafts drawn from the drafter's distribution through the
945    // request's chain, as DeepSeek's reference does (else its argmax: the same acceptance on Uranus, 31-32% of 5
946    // drafts a round either way); DS4_DSPARK_QTEMP=f: those draws at f x the request's temperature (any q keeps the
947    // rule exact); DS4_DSPARK_MAX=n: at most n drafts a round; DS4_DSPARK_DUMP=file: the drafter's inputs and outputs
948    // (tools/ds4/dspark_ref.py checks them against DeepSeek's checkpoint)
949    bool sample_drafts = std::getenv("DS4_DSPARK_SAMPLE") != nullptr && std::atoi(std::getenv("DS4_DSPARK_SAMPLE")) != 0;
950    float q_temp_scale = std::getenv("DS4_DSPARK_QTEMP") ? (float) std::atof(std::getenv("DS4_DSPARK_QTEMP")) : 1.0f;
951    int max_drafts = std::getenv("DS4_DSPARK_MAX") ? std::atoi(std::getenv("DS4_DSPARK_MAX")) : 0;
952    std::FILE* dump_d = std::getenv("DS4_DSPARK_DUMP") ? std::fopen(std::getenv("DS4_DSPARK_DUMP"), "wb") : nullptr;
953    float* h_dump = nullptr;          // (the dump's pinned copies: each block's stream, each block's ring)
954    uint16_t* h_dump_ring = nullptr;
955
956    uint16_t* embed_pinned = nullptr;
957    std::vector<float> freqs_win, freqs_comp;
958    std::vector<std::unique_ptr<Pool>> pools;   // one per NUMA node, its workers on that node's cores
959    std::vector<std::vector<int>> cores;        // each node's physical cores
960    int NH = 1;                                 // the CPU lane's parts of an expert (the NUMA nodes)
961    // the CPU lane's experts read in place from the model's files (one part, the files' layout; the page cache keeps
962    // what fits) instead of copied into RAM, and how much of them the load reads ahead (the most-routed first)
963    bool file_experts = false;
964    uint64_t warm_bytes = 0;
965    static constexpr uint64_t kRamMargin = 8ull << 30;   // RAM left to the rest (the system, the page cache's churn)
966    uint8_t* file_part(const Layer& l, int e) const {
967        return pk.maps[(size_t) l.region_file[(size_t) e]].first + l.region_off[(size_t) e];
968    }
969    // host side of the CPU lane, a window's rows
970    float *h_x = nullptr, *h_w = nullptr, *h_part = nullptr;
971    int* h_idx = nullptr;
972    uint8_t* h_eg = nullptr;          // the window's Engram rows: [engram layer][token] of [cols][hd] then the scales
973    // the Engram rows' reader (its own threads and file handles), the rows already fetched, the window's batches (one
974    // an Engram layer: asked for when the window's tokens are known, collected right before that layer)
975    EgReader eg_io;
976    EgRowCache eg_cache;
977    std::mutex eg_cache_mu;
978    std::vector<std::unique_ptr<EgBatch>> eg_win;
979    // Engram layer li's embed rows, as the pack stores them: 0 MXFP8 ([scale, 32 codes] blocks, 33 bytes a 32), 1
980    // ggml Q6_K (210 bytes a 256), 2 ggml IQ4_NL (18 bytes a 32: an fp16 d and 16 nibble bytes), 3 an old pack's FP8
981    // codes with their E8M0 scales in a tensor of their own (see eg_issue)
982    std::vector<uint8_t> eg_fmt;
983    std::atomic<int64_t> eg_rows_n{0}, eg_hits_n{0}, eg_reads_n{0}, eg_wait_ns{0}, eg_io_ns{0};
984    uint16_t* h_emb = nullptr;        // the window's embedding rows
985    std::vector<float> c_xh, c_xsb, c_acc, c_xhd, c_xsd, c_accd, c_yd;
986    // the state
987    bool scr_derived = false;
988    int64_t scr_band_start = -1;
989    int64_t pos = 0;
990    std::vector<int32_t> toks, ctoks;
991    struct Check {                    // the state at a position: every window ring, the compressors' partial groups
992        int64_t pos = -1;
993        std::vector<std::vector<uint8_t>> win;
994        std::vector<std::vector<float>> comp;
995    };
996    static constexpr int kChecks = 4;
997    Check ck[kChecks];                // the end of the last prompt, the position before it, the anchor (the position
998                                      // before the end of the first prompt of the run of prompts that each continued
999                                      // the last in place: a chat template that drops earlier turns' reasoning at a new
1000                                      // user message re-renders the history from about there) and the prefix (where the
1001                                      // server said the prompt's shared start - system prompt and tools - ends: another
1002                                      // agent behind the same start goes back to it)
1003    bool slot_held = false;           // slot_save took this state and nothing has changed it since
1004    std::vector<uint32_t> prof;       // [nl][n_exp] routed-expert hits
1005    Stats st;
1006    int cur_topk_n[kWin] = {}, cur_cand_n[kWin] = {};   // what the latest indexer / candidate source left, per query
1007                                                        // (plan_window's: the windows' plans are made in order)
1008    int n_logits = 0;                 // the last forward's logit rows
1009    // the decode path (windows of one): the device publishes each layer's routing into reqs, the service thread
1010    // answers in resps with the CPU lane's part, and the device waits for the answer only before the expert sum
1011    Req* reqs = nullptr;
1012    Resp* resps = nullptr;
1013    unsigned seq_issued = 0;
1014    std::atomic<int> layer_of[kRing];
1015    std::thread service;
1016    std::atomic<bool> quit{false};
1017    std::thread store_bg;   // the RAM store's fill beyond the first 48 GB, read after the model is ready (preload_store)
1018    bool sync_decode = std::getenv("DS4_SYNC") != nullptr;
1019    // a window of one through moe_gate_up / moe_down (DS4_MOE_TOKEN=0: win_experts, whose down rows run
1020    // before the wait for the CPU lane - the same bits, no faster)
1021    bool moe_token_path = std::getenv("DS4_MOE_TOKEN") == nullptr || std::atoi(std::getenv("DS4_MOE_TOKEN")) != 0;
1022    int async_max_t = std::getenv("DS4_ASYNC_T") ? std::atoi(std::getenv("DS4_ASYNC_T")) : 8;   // windows up to this
1023    // lookahead: while layer L runs, the device guesses the next layer's picks (its gate on L's FFN input, the same
1024    // choice) and publishes them with L's routing; the CPU lane asks for the guessed experts it will read from the files
1025    // at once (a thread of its own, os::prefetch), so the SSD reads them while L computes instead of on the next
1026    // layer's critical path.  Only the page cache sees it - the outputs are the same.  DS4_AHEAD=0: off, 2: also the
1027    // layer after (from L's input too); DS4_AHEAD_EXTRA: guesses past the next layer's top k (< 0: fewer - the guess's
1028    // picks by rank on Sun: 97 91 81 70 57 41 %, past the top 6 29 20 %: reads wasted on an SSD-bound PC).
1029    int ahead_mode = std::getenv("DS4_AHEAD") ? std::atoi(std::getenv("DS4_AHEAD")) : 1;
1030    int ahead_extra = std::getenv("DS4_AHEAD_EXTRA") ? std::atoi(std::getenv("DS4_AHEAD_EXTRA")) : 0;
1031    // (DS4_AHEAD_ORDER=0: the CPU lane computes a layer's experts in expert order, not the ones asked for early first)
1032    bool ahead_order = std::getenv("DS4_AHEAD_ORDER") == nullptr || std::atoi(std::getenv("DS4_AHEAD_ORDER")) != 0;
1033    std::vector<uint8_t> ahead_fl;     // [layer][1024]: 1 the top-k guess, 2 any guess, a layer before; 4 two layers before;
1034                                       // 8 asked for (prefetch)
1035    std::vector<uint8_t> ahead_rank;   // [layer][1024]: 1 + the expert's rank in the guess a layer before (0: not guessed)
1036    std::vector<unsigned> ahead_for;   // [layer]: the request (seq) its flags are for
1037    std::thread pf_th;
1038    std::mutex pf_mu;
1039    std::condition_variable pf_cv;
1040    std::vector<std::pair<const void*, size_t>> pf_q;
1041    // the expert cache: swaps prepared on threads of their own (DS4_CACHE_THREADS, 1 by default - 4 measured no faster
1042    // on one V100 - more for a PC to try: each its staging buffers and
1043    // copy streams), switched between windows
1044    struct Swap {
1045        int layer = 0, in = -1, out = -1;
1046        int ram = -1;   // (copy_mode, `in` held in RAM) the spare slot `out` is copied into from VRAM
1047    };
1048    static constexpr int kMaxSwaps = 8;
1049    // the swap rule: a CPU-lane expert in when its heat passes the coldest VRAM one's x margin + bonus; heat x decay
1050    // every 256 tokens; at most `inflight` swaps under way (DS4_CACHE_MARGIN / _BONUS / _DECAY / _INFLIGHT)
1051    static float env_f(const char* k, float d) { return std::getenv(k) ? (float) std::atof(std::getenv(k)) : d; }
1052    const float c_margin = env_f("DS4_CACHE_MARGIN", 1.25f), c_bonus = env_f("DS4_CACHE_BONUS", 1.0f),
1053                c_decay = env_f("DS4_CACHE_DECAY", 0.9f);
1054    const int c_inflight = std::max(1, (int) env_f("DS4_CACHE_INFLIGHT", (float) kMaxSwaps));
1055    // the RAM tier (a GGUF's in-place experts, as GLM's: the hottest in VRAM, the next hottest here, the coldest in the
1056    // files): RAM slots of one expert blob each, filled at load with the hottest experts VRAM does not hold, so the
1057    // CPU lane reads them from RAM; between windows (cache_tick) a hotter expert from the files takes the place of the
1058    // layer's coldest held one - read into a free slot by ram_th, switched while nothing reads them.  Opt-in
1059    // (STRATA_DS4_RAM_TIER=1): on a V100 with 64 GB of RAM it was slower than the page cache alone (1.4 against 2.2-2.4
1060    // tokens/s sampled) - the cache follows a conversation's experts at once, the tier's moves lag behind.
1061    struct RamSwap {
1062        int layer = 0, in = -1, out = -1, slot = -1;
1063    };
1064    std::vector<uint8_t*> ram_slots, ram_chunks;
1065    std::vector<size_t> ram_chunk_bytes;
1066    bool ram_pinned = false;   // the slots are pinned memory (the prompt path DMAs them from where they lie)
1067    size_t flow_part[3] = {0, 0, 0};   // the flow's staging room for each part: its largest over the trunk's layers
1068    std::vector<int> ram_free;
1069    std::deque<RamSwap> ram_queue;
1070    std::vector<RamSwap> ram_ready;
1071    std::condition_variable ram_cv;
1072    std::thread ram_th;
1073    int ram_inflight = 0, ram_held = 0;
1074    bool ram_tier = std::getenv("STRATA_DS4_RAM_TIER") != nullptr && std::atoi(std::getenv("STRATA_DS4_RAM_TIER")) != 0;
1075    // STRATA_DS4_DISK_SKIP_W (experimental opt-in, CHANGES THE ANSWERS; 0 = off): on the small windows (decode, a
1076    // draft's check - never the prompt path) the CPU lane leaves out a routed expert whose share of its token's route
1077    // weights is below this and whose pages are not in RAM now (the page cache or the RAM tier; os::in_ram - Linux every
1078    // page, Windows sampled pages of the working set), so a token waits on the SSD only for the experts that weigh; the
1079    // weight it carried is lost (no renormalisation).  On layers from STRATA_DS4_DISK_SKIP_FROM (0) on.  An expert left
1080    // out still counts as used (the expert cache, the profile).
1081    const float disk_skip_w = [] {
1082        const char* v = std::getenv("STRATA_DS4_DISK_SKIP_W");
1083        return v != nullptr ? std::max(0.0f, (float) std::atof(v)) : 0.0f;
1084    }();
1085    const int disk_skip_from = [] {
1086        const char* v = std::getenv("STRATA_DS4_DISK_SKIP_FROM");
1087        return v != nullptr ? std::max(0, std::atoi(v)) : 0;
1088    }();
1089    // the RAM store (--ssd-cache): the CPU lane's experts in slots a policy owns, read unbuffered (null: off)
1090    std::unique_ptr<ExpertStore> store;
1091    uint8_t* zc_stage_buf = nullptr;   // device: k staging slots for the store's experts of a decode token
1092    size_t zc_stride = 0;
1093    bool zc_copy = true;               // DS4_STORE_STAGE=0: the expert kernels read the arena over PCIe themselves
1094    bool in_ram(const Layer& l, int e) const {   // (DISK_SKIP_W) expert e's pages in RAM now
1095        if (!l.ram.empty() && l.ram[(size_t) e] >= 0) return true;
1096        if (l.lay.fmt == gg::kFmtMXFP4) {
1097            for (int r = 0; r < 3; ++r)
1098                if (!os::in_ram(mx_mat(l, e, r), mx_part_bytes(l, r))) return false;
1099            return true;
1100        }
1101        return !file_experts || os::in_ram(file_part(l, e), l.blob);
1102    }
1103    // a GGUF's CPU-lane experts copied into RAM (copy_experts, after VRAM took its share: --mmap-experts off - auto reads
1104    // them in place; DS4_COPY_GB=<n>: the hottest n GB, the rest in place - static, no moves between
1105    // them): RAM slots (l.ram, as the tier's) of NH parts, part X on NUMA node X with rows [X n / NH, (X + 1) n / NH) of
1106    // each matrix at cp_lay[layer][r] - whole rows, so the split never cuts a GGUF block (MXFP4's 32, the IQ / K types'
1107    // 256 values: blocks run along a row); one spare slot a layer for the cache's swaps (the expert VRAM gives back takes
1108    // the RAM place of the one it takes in)
1109    // Windows' commit on an integrated GPU: its allocations are charged to the commit (RAM + page file) like any private
1110    // memory - measured on a Radeon 8065S with 160 GiB of its own: the system's free commit fell by each one, whatever
1111    // its size (one above ~3 GiB also counts as the process's private bytes, a smaller one does not, the commit the
1112    // same), so a page file at least the GPU's share is what lets it hold experts at all.  The experts it holds
1113    // (place_experts) and the copies stay within what Windows can still commit, less max(8 GB, 10% of the RAM) for the
1114    // other programs - commit_kept: the experts that kept off the GPU, pagefile_hint: the page file (GB) that would hold
1115    // them (the log's WARNING, a NOTE and INFO for the server)
1116    double commit_kept = 0, pagefile_hint = 0;
1117    double commit_margin() const {
1118        const os::Commit c = os::commit();
1119        return std::max(8.0 * (double) (1ull << 30), c.ram == ~uint64_t{0} ? 0.0 : 0.1 * (double) c.ram);
1120    }
1121    // what may still be committed beside the margin (~inf: nothing limits it; DS4_COMMIT_CAP_GB: at most that, tests)
1122    double commit_room() const {
1123        const os::Commit c = os::commit();
1124        double avail = c.avail == ~uint64_t{0} ? 1e300 : (double) c.avail;
1125        if (const char* v = std::getenv("DS4_COMMIT_CAP_GB")) avail = std::min(avail, std::atof(v) * 1e9);
1126        return avail >= 1e300 ? 1e300 : std::max(0.0, avail - commit_margin());
1127    }
1128    // a device whose allocations Windows charges to the commit: an integrated GPU (DS4_COMMIT_CAP_GB: any, tests)
1129    bool commit_charged(const Dev& d) const {
1130        if (std::getenv("DS4_COMMIT_CAP_GB") != nullptr) return true;
1131#if defined(_WIN32)
1132        int v = 0;
1133        if (cudaDeviceGetAttribute(&v, cudaDevAttrIntegrated, d.id) != cudaSuccess) {
1134            (void) cudaGetLastError();
1135            return false;
1136        }
1137        return v != 0;
1138#else
1139        (void) d;
1140        return false;
1141#endif
1142    }
1143    bool copy_mode = false;
1144    std::vector<std::array<uint8_t*, 2>> ram_part;   // slot -> its parts
1145    std::vector<std::array<size_t, 4>> cp_lay;       // layer -> part offsets of gate, up, down rows; a part's bytes
1146    std::vector<int> copy_spare;                      // layer -> its spare slot (-1: none)
1147    std::mutex sw_mu;
1148    std::condition_variable sw_cv;
1149    std::deque<Swap> sw_queue;
1150    std::vector<Swap> sw_ready;
1151    std::condition_variable sw_done_cv;   // (a swap landed in sw_ready: the deterministic boundary waits for all of them)
1152    struct SwapBufs {
1153        uint8_t *a = nullptr, *b = nullptr, *h = nullptr;
1154        std::vector<cudaStream_t> st;   // a copy stream a device
1155    };
1156    std::vector<SwapBufs> sw_bufs;
1157    std::vector<std::thread> cache_ths;
1158    int sw_inflight = 0;
1159    int64_t decay_tokens = 0;
1160    bool check_swaps = std::getenv("DS4_CHECK_SWAPS") != nullptr;
1161    std::vector<float> host_logits;
1162    std::vector<void*> host_allocs;
1163    std::FILE* dump_h = std::getenv("DS4_DUMP_H") ? std::fopen(std::getenv("DS4_DUMP_H"), "wb") : nullptr;
1164    // DS4_DUMP_L: (threads) every layer's residual streams as records [layer, p0, T, T x hc x dim floats], window or
1165    // chunk path (tests: where the two part)
1166    std::FILE* dump_l = std::getenv("DS4_DUMP_L") ? std::fopen(std::getenv("DS4_DUMP_L"), "wb") : nullptr;
1167    // DS4_DUMP_R: the chunk path's routing, a record a layer [layer, p0, T, k, n_exp, n_vs, n_slots, kPicks] (int64),
1168    // then the picks' experts [T kPicks] (the first k of each token's), each expert's virtual slot [n_exp], the
1169    // slots' row bounds [n_vs + 1], the sorted rows' tokens [T k] (int32), the gate's logits [T n_exp] and its bias
1170    // [n_exp] (F32)
1171    std::FILE* dump_r = std::getenv("DS4_DUMP_R") ? std::fopen(std::getenv("DS4_DUMP_R"), "wb") : nullptr;
1172    // DS4_DUMP_Y=<layer>:<file> (layer -1: every layer): its expert sets on the chunk path, a record a piece [layer,
1173    // row0, rows, n_exp, wbase kind (0 VRAM, 1 ring), max_rows] (int64), its bounds [n_exp + 1], its h rows [rows ff]
1174    // (F16) and y rows [rows dim] (F32)
1175    int dump_y_layer = std::getenv("DS4_DUMP_Y") ? std::atoi(std::getenv("DS4_DUMP_Y")) : -1;
1176    std::FILE* dump_y = [] {
1177        const char* v = std::getenv("DS4_DUMP_Y");
1178        const char* f = v != nullptr ? std::strchr(v, ':') : nullptr;
1179        return f != nullptr ? std::fopen(f + 1, "wb") : nullptr;
1180    }();
1181    std::mutex dump_mu;
1182    // DS4_PROF: the GPU's time a decoded token by stage - events in stream order at a layer's start, after its
1183    // attention, after the routing and the shared expert, after the experts' gate / up, after the wait for the CPU
1184    // lane, after the down pass and the post - read after the token's sync, each the time since the mark before it
1185    bool prof_on = std::getenv("DS4_PROF") != nullptr;
1186    // DS4_PRED_DUMP=file (predictor data, the chunked prompt path): per layer and chunk u8 layer, u16 T, T x 384 fp16 router
1187    // logits, T x 256 fp16 projection of the router input.  DS4_XIN_DUMP=file (expert similarity inputs): u8 layer, u16 T,
1188    // T x D fp32 router inputs, the first DS4_XIN_N (1024) tokens of each layer.
1189    std::FILE* pred_f = std::getenv("DS4_PRED_DUMP") != nullptr ? std::fopen(std::getenv("DS4_PRED_DUMP"), "wb") : nullptr;
1190    std::FILE* xin_f = std::getenv("DS4_XIN_DUMP") != nullptr ? std::fopen(std::getenv("DS4_XIN_DUMP"), "wb") : nullptr;
1191    int xin_n = std::getenv("DS4_XIN_N") ? std::atoi(std::getenv("DS4_XIN_N")) : 1024;
1192    std::array<int, 64> xin_got{};
1193    std::FILE* trace_f = std::getenv("DS4_TRACE") != nullptr ? std::fopen(std::getenv("DS4_TRACE"), "wb") : nullptr;
1194    struct ProfMark {
1195        const Dev* d;
1196        cudaEvent_t ev;
1197        int stage;
1198    };
1199    std::mutex prof_mu;
1200    std::vector<ProfMark> prof_marks;
1201    std::map<int, std::vector<cudaEvent_t>> prof_pool;   // by device: an event belongs to the device it was made on
1202    bool prof_window = false;   // (decode windows only: T == 1)
1203    // ... and a run of chunks' (prof_chunk): a layer's start, after its attention, after the routing and the shared
1204    // expert, after its experts (the streamed ones' waits for their reads in it); printed after the run
1205    bool prof_chunk = false;
1206    // DS4_PROF stages of the chunked prompt (finer ones than the decode's 0..5): 0 between layers, 1 attention rest (wq_b, wo,
1207    // hc_post), 2 router-side tail (shared expert), 3 experts (+ waits), 4 Engram, 5 attn mHC (mix, split, norm), 6 attention
1208    // projections (wq_a, wkv, compressor), 7 compressor + indexer, 8 q_b + rope, 9 sparse attention, 10 ffn mHC + router + sort
1209    double cprof_ms[16] = {};
1210    // DS4_PROF: the experts' kernels alone, by type (events around the gate/up and down calls of run_set)
1211    struct EkMark {
1212        cudaEvent_t e0, e1, e2;
1213        int tg, td, nrows, nexp, maxrows, dev, ff;
1214    };
1215    std::vector<EkMark> ek_marks;
1216    std::map<int, std::vector<cudaEvent_t>> ek_pool;   // by device
1217    cudaEvent_t ek_ev() {
1218        int cur = 0;
1219        cudaGetDevice(&cur);
1220        std::vector<cudaEvent_t>& pl = ek_pool[cur];
1221        if (!pl.empty()) {
1222            cudaEvent_t e = pl.back();
1223            pl.pop_back();
1224            return e;
1225        }
1226        cudaEvent_t e = nullptr;
1227        cudaEventCreate(&e);
1228        return e;
1229    }
1230    void prof_mark(const Dev& d, int stage) {
1231        if (!prof_window && !prof_chunk) return;
1232        std::lock_guard<std::mutex> lk(prof_mu);
1233        int cur = 0;
1234        cudaGetDevice(&cur);
1235        cudaSetDevice(d.id);   // (events of another device are an "invalid resource handle")
1236        cudaEvent_t e = nullptr;
1237        std::vector<cudaEvent_t>& pool = prof_pool[d.id];
1238        if (pool.empty()) cudaEventCreate(&e);
1239        else {
1240            e = pool.back();
1241            pool.pop_back();
1242        }
1243        cudaEventRecord(e, d.st);
1244        cudaSetDevice(cur);
1245        prof_marks.push_back({&d, e, stage});
1246    }
1247    void prof_collect() {
1248        if (!prof_window && !prof_chunk) return;
1249        std::lock_guard<std::mutex> lk(prof_mu);
1250        std::vector<std::pair<const Dev*, cudaEvent_t>> last;
1251        for (const ProfMark& m : prof_marks) {
1252            auto it = std::find_if(last.begin(), last.end(), [&](const auto& x) { return x.first == m.d; });
1253            if (it != last.end()) {
1254                float ms = 0.0f;
1255                cudaSetDevice(m.d->id);
1256                if (cudaEventElapsedTime(&ms, it->second, m.ev) == cudaSuccess)
1257                    (prof_chunk ? cprof_ms : st.prof_ms)[m.stage] += ms;
1258                it->second = m.ev;
1259            } else {
1260                last.push_back({m.d, m.ev});
1261            }
1262        }
1263        for (const ProfMark& m : prof_marks) prof_pool[m.d->id].push_back(m.ev);
1264        prof_marks.clear();
1265        if (!prof_chunk) ++st.prof_tokens;
1266    }
1267    void dump_layer(Dev& d, const float* h, int il, int64_t p0, int T) {
1268        std::vector<float> v((size_t) T * g.hc * g.dim);
1269        cudaSetDevice(d.id);
1270        cudaMemcpyAsync(v.data(), h, v.size() * 4, cudaMemcpyDeviceToHost, d.st);
1271        cudaStreamSynchronize(d.st);
1272        std::lock_guard<std::mutex> lk(dump_mu);
1273        const int64_t hdr[3] = {il, p0, T};
1274        std::fwrite(hdr, 8, 3, dump_l);
1275        std::fwrite(v.data(), 4, v.size(), dump_l);
1276        std::fflush(dump_l);
1277    }
1278
1279    ~Impl() {
1280        quit.store(true);
1281        if (warm_bg.joinable()) warm_bg.join();   // (the warm-up uses the BLAS handles destroyed below)
1282        eg_io.stop();   // (its threads write into h_eg)
1283        for (auto& w : workers) w->stop();
1284        for (size_t i = 0; i < chunks.size(); ++i)
1285            if (chunks[i] && chunks[i]->blas) {
1286                cudaSetDevice(devs[i].id);
1287                cublasDestroy(chunks[i]->blas);
1288            }
1289        quit.store(true);
1290        if (service.joinable()) service.join();
1291        if (store_bg.joinable()) store_bg.join();   // (the store's background fill: it checks quit between its pieces)
1292        {
1293            std::lock_guard<std::mutex> lk(pf_mu);
1294        }
1295        pf_cv.notify_all();
1296        if (pf_th.joinable()) pf_th.join();
1297        {
1298            std::lock_guard<std::mutex> lk(sw_mu);
1299        }
1300        sw_cv.notify_all();
1301        ram_cv.notify_all();
1302        for (std::thread& t : cache_ths)
1303            if (t.joinable()) t.join();
1304        {
1305            std::lock_guard<std::mutex> lk(ac.mu);
1306        }
1307        ac.cv.notify_all();
1308        if (ac.th.joinable()) ac.th.join();
1309        if (ac.pin != nullptr) cudaFreeHost(ac.pin);
1310        if (ram_th.joinable()) ram_th.join();
1311        for (size_t i = 0; i < ram_chunks.size(); ++i) os::anon_free(ram_chunks[i], ram_chunk_bytes[i]);
1312        for (Dev& d : devs) {
1313            cudaSetDevice(d.id);
1314            for (void* p : d.allocs) cudaFree(p);
1315            if (d.st) cudaStreamDestroy(d.st);
1316            if (d.ev) cudaEventDestroy(d.ev);
1317        }
1318        for (void* p : host_allocs) cudaFreeHost(p);
1319        for (Layer& l : L)
1320            for (uint8_t* b : l.host)
1321                if (b != nullptr) {
1322                    (void) b;   // host blobs live in one mapping per layer, unmapped below
1323                }
1324        for (auto& m : host_maps) {
1325            if (chunk > 0) cudaHostUnregister(m.first);
1326            os::anon_free(m.first, m.second);
1327        }
1328    }
1329    std::vector<std::pair<void*, size_t>> host_maps;
1330
1331    template <class T>
1332    bool dalloc(Dev& d, T*& p, size_t n, std::string& err, size_t* acct = nullptr) {
1333        void* v = nullptr;
1334        cudaSetDevice(d.id);
1335        const size_t b = align256(n * sizeof(T));
1336        if (cudaMalloc(&v, b) != cudaSuccess) {
1337            err = "cudaMalloc " + std::to_string(b >> 20) + " MiB on CUDA" + std::to_string(d.id) + " failed";
1338            return false;
1339        }
1340        // zeroed before anything lands in it: the loads copy in on the default stream, which the non-blocking d.st
1341        // does not order against - a zeroing still queued there could wipe the weights just copied
1342        if (cudaMemsetAsync(v, 0, b, d.st) != cudaSuccess || cudaStreamSynchronize(d.st) != cudaSuccess) {
1343            cudaFree(v);
1344            err = "zeroing " + std::to_string(b >> 20) + " MiB on CUDA" + std::to_string(d.id) + " failed";
1345            return false;
1346        }
1347        d.allocs.push_back(v);
1348        if (acct) *acct += b;
1349        else d.scratch += b;
1350        p = (T*) v;
1351        return true;
1352    }
1353    static Layer& member(Layer& l, int m) { return m == 0 ? l : l.mates[(size_t) m - 1]; }
1354    static const Layer& member(const Layer& l, int m) { return m == 0 ? l : l.mates[(size_t) m - 1]; }
1355    // bytes of a VRAM slot of l's experts (a member's part of each, in a group)
1356    static size_t unit(const Layer& l) { return l.nm > 1 ? l.hblob : l.blob; }
1357    // the members of a group of nm that take heads: the most the heads and the wo_a groups split among evenly (64
1358    // heads and 8 groups: 9 -> 8, 7 or 6 -> 4, 5 -> 4, 3 -> 2); the first members the rest, only their FFN share
1359    int head_members(int nm) const {
1360        int na = nm;
1361        while (na > 1 && (g.heads % na != 0 || g.o_groups % na != 0)) --na;
1362        return na;
1363    }
1364    // host-mapped memory (the same address on the host and every device), zeroed
1365    template <class T>
1366    bool hmap(T*& p, size_t n, std::string& err) {
1367        void* v = nullptr;
1368        if (cudaHostAlloc(&v, n * sizeof(T) + 64, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) {
1369            err = "host-mapped memory (" + std::to_string((n * sizeof(T)) >> 20) + " MiB)";
1370            return false;
1371        }
1372        std::memset(v, 0, n * sizeof(T) + 64);
1373        host_allocs.push_back(v);
1374        p = (T*) v;
1375        return true;
1376    }
1377    template <class T>
1378    bool halloc(T*& p, size_t n, std::string& err) {
1379        void* v = nullptr;
1380        if (cudaHostAlloc(&v, n * sizeof(T) + 64, cudaHostAllocPortable) != cudaSuccess) {
1381            err = "cudaHostAlloc " + std::to_string((n * sizeof(T)) >> 20) + " MiB failed";
1382            return false;
1383        }
1384        host_allocs.push_back(v);
1385        p = (T*) v;
1386        return true;
1387    }
1388
1389    // ---- weights
1390    bool upload(Dev& d, const Tensor& t, void* dst, std::string& err) {
1391        std::vector<uint8_t> tmp(t.bytes);
1392        if (!pk.read(t, tmp.data())) {
1393            err = "read failed";
1394            return false;
1395        }
1396        cudaSetDevice(d.id);
1397        CK(cudaMemcpy(dst, tmp.data(), t.bytes, cudaMemcpyHostToDevice));
1398        return true;
1399    }
1400    // a dense matrix in a ggml block type (x3::Mat fmt kFmtGG, row = k / 256 blocks): whole, or part of its rows / inputs
1401    bool mat_gg(Dev& d, const std::string& pre, const Tensor& t, int ggt, x3::Mat& m, std::string& err, size_t* acct, int part,
1402                int np, bool cols) {
1403        if (t.shape.size() != 2 || t.shape[1] % 256 != 0) {
1404            err = pre + ": a " + t.dtype + " tensor that is not a matrix of whole blocks";
1405            return false;
1406        }
1407        int n = (int) t.shape[0], k = (int) t.shape[1];
1408        const size_t rb = gg::type_row_bytes(ggt, k), bb = rb / ((size_t) k / 256);
1409        std::vector<uint8_t> w((size_t) n * rb);
1410        if (t.bytes != w.size() || !pk.read(t, w.data())) {
1411            err = pre + ": read failed";
1412            return false;
1413        }
1414        if (np > 1) {
1415            const int whole = cols ? n : k, wd = whole / np;
1416            if (whole % np != 0 || wd % (cols ? 1 : 256) != 0) {
1417                err = pre + ": " + std::to_string(whole) + (cols ? " outputs" : " inputs") + " do not split in " + std::to_string(np) + " parts";
1418                return false;
1419            }
1420            std::vector<uint8_t> p;
1421            if (cols) {
1422                p.assign(w.begin() + (long) ((size_t) part * wd * rb), w.begin() + (long) ((size_t) (part + 1) * wd * rb));
1423                n = wd;
1424            } else {
1425                const size_t pb = (size_t) (wd / 256) * bb, off = (size_t) (part * wd / 256) * bb;
1426                p.resize((size_t) n * pb);
1427                for (size_t r = 0; r < (size_t) n; ++r) std::memcpy(p.data() + r * pb, w.data() + r * rb + off, pb);
1428                k = wd;
1429            }
1430            w.swap(p);
1431        }
1432        uint8_t* dp = nullptr;
1433        if (!dalloc(d, dp, w.size(), err, acct)) return false;
1434        cudaSetDevice(d.id);
1435        CK(cudaMemcpy(dp, w.data(), w.size(), cudaMemcpyHostToDevice));
1436        m = x3::Mat{};
1437        m.fmt = gg::kFmtGG;
1438        m.K = ggt;
1439        m.raw = dp;
1440        m.k = k;
1441        m.n = n;
1442        m.ld = (int) gg::type_row_bytes(ggt, k);
1443        return true;
1444    }
1445    // a GGUF's BF16 or Q8_0 matrix ([out][in]) onto the device, as mat() takes an EXL3 one: whole, or part `part` of its
1446    // columns (outputs: a range of its rows) or of its rows (inputs: a range of each row, whole Q8_0 blocks) - a
1447    // standalone [n][k] matrix
1448    bool mat_bf16(Dev& d, const std::string& pre, const Tensor& t, x3::Mat& m, std::string& err, size_t* acct, int part,
1449                  int np, bool cols) {
1450        const bool q8 = t.dtype == "Q8_0";
1451        // a ggml K-quant dense matrix (Q4_K / Q5_K / Q6_K: 256 values a block; the GEMV path of ds4_iq)
1452        const int ggt = (t.dtype == "Q4_K" || t.dtype == "Q5_K" || t.dtype == "Q6_K") ? gg_type_of(t.dtype) : -1;
1453        if (ggt > 0) return mat_gg(d, pre, t, ggt, m, err, acct, part, np, cols);
1454        if (t.shape.size() != 2 || (q8 && t.shape[1] % 32 != 0)) {
1455            err = pre + ": a " + t.dtype + " tensor that is not a matrix";
1456            return false;
1457        }
1458        int n = (int) t.shape[0], k = (int) t.shape[1];
1459        // a row's bytes, and the bytes of v of its values (BF16: 2 each; Q8_0: 34 every 32)
1460        auto bytes_of = [&](size_t v) { return q8 ? v / 32 * gg::kQ8Bytes : v * 2; };
1461        std::vector<uint8_t> w((size_t) n * bytes_of((size_t) k));
1462        if (t.bytes != w.size() || !pk.read(t, w.data())) {
1463            err = pre + ": read failed";
1464            return false;
1465        }
1466        if (np > 1) {
1467            const int whole = cols ? n : k, wd = whole / np;
1468            if (whole % np != 0 || wd % (q8 ? 32 : 8) != 0) {
1469                err = pre + ": " + std::to_string(whole) + (cols ? " outputs" : " inputs") + " do not split in " +
1470                      std::to_string(np) + " parts";
1471                return false;
1472            }
1473            const size_t rb = bytes_of((size_t) k);
1474            std::vector<uint8_t> p;
1475            if (cols) {
1476                p.assign(w.begin() + (long) ((size_t) part * wd * rb), w.begin() + (long) ((size_t) (part + 1) * wd * rb));
1477                n = wd;
1478            } else {
1479                const size_t pb = bytes_of((size_t) wd);
1480                p.resize((size_t) n * pb);
1481                for (size_t r = 0; r < (size_t) n; ++r)
1482                    std::memcpy(p.data() + r * pb, w.data() + r * rb + bytes_of((size_t) part * wd), pb);
1483                k = wd;
1484            }
1485            w.swap(p);
1486        }
1487        uint8_t* dp = nullptr;
1488        if (!dalloc(d, dp, w.size(), err, acct)) return false;
1489        cudaSetDevice(d.id);
1490        CK(cudaMemcpy(dp, w.data(), w.size(), cudaMemcpyHostToDevice));
1491        m = x3::Mat{};
1492        m.fmt = q8 ? gg::kFmtQ8_0 : gg::kFmtBF16;
1493        m.raw = dp;
1494        m.k = k;
1495        m.n = n;
1496        m.ld = q8 ? (int) bytes_of((size_t) k) : k;
1497        return true;
1498    }
1499    // a Q8_0 tensor's values as F32 (host)
1500    static std::vector<float> q8_values(const uint8_t* q, size_t n) {
1501        std::vector<float> v(n);
1502        for (size_t b = 0; b < n / 32; ++b) {
1503            const uint8_t* p = q + b * gg::kQ8Bytes;
1504            const float d = f16_to_f32((uint16_t) (p[0] | p[1] << 8));
1505            for (int j = 0; j < 32; ++j) v[b * 32 + j] = d * (float) (int8_t) p[2 + j];
1506        }
1507        return v;
1508    }
1509    // an EXL3 matrix onto the device: whole, or (np > 1) part `part` of its columns (cols) or of its rows - a standalone
1510    // matrix of its own (the rotations' 128-blocks stay whole)
1511    // (rot: split128's - an EXL3 matrix's uneven 128-block shares going round the members; a GGUF's BF16 / Q8_0 matrix
1512    // splits evenly, its groups only as wide as that goes)
1513    bool mat(Dev& d, const std::string& pre, x3::Mat& m, std::string& err, size_t* acct, int part = 0, int np = 1,
1514             bool cols = true, int rot = 0) {
1515        if (const Tensor* tw = pk.get(pre + ".weight"); tw != nullptr && (tw->dtype == "BF16" || tw->dtype == "Q8_0" || tw->dtype == "Q4_K" || tw->dtype == "Q5_K" || tw->dtype == "Q6_K"))
1516            return mat_bf16(d, pre, *tw, m, err, acct, part, np, cols);
1517        const Tensor* tr = pk.get(pre + ".trellis");
1518        const Tensor* su = pk.get(pre + ".suh");
1519        const Tensor* sv = pk.get(pre + ".svh");
1520        if (tr == nullptr || su == nullptr || sv == nullptr || tr->shape.size() != 3) {
1521            err = pre + ": not an EXL3 matrix in the pack";
1522            return false;
1523        }
1524        if (pk.get(pre + ".mul1") == nullptr) {
1525            err = pre + ": only the mul1 codebook is covered";
1526            return false;
1527        }
1528        m.k = (int) tr->shape[0] * 16;
1529        m.n = (int) tr->shape[1] * 16;
1530        m.K = (int) tr->shape[2] / 16;
1531        m.cb = 2;
1532        m.ld = 0;
1533        if (np > 1) {
1534            const int whole = cols ? m.n : m.k;
1535            int at = 0, w = 0;
1536            if (whole % 128 != 0 || whole / 128 < np) {
1537                err = pre + ": " + std::to_string(whole) + (cols ? " columns" : " rows") + " do not split in " +
1538                      std::to_string(np) + " parts of 128-blocks";
1539                return false;
1540            }
1541            split128(whole, np, part, at, w, rot);
1542            std::vector<uint8_t> t0(tr->bytes), u0(su->bytes), v0(sv->bytes);
1543            if (!pk.read(*tr, t0.data()) || !pk.read(*su, u0.data()) || !pk.read(*sv, v0.data())) {
1544                err = pre + ": read failed";
1545                return false;
1546            }
1547            const size_t tile = tr->bytes / ((size_t) (m.k / 16) * (m.n / 16));
1548            std::vector<uint8_t> t1, u1, v1;
1549            if (cols) {   // the tiles [c0 / 16, (c0 + w) / 16) of each 16-row slice, svh [c0, c0 + w)
1550                const size_t c0 = (size_t) at, nt = (size_t) m.n / 16, nth = (size_t) w / 16;
1551                t1.resize((size_t) (m.k / 16) * nth * tile);
1552                for (size_t sl = 0; sl < (size_t) m.k / 16; ++sl)
1553                    std::memcpy(t1.data() + sl * nth * tile, t0.data() + (sl * nt + c0 / 16) * tile, nth * tile);
1554                u1 = u0;
1555                v1.assign(v0.begin() + (long) (c0 * 2), v0.begin() + (long) ((c0 + w) * 2));
1556                m.n = w;
1557            } else {      // the 16-row slices [r0 / 16, (r0 + w) / 16), suh [r0, r0 + w)
1558                const size_t r0 = (size_t) at, row = (size_t) (m.n / 16) * tile;
1559                t1.assign(t0.begin() + (long) (r0 / 16 * row), t0.begin() + (long) ((r0 + w) / 16 * row));
1560                u1.assign(u0.begin() + (long) (r0 * 2), u0.begin() + (long) ((r0 + w) * 2));
1561                v1 = v0;
1562                m.k = w;
1563            }
1564            uint32_t* dt = nullptr;
1565            uint16_t *ds = nullptr, *dv = nullptr;
1566            if (!dalloc(d, dt, t1.size() / 4, err, acct) || !dalloc(d, ds, u1.size() / 2, err, acct) ||
1567                !dalloc(d, dv, v1.size() / 2, err, acct))
1568                return false;
1569            cudaSetDevice(d.id);
1570            CK(cudaMemcpy(dt, t1.data(), t1.size(), cudaMemcpyHostToDevice));
1571            CK(cudaMemcpy(ds, u1.data(), u1.size(), cudaMemcpyHostToDevice));
1572            CK(cudaMemcpy(dv, v1.data(), v1.size(), cudaMemcpyHostToDevice));
1573            m.trellis = dt;
1574            m.suh = ds;
1575            m.svh = dv;
1576            return x3::supported(m) || (err = pre + ": a part not covered by the EXL3 kernels", false);
1577        }
1578        uint32_t* dt = nullptr;
1579        uint16_t *ds = nullptr, *dv = nullptr;
1580        if (!dalloc(d, dt, tr->bytes / 4, err, acct) || !dalloc(d, ds, su->bytes / 2, err, acct) ||
1581            !dalloc(d, dv, sv->bytes / 2, err, acct))
1582            return false;
1583        if (!upload(d, *tr, dt, err) || !upload(d, *su, ds, err) || !upload(d, *sv, dv, err)) return false;
1584        m.trellis = dt;
1585        m.suh = ds;
1586        m.svh = dv;
1587        if (!x3::supported(m)) {
1588            err = pre + ": k " + std::to_string(m.k) + " n " + std::to_string(m.n) + " K " + std::to_string(m.K) +
1589                  " not covered by the EXL3 kernels";
1590            return false;
1591        }
1592        return true;
1593    }
1594    // a float tensor (F32 / F16 / BF16) as F32 on the device
1595    bool f32(Dev& d, const std::string& name, float*& p, std::string& err, size_t* acct, size_t want = 0) {
1596        const Tensor* t = pk.get(name);
1597        if (t == nullptr) {
1598            err = name + ": not in the pack";
1599            return false;
1600        }
1601        std::vector<uint8_t> raw(t->bytes);
1602        if (!pk.read(*t, raw.data())) {
1603            err = name + ": read failed";
1604            return false;
1605        }
1606        size_t n = 0;
1607        std::vector<float> v;
1608        if (t->dtype == "F32") {
1609            n = t->bytes / 4;
1610            v.resize(n);
1611            std::memcpy(v.data(), raw.data(), t->bytes);
1612        } else if (t->dtype == "F16" || t->dtype == "BF16") {
1613            n = t->bytes / 2;
1614            v.resize(n);
1615            const uint16_t* s = (const uint16_t*) raw.data();
1616            for (size_t i = 0; i < n; ++i) v[i] = t->dtype == "F16" ? f16_to_f32(s[i]) : bf16_to_f32(s[i]);
1617        } else if (t->dtype == "Q8_0") {   // (a GGUF's router may come so)
1618            n = t->bytes / gg::kQ8Bytes * 32;
1619            v = q8_values(raw.data(), n);
1620        } else {
1621            err = name + ": dtype " + t->dtype + " is not a float";
1622            return false;
1623        }
1624        if (want != 0 && n != want) {
1625            err = name + ": " + std::to_string(n) + " values, expected " + std::to_string(want);
1626            return false;
1627        }
1628        if (!dalloc(d, p, n, err, acct)) return false;
1629        cudaSetDevice(d.id);
1630        CK(cudaMemcpy(p, v.data(), n * 4, cudaMemcpyHostToDevice));
1631        return true;
1632    }
1633    bool f16raw(Dev& d, const std::string& name, uint16_t*& p, std::string& err, size_t* acct) {
1634        const Tensor* t = pk.get(name);
1635        if (t != nullptr && (t->dtype == "F32" || t->dtype == "BF16" || t->dtype == "Q8_0")) {   // (a GGUF's)
1636            const size_t n = t->dtype == "Q8_0" ? t->bytes / gg::kQ8Bytes * 32 : t->bytes / (t->dtype == "F32" ? 4 : 2);
1637            std::vector<uint8_t> raw(t->bytes);
1638            if (!pk.read(*t, raw.data())) {
1639                err = name + ": read failed";
1640                return false;
1641            }
1642            const std::vector<float> q = t->dtype == "Q8_0" ? q8_values(raw.data(), n) : std::vector<float>();
1643            std::vector<uint16_t> h(n);
1644            for (size_t i = 0; i < n; ++i) {
1645                float v;
1646                if (t->dtype == "F32") std::memcpy(&v, raw.data() + i * 4, 4);
1647                else if (t->dtype == "Q8_0") v = q[i];
1648                else v = bf16_to_f32(((const uint16_t*) raw.data())[i]);
1649                h[i] = strata::kernels::f16_from_f32(v);
1650            }
1651            if (!dalloc(d, p, n, err, acct)) return false;
1652            cudaSetDevice(d.id);
1653            CK(cudaMemcpy(p, h.data(), n * 2, cudaMemcpyHostToDevice));
1654            return true;
1655        }
1656        if (t == nullptr || t->dtype != "F16") {
1657            err = name + ": not an F16 tensor in the pack";
1658            return false;
1659        }
1660        if (!dalloc(d, p, t->bytes / 2, err, acct)) return false;
1661        return upload(d, *t, p, err);
1662    }
1663
1664    size_t mat_bytes(const std::string& pre) const {
1665        if (const Tensor* t = pk.get(pre + ".weight")) return align256(t->bytes);
1666        size_t b = 0;
1667        for (const char* s : {".trellis", ".suh", ".svh"})
1668            if (const Tensor* t = pk.get(pre + s)) b += align256(t->bytes);
1669        return b;
1670    }
1671    size_t tensor_bytes(const std::string& name) const {
1672        const Tensor* t = pk.get(name);
1673        return t ? align256(t->bytes * (t->dtype == "F32" ? 1 : 2)) : 0;
1674    }
1675
1676    // ---- expert regions and blob layout
1677    // a GGUF's MXFP4 experts: the blob is gate | up | down ([out][in / 32] blocks each, as the file holds them), every
1678    // expert's matrix r at the same stride from expert 0's in one file (the GGUF's [n_exp][out][in] tensor)
1679    // (the other block types: lay.fmt stays kFmtMXFP4 - read in place as these - and lay.K[r] is role r's ggml type)
1680    static int gg_type_of(const std::string& dtype) {
1681        for (int t : {gg::kTypeMXFP4, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 29, 145, 146, 224, 225, 226, 227})
1682            if (dtype == gg::type_name(t)) return t;
1683        return -1;
1684    }
1685    bool expert_layout_mx(Layer& l, std::string& err) {
1686        const std::string P = l.name + "ffn.experts.";
1687        const char* parts[3] = {"w1", "w3", "w2"};   // gate, up, down
1688        size_t off = 0;
1689        for (int r = 0; r < 3; ++r) {
1690            const int n = r < 2 ? g.ff : g.dim, k = r < 2 ? g.dim : g.ff;
1691            const Tensor* t0 = pk.get(P + "0." + parts[r] + ".weight");
1692            const Tensor* t1 = l.n_exp > 1 ? pk.get(P + "1." + parts[r] + ".weight") : t0;
1693            const int ty = t0 != nullptr ? gg_type_of(t0->dtype) : -1;
1694            const size_t bytes = ty > 0 ? (size_t) n * gg::type_row_bytes(ty, k) : 0;
1695            if (t0 == nullptr || t1 == nullptr || bytes == 0 || t0->bytes != bytes) {
1696                err = P + "0." + parts[r] + ": not an MXFP4 or low-bit [" + std::to_string(n) + "][" + std::to_string(k) +
1697                      "] matrix the engine reads (" + (t0 != nullptr ? t0->dtype : std::string("missing")) + ")";
1698                return false;
1699            }
1700            l.mx_file[r] = t0->file;
1701            l.mx_off[r] = t0->off;
1702            l.mx_stride[r] = l.n_exp > 1 ? t1->off - t0->off : bytes;
1703            for (int e = 0; e < l.n_exp; ++e) {
1704                const Tensor* t = pk.get(P + std::to_string(e) + "." + parts[r] + ".weight");
1705                if (t == nullptr || t->dtype != t0->dtype || t->bytes != bytes || t->file != l.mx_file[r] ||
1706                    t->off != l.mx_off[r] + (uint64_t) e * l.mx_stride[r]) {
1707                    err = P + std::to_string(e) + "." + parts[r] + ": missing, or not where the layer's others are";
1708                    return false;
1709                }
1710            }
1711            l.lay.trellis[r] = off;
1712            l.lay.suh[r] = l.lay.svh[r] = off;
1713            l.lay.K[r] = ty;
1714            off += align256(bytes) + (store_gb() > 0 ? ExpertStore::kSlack : 0);   // (the store's aligned reads spill into the gaps)
1715        }
1716        l.lay.fmt = gg::kFmtMXFP4;
1717        if (!gg::mx_experts(l.lay) && (gg::expert_type(l.lay, 0) != gg::expert_type(l.lay, 1) ||
1718                                       gg::expert_type(l.lay, 0) == gg::kTypeMXFP4 ||
1719                                       gg::expert_type(l.lay, 2) == gg::kTypeMXFP4)) {
1720            err = P + ": gate / up / down of types " + gg::type_name(l.lay.K[0]) + " / " + gg::type_name(l.lay.K[1]) +
1721                  " / " + gg::type_name(l.lay.K[2]) + " (gate and up must match; MXFP4 does not mix with the others)";
1722            return false;
1723        }
1724        l.blob = off;
1725        // a type the device kernels do not take (none of the i-quants now: gg::type_on_device lists them): the layer stays on the CPU lane, where
1726        // ggml-cpu's row dots read it - one warning, then the placement code keeps it out of VRAM
1727        for (int r = 0; r < 3; ++r)
1728            if (!gg::type_on_device(l.lay.K[r])) {
1729                l.cpu_only = true;
1730                std::fprintf(stderr,
1731                             "ds4: layer %d %s is %s: no GPU kernel for it, its experts stay on the CPU lane "
1732                             "(ggml-cpu's rows; VRAM tier: none)\n", l.il, r == 2 ? "down" : "gate/up",
1733                             gg::type_name(l.lay.K[r]));
1734                break;
1735            }
1736        return true;
1737    }
1738    const uint8_t* mx_mat(const Layer& l, int e, int r) const {   // expert e's matrix r: its RAM-tier slot, else the file's
1739        if (store) {
1740            const int s = store->find(l.il, e);
1741            if (s >= 0) return store->mat(s, r);
1742        }
1743        if (!l.ram.empty() && l.ram[(size_t) e] >= 0)   // (a copy with NH > 1: part 0's rows only - whole: read_mx)
1744            return copy_mode ? ram_part[(size_t) l.ram[(size_t) e]][0] + cp_lay[(size_t) l.il][(size_t) r]
1745                             : ram_slots[(size_t) l.ram[(size_t) e]] + l.lay.trellis[r];
1746        return pk.at(l.mx_file[r], l.mx_off[r] + (uint64_t) e * l.mx_stride[r]);
1747    }
1748    size_t mx_part_bytes(const Layer& l, int r) const {   // (its type's)
1749        return r < 2 ? (size_t) g.ff * gg::type_row_bytes(gg::expert_type(l.lay, r), g.dim)
1750                     : (size_t) g.dim * gg::type_row_bytes(gg::expert_type(l.lay, 2), g.ff);
1751    }
1752    // (copy_mode) matrix r's rows, and the rows of one NUMA part of it
1753    int mx_n(int r) const { return r < 2 ? g.ff : g.dim; }
1754    size_t mx_row_b(const Layer& l, int r) const { return mx_part_bytes(l, r) / (size_t) mx_n(r); }
1755    // part X's rows [X n / NH, ..) of expert e's matrix r: its copy's part on node X, else where the file has them
1756    const uint8_t* mx_part_ptr(const Layer& l, int e, int r, int X) const {
1757        if (copy_mode && l.ram[(size_t) e] >= 0)
1758            return ram_part[(size_t) l.ram[(size_t) e]][(size_t) X] + cp_lay[(size_t) l.il][(size_t) r];
1759        return mx_mat(l, e, r) + (size_t) X * (size_t) (mx_n(r) / NH) * mx_row_b(l, r);
1760    }
1761    // a copy's NH parts -> the blob, and back (each matrix's rows of part X at X n / NH rows into the blob's matrix)
1762    void ram_to_blob(const Layer& l, int s, uint8_t* blob) const {
1763        for (int r = 0; r < 3; ++r) {
1764            const size_t nb = (size_t) (mx_n(r) / NH) * mx_row_b(l, r);
1765            for (int X = 0; X < NH; ++X)
1766                std::memcpy(blob + l.lay.trellis[r] + (size_t) X * nb, ram_part[(size_t) s][(size_t) X] + cp_lay[(size_t) l.il][(size_t) r], nb);
1767        }
1768    }
1769    void blob_to_ram(const Layer& l, const uint8_t* blob, int s) const {
1770        for (int r = 0; r < 3; ++r) {
1771            const size_t nb = (size_t) (mx_n(r) / NH) * mx_row_b(l, r);
1772            for (int X = 0; X < NH; ++X)
1773                std::memcpy(ram_part[(size_t) s][(size_t) X] + cp_lay[(size_t) l.il][(size_t) r], blob + l.lay.trellis[r] + (size_t) X * nb, nb);
1774        }
1775    }
1776    // expert e (from the file) -> its blob; and member m of nm's part of a blob (gate / up rows [m n_ff / nm, ..), down
1777    // inputs of the same range: in each row the blocks [m n_ff / nm / 32, ..)) and back
1778    bool read_mx(const Layer& l, int e, uint8_t* blob) const {   // (from its RAM-tier slot or copy when it has one)
1779        if (!l.ram.empty() && l.ram[(size_t) e] >= 0) {
1780            if (copy_mode) ram_to_blob(l, l.ram[(size_t) e], blob);
1781            else std::memcpy(blob, ram_slots[(size_t) l.ram[(size_t) e]], l.blob);
1782            return true;
1783        }
1784        return read_mx_file(l, e, blob);
1785    }
1786    bool read_mx_file(const Layer& l, int e, uint8_t* blob) const {   // (the movers: never a slot that may change)
1787        for (int r = 0; r < 3; ++r)
1788            if (!pk.read_at(l.mx_file[r], l.mx_off[r] + (uint64_t) e * l.mx_stride[r], mx_part_bytes(l, r),
1789                            blob + l.lay.trellis[r]))
1790                return false;
1791        return true;
1792    }
1793    void mx_blob_to_half(const Layer& l, const uint8_t* blob, int m, uint8_t* dst) const {
1794        const int ffh = g.ff / l.nm;
1795        const size_t gr = gg::type_row_bytes(gg::expert_type(l.lay, 0), g.dim),
1796                     dr = gg::type_row_bytes(gg::expert_type(l.lay, 2), g.ff),
1797                     dh = gg::type_row_bytes(gg::expert_type(l.lay, 2), ffh);
1798        for (int r = 0; r < 2; ++r)
1799            std::memcpy(dst + l.hlay.trellis[r], blob + l.lay.trellis[r] + (size_t) m * ffh * gr, (size_t) ffh * gr);
1800        for (size_t row = 0; row < (size_t) g.dim; ++row)
1801            std::memcpy(dst + l.hlay.trellis[2] + row * dh, blob + l.lay.trellis[2] + row * dr + (size_t) m * dh, dh);
1802    }
1803    void mx_half_to_blob(const Layer& l, const uint8_t* src, int m, uint8_t* blob) const {
1804        const int ffh = g.ff / l.nm;
1805        const size_t gr = gg::type_row_bytes(gg::expert_type(l.lay, 0), g.dim),
1806                     dr = gg::type_row_bytes(gg::expert_type(l.lay, 2), g.ff),
1807                     dh = gg::type_row_bytes(gg::expert_type(l.lay, 2), ffh);
1808        for (int r = 0; r < 2; ++r)
1809            std::memcpy(blob + l.lay.trellis[r] + (size_t) m * ffh * gr, src + l.hlay.trellis[r], (size_t) ffh * gr);
1810        for (size_t row = 0; row < (size_t) g.dim; ++row)
1811            std::memcpy(blob + l.lay.trellis[2] + row * dr + (size_t) m * dh, src + l.hlay.trellis[2] + row * dh, dh);
1812    }
1813
1814    bool expert_layout(Layer& l, std::string& err) {
1815        if (const Tensor* t = pk.get(l.name + "ffn.experts.0.w1.weight"); t != nullptr && gg_type_of(t->dtype) > 0)
1816            return expert_layout_mx(l, err);
1817        const std::string P = l.name + "ffn.experts.";
1818        const char* parts[3] = {"w1", "w3", "w2"};   // gate, up, down
1819        const char* pieces[3] = {".trellis", ".suh", ".svh"};
1820        l.region_off.resize((size_t) l.n_exp);
1821        l.region_bytes.resize((size_t) l.n_exp);
1822        l.region_file.resize((size_t) l.n_exp);
1823        size_t off = 0;
1824        for (int r = 0; r < 3; ++r) {
1825            const Tensor* tr = pk.get(P + "0." + parts[r] + ".trellis");
1826            if (tr == nullptr || pk.get(P + "0." + parts[r] + ".mul1") == nullptr) {
1827                err = P + "0." + parts[r] + ": not an EXL3 (mul1) matrix";
1828                return false;
1829            }
1830            l.lay.K[r] = (int) tr->shape[2] / 16;
1831            l.lay.trellis[r] = off;
1832            off += align256(tr->bytes);
1833            l.lay.suh[r] = off;
1834            off += align256(pk.get(P + "0." + parts[r] + ".suh")->bytes);
1835            l.lay.svh[r] = off;
1836            off += align256(pk.get(P + "0." + parts[r] + ".svh")->bytes);
1837        }
1838        l.lay.cb = 2;
1839        l.blob = off;
1840        for (int e = 0; e < l.n_exp; ++e) {
1841            const std::string E = P + std::to_string(e) + ".";
1842            uint64_t lo = UINT64_MAX, hi = 0;
1843            int file = -1;
1844            for (int r = 0; r < 3; ++r)
1845                for (int q = 0; q < 3; ++q) {
1846                    const Tensor* t = pk.get(E + parts[r] + pieces[q]);
1847                    if (t == nullptr) {
1848                        err = E + parts[r] + pieces[q] + ": missing";
1849                        return false;
1850                    }
1851                    if (file < 0) file = t->file;
1852                    if (t->file != file) {
1853                        err = E + ": split across files";
1854                        return false;
1855                    }
1856                    lo = std::min(lo, t->off);
1857                    hi = std::max(hi, t->off + t->bytes);
1858                    if (e == 0) l.piece_bytes[r][q] = t->bytes;
1859                    else if (t->bytes != l.piece_bytes[r][q]) {
1860                        err = E + parts[r] + ": not the shape of expert 0's";
1861                        return false;
1862                    }
1863                }
1864            l.region_off[(size_t) e] = lo;
1865            l.region_bytes[(size_t) e] = hi - lo;
1866            l.region_file[(size_t) e] = file;
1867            for (int r = 0; r < 3; ++r)
1868                for (int q = 0; q < 3; ++q) {
1869                    const size_t src = pk.get(E + parts[r] + pieces[q])->off - lo;
1870                    if (e == 0) l.piece_src[r][q] = src;
1871                    else if (src != l.piece_src[r][q]) {
1872                        err = E + ": the pieces lie differently from expert 0's";
1873                        return false;
1874                    }
1875                }
1876        }
1877        return true;
1878    }
1879    // the region of expert e (read from the file) -> its blob
1880    void repack(const Layer& l, const uint8_t* region, uint8_t* blob) const {
1881        for (int r = 0; r < 3; ++r) {
1882            const size_t dst[3] = {l.lay.trellis[r], l.lay.suh[r], l.lay.svh[r]};
1883            for (int q = 0; q < 3; ++q) std::memcpy(blob + dst[q], region + l.piece_src[r][q], l.piece_bytes[r][q]);
1884        }
1885    }
1886
1887    // the region of expert e -> its CPU-lane part X (columns [X n / NH, (X + 1) n / NH) of each matrix)
1888    void repack_part(const Layer& l, const uint8_t* region, int X, uint8_t* dst) const {
1889        for (int r = 0; r < 3; ++r) {
1890            const size_t tile = (size_t) 32 * l.lay.K[r];
1891            const int k = l.hl.k[r], nt = l.hl.n[r] * NH / 16, nth = l.hl.n[r] / 16;
1892            const uint8_t* tr = region + l.piece_src[r][0];
1893            for (int sl = 0; sl < k / 16; ++sl)
1894                std::memcpy(dst + l.hl.trellis[r] + (size_t) sl * nth * tile, tr + ((size_t) sl * nt + (size_t) X * nth) * tile,
1895                            (size_t) nth * tile);
1896            std::memcpy(dst + l.hl.suh[r], region + l.piece_src[r][1], (size_t) k * 2);
1897            std::memcpy(dst + l.hl.svh[r], region + l.piece_src[r][2] + (size_t) X * l.hl.n[r] * 2, (size_t) l.hl.n[r] * 2);
1898        }
1899    }
1900
1901    // ---- the lookahead adapter: DS4_AHEAD_ADAPTER=file ("DSAD", u32 r, u32 D, u32 n, then records i32 layer, U [D][r] f32,
1902    // V [r][n] f32), read once; a layer's U, V go to its device the first time its guess runs.  Only the guesses change
1903    // (the page cache's reads ahead), never the routing.
1904    std::map<int, std::pair<std::vector<float>, std::vector<float>>> ad_host;
1905    int ad_file_r = 0;
1906    std::map<int, float*> ad_tmps;   // device -> kWin x r floats
1907    bool ahead_adapter(Layer& l) {
1908        static const char* path = std::getenv("DS4_AHEAD_ADAPTER");
1909        if (path == nullptr) return false;
1910        static std::once_flag once;
1911        std::call_once(once, [&] {
1912            std::FILE* f = std::fopen(path, "rb");
1913            uint32_t h[4] = {0, 0, 0, 0};
1914            if (f == nullptr || std::fread(h, 4, 4, f) != 4 || h[0] != 0x44415344u || h[2] != (uint32_t) g.dim) {
1915                std::fprintf(stderr, "ds4: DS4_AHEAD_ADAPTER %s: not an adapter for this model, ignored\n", path);
1916                if (f) std::fclose(f);
1917                return;
1918            }
1919            ad_file_r = (int) h[1];
1920            for (;;) {
1921                int32_t il = 0;
1922                if (std::fread(&il, 4, 1, f) != 1) break;
1923                std::vector<float> U((size_t) h[2] * h[1]), V((size_t) h[1] * h[3]);
1924                if (std::fread(U.data(), 4, U.size(), f) != U.size() || std::fread(V.data(), 4, V.size(), f) != V.size()) break;
1925                ad_host[il] = {std::move(U), std::move(V)};
1926            }
1927            std::fclose(f);
1928            std::fprintf(stderr, "ds4: lookahead adapter: rank %d for %zu layers\n", ad_file_r, ad_host.size());
1929        });
1930        if (!l.ad_tried) {
1931            l.ad_tried = true;
1932            auto it = ad_host.find(l.il);
1933            if (it != ad_host.end() && cudaMalloc(&l.ad_U, it->second.first.size() * 4) == cudaSuccess &&
1934                cudaMalloc(&l.ad_V, it->second.second.size() * 4) == cudaSuccess) {
1935                cudaMemcpy(l.ad_U, it->second.first.data(), it->second.first.size() * 4, cudaMemcpyHostToDevice);
1936                cudaMemcpy(l.ad_V, it->second.second.data(), it->second.second.size() * 4, cudaMemcpyHostToDevice);
1937                l.ad_r = ad_file_r;
1938            }
1939        }
1940        return true;
1941    }
1942    // DS4_CP_STORE=1: at each window boundary, every layer's table of the experts that need no disk read (VRAM or the RAM
1943    // store), for Cache-Prior to favour; the store's contents there depend on the routing alone (each read a token asked
1944    // for has landed: the lane waited for it)
1945    bool cp_store_on() const {
1946        static const bool on = std::getenv("DS4_CP_STORE") != nullptr && std::atoi(std::getenv("DS4_CP_STORE")) != 0;
1947        return on && store != nullptr;
1948    }
1949    // DS4_CP_AUX=1: the expert GPU's experts count as resident too (their reads cost nothing)
1950    bool cp_aux_on() const {
1951        static const bool on = std::getenv("DS4_CP_AUX") != nullptr && std::atoi(std::getenv("DS4_CP_AUX")) != 0;
1952        return on && aux.n_experts > 0;
1953    }
1954    void cp_store_sync() {
1955        if (!cp_store_on() && !cp_aux_on()) return;
1956        for (Layer& l : L) {
1957            if (l.mtp || l.il >= g.nl || l.nm != 1) continue;
1958            std::vector<unsigned char> now((size_t) l.n_exp, 0);
1959            for (int e = 0; e < l.n_exp; ++e)
1960                now[(size_t) e] = l.slot[(size_t) e] >= 0 || (cp_store_on() && store->find(l.il, e) >= 0) ||
1961                                  (cp_aux_on() && !l.aux.empty() && l.aux[(size_t) e]);
1962            if (now == l.res_host) continue;
1963            l.res_host.swap(now);
1964            Dev& d = devs[(size_t) l.dev];
1965            cudaSetDevice(d.id);
1966            if (l.res_tab == nullptr && cudaMalloc((void**) &l.res_tab, (size_t) l.n_exp) != cudaSuccess) {
1967                l.res_tab = nullptr;
1968                continue;
1969            }
1970            cudaMemcpyAsync(l.res_tab, l.res_host.data(), (size_t) l.n_exp, cudaMemcpyHostToDevice, d.st);
1971        }
1972    }
1973    float* ad_tmp(const Dev& d, int r) {
1974        float*& t = ad_tmps[d.id];
1975        if (t == nullptr) cudaMalloc(&t, (size_t) kWin * r * 4);
1976        return t;
1977    }
1978
1979    // ---- loading
1980    bool load(const Options& opt, std::string& err) {
1981        o = opt;
1982        scr_master = [] { const char* v = std::getenv("STRATA_DS4_SCR"); return v != nullptr && std::string(v) == "1"; }();
1983        const double t0 = now_ms();
1984        if (!pk.load(o.pack, err)) return false;
1985        g.from(pk);
1986        if (g.dim == 0 || g.nl == 0 || (int) g.ratios.size() < g.nl) {
1987            err = o.pack + "/ds4.txt: incomplete geometry";
1988            return false;
1989        }
1990        if (g.hd != 512 || g.ix_hd != 128 || g.k_exp > 8 || g.hc > 8) {
1991            err = "geometry not covered (head_dim " + std::to_string(g.hd) + ", index_head_dim " +
1992                  std::to_string(g.ix_hd) + ", experts per token " + std::to_string(g.k_exp) + ")";
1993            return false;
1994        }
1995        freqs_win = rope_freqs(g.rd, 0, g.rope_theta, g.factor, g.beta_fast, g.beta_slow);
1996        freqs_comp = rope_freqs(g.rd, g.orig_ctx, g.comp_theta, g.factor, g.beta_fast, g.beta_slow);
1997
1998        // devices
1999        int ndev = 0;
2000        if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev == 0) {
2001            err = "no CUDA device";
2002            return false;
2003        }
2004        std::vector<int> ids = o.gpus;
2005        if (ids.empty())
2006            for (int i = 0; i < ndev; ++i) ids.push_back(i);
2007        devs.resize(ids.size());
2008        for (size_t i = 0; i < ids.size(); ++i) {
2009            Dev& d = devs[i];
2010            d.id = ids[i];
2011            CK(cudaSetDevice(d.id));
2012            CK(cudaStreamCreateWithFlags(&d.st, cudaStreamNonBlocking));
2013            CK(cudaEventCreateWithFlags(&d.ev, cudaEventDisableTiming));
2014            if (!x3::prepare(d.st) || (pk.gguf && !gg::prepare(d.st))) {
2015                err = "exl3 scratch on CUDA" + std::to_string(d.id);
2016                return false;
2017            }
2018            CK(cudaMemGetInfo(&d.free0, &d.total));
2019        }
2020        // the groups' width: o.tp, less while the experts' blocks do not split in it (a member takes n_ff / tp of each
2021        // expert: the down's inputs in whole blocks - a GGUF's 256-value types split n_ff 2304 in 1, 3 or 9 parts)
2022        int tp = o.tp;
2023        if (pk.gguf && tp > 1) {
2024            int blk = 32;
2025            for (const auto& kv : pk.t) {
2026                const std::string& n = kv.first;
2027                if (n.find(".ffn.experts.") == std::string::npos || n.size() < 9 ||
2028                    n.compare(n.size() - 9, 9, "w2.weight") != 0)
2029                    continue;
2030                const int ty = gg_type_of(kv.second.dtype);
2031                if (ty >= 0) blk = std::max(blk, gg::type_block(ty));
2032            }
2033            while (tp > 1 && (g.ff % tp != 0 || (g.ff / tp) % blk != 0 || (g.ff / tp) % (std::getenv("DS4_TP_ALIGN") ? std::atoi(std::getenv("DS4_TP_ALIGN")) : 128) != 0 || g.heads % tp != 0 ||
2034                              g.o_groups % tp != 0))
2035                --tp;
2036            if (tp != o.tp)
2037                std::fprintf(stderr, "ds4: tensor parallel %d -> %d: the experts' %d-value blocks split n_ff %d no other way "
2038                                     "(each GPU its own layers)\n", o.tp, tp, blk, g.ff);
2039        }
2040        // the groups: runs of tp devices of one kind (their memory), a device unlike the next alone
2041        // - or, tp the number of GPUs, one group of all of them whatever their kind (its tightest member sets the
2042        // experts' room); threads mode for the windows (decode) where a group is 2 wide or more or --threads on, the
2043        // prompt path (its own thread a GPU) as asked for - also where the experts' blocks took the groups' width down
2044        // to 1 (a 256-value type's: Maya's quants), which left every prompt in windows of 16
2045        par = o.threads || tp > 1;
2046        // the chunked (layer-major) prompt path: with --tp / --threads as before; --prefill-chunk N (N > 0) or
2047        // kChunkedPromptDefault bring it to a single card's default run too (a host thread a GPU for the prompt only;
2048        // decode stays as asked).  --prefill-chunk 0 keeps the windows of 16 (DS4_WINDOWS=1 the same).  Off by default
2049        // until a prompt costs the decode nothing: its buffers hold VRAM the windowed path gives to experts
2050        prompt_par = par || o.tp > 1 ||
2051                     ((o.prefill_chunk > 0 || (o.prefill_chunk < 0 && kChunkedPromptDefault)) &&
2052                      std::getenv("DS4_WINDOWS") == nullptr);
2053        const bool tp_all = tp > 1 && tp == (int) devs.size();
2054        for (size_t i = 0; i < devs.size();) {
2055            Group G;
2056            G.mem.push_back((int) i);
2057            size_t j = i + 1;
2058            while ((int) G.mem.size() < tp && j < devs.size() && (tp_all || devs[j].total == devs[i].total))
2059                G.mem.push_back((int) j++);
2060            if ((int) G.mem.size() < tp && G.mem.size() > 1) {   // a short run at the end: devices of their own
2061                for (int m : G.mem) {
2062                    Group one;
2063                    one.mem.push_back(m);
2064                    groups.push_back(one);
2065                }
2066            } else groups.push_back(G);
2067            i = j;
2068        }
2069        for (size_t gi = 0; gi < groups.size(); ++gi)
2070            for (size_t m = 0; m < groups[gi].mem.size(); ++m) {
2071                devs[(size_t) groups[gi].mem[m]].grp = (int) gi;
2072                devs[(size_t) groups[gi].mem[m]].mi = (int) m;
2073            }
2074        // whether the CPU lane's experts are read in place (--mmap-experts; auto: the pack's expert bytes beyond what the
2075        // GPUs can take - their free memory less the other weights and the prompt path's buffers - do not fit the RAM
2076        // this process can get beside kRamMargin), decided here because it sets the prompt chunk's default: in place
2077        // every chunk streams every expert VRAM does not hold from the files, so the larger the chunk the fewer times
2078        if (pk.gguf) file_experts = true;   // (a GGUF's: the files stay their source - copy_experts copies them into RAM
2079                                            // after VRAM's are in, by --mmap-experts)
2080        else if (o.mmap_experts >= 0) file_experts = o.mmap_experts > 0;
2081        else {
2082            double exp_b = 0, other_b = 0, room = 0;
2083            for (const auto& kt : pk.t) {
2084                const std::string& n = kt.first;
2085                if (n.find(".engram.embed.") != std::string::npos || n.rfind("vision.", 0) == 0 || n == "embed.weight" ||
2086                    (!o.dspark && n.rfind("mtp.", 0) == 0))
2087                    continue;
2088                (n.find(".ffn.experts.") != std::string::npos ? exp_b : other_b) += (double) kt.second.bytes;
2089            }
2090            for (const Dev& d : devs)
2091                room += std::max(0.0, (double) d.free0 - (double) ((size_t) o.reserve_mib << 20) -
2092                                          (prompt_par ? 1.5 : 0.4) * (1 << 30)) *
2093                        o.vram_experts;
2094            file_experts = exp_b - std::max(0.0, room - other_b) + (double) kRamMargin > (double) ram_avail();
2095        }
2096        // The default prompt chunk, one rule (ds4_experts_rule.hpp: prefill_chunk_default).  Measured: the chunked pass streams the experts the GPUs
2097        // do not hold once per chunk, so where they hold less than half of them a larger chunk is fewer passes (1 x R9700 + 251 GB, 8K prompt:
2098        // 1024 200, 2048 277, 4096 353, 8192 431 tok/s; RTX 5070 / 3060 12 GB in place: 8192 244 / 228 against 1024 186 / 175); where they hold
2099        // most (4 x R9700: 8192 214, 1024 370) the small one wins; with the experts copied into RAM (--mmap-experts off) 4096 beats 8192 by 7-9%
2100        // (H100 32 GiB: 2048 502, 4096 538, 8192 495).  A GGUF pack always has file_experts set (copied only by --mmap-experts off).
2101        const bool own_default = !(par || o.tp > 1);   // (a single-card run: no --threads, tp 1 - a launch with several cards passes --tp 1; one card passes neither)
2102        const bool gguf_copy = pk.gguf && (o.mmap_experts == 0 || (store_gb() <= 0.0 && auto_copy_all));
2103        uint64_t vmin_bytes = ~0ull;
2104        for (const Dev& dv : devs) vmin_bytes = std::min<uint64_t>(vmin_bytes, (uint64_t) dv.total);
2105        if (devs.empty()) vmin_bytes = 0;
2106#if defined(__HIP_PLATFORM_AMD__) || defined(__HIPCC__)
2107        const bool hip_build = true;
2108#else
2109        const bool hip_build = false;
2110#endif
2111        const int rule_chunk = prefill_chunk_default(own_default, gpu_expert_share(), gguf_copy, file_experts, hip_build, vmin_bytes, kVlRows);
2112        chunk = prompt_par ? (o.prefill_chunk >= 0 ? o.prefill_chunk : rule_chunk) : 0;
2113        if (prompt_par && o.prefill_chunk < 0 && rule_chunk == 4096 && gguf_copy)
2114            std::fprintf(stderr, "ds4: prompts in chunks of 4096 tokens (the experts are copied into RAM, %.0f GiB of graphics memory; --prefill-chunk N changes it)\n",
2115                         (double) vmin_bytes / (double) (1ull << 30));
2116        const char* dc = std::getenv("DS4_CHUNK");   // (tests: down to 16, a short prompt in several chunks)
2117        if (dc != nullptr) chunk = prompt_par ? std::atoi(dc) : 0;
2118        if (const char* v = std::getenv("DS4_CHUNK_MIN")) chunk_min = std::max(1, std::atoi(v));
2119        if (chunk > 0) {
2120            chunk = std::min(kMaxChunk, std::max(dc != nullptr ? 16 : 256, chunk / 16 * 16));
2121            eg_cap = (size_t) chunk;
2122            tap_cap = std::max(kWin, 128);
2123            if (const char* v = std::getenv("DS4_LEND")) {
2124                chunk_small_ = std::getenv("DS4_LEND_SMALL") ? std::atoi(std::getenv("DS4_LEND_SMALL")) / 16 * 16 : 4096;
2125                if (std::getenv("DS4_LEND_SLAB")) lend_slab_ = std::max(64, std::atoi(std::getenv("DS4_LEND_SLAB")) / 64 * 64);
2126                lend_min_ = chunk_small_ >= 256 && chunk > chunk_small_ ? std::max(1, std::atoi(v)) : 0;
2127            }
2128        } else   // (only as asked for: --prefill-chunk 0, or --tp 1 with --threads off)
2129            std::fprintf(stderr,
2130                         "ds4: prompts run in windows of %d tokens (%s): long prompts prefill far slower than in\n"
2131                         "     chunks (a 7-GPU RTX 3090 rig, Maya-S read in place: 8K / 32K tokens 115 / 99 tokens/s,\n"
2132                         "     461 / 1010 in chunks of %d) - %s\n",
2133                         kWin, o.prefill_chunk == 0 ? "--prefill-chunk 0" : "--tp 1 with --threads off", kVlRows,
2134                         o.prefill_chunk == 0 ? "leave --prefill-chunk out for chunks"
2135                                              : "leave --tp 1 out, or pass --threads on, for chunks");
2136        // the vision tower on the first GPU, before the split: the layers get what it leaves
2137        if (o.vision && !load_vision(err)) {   // (a tower that cannot load leaves the model reading text: said loudly,
2138            if (o.vision_only) return false;   // and the server is told pictures are off - info_lines)
2139            std::fprintf(stderr, "ds4: WARNING: the vision tower did not load (%s): pictures are OFF, the model reads "
2140                                 "text only\n", err.c_str());
2141            vision_err = err.empty() ? "unknown reason" : err;
2142            err.clear();
2143            vt.release();
2144            img_tok = -1;
2145        }
2146        if (o.vision_only) return true;
2147
2148        // layers: roles and the sources they read
2149        if (o.dspark_auto && o.dspark && g.n_mtp > 0) {   // (see Options::dspark_auto)
2150            double exp_b = 0, room_b = 0;
2151            for (const auto& kt : pk.t)
2152                if (kt.first.rfind("layers.", 0) == 0 && kt.first.find(".ffn.experts.") != std::string::npos) exp_b += (double) kt.second.bytes;
2153            for (const Dev& d : devs) room_b += std::max(0.0, (double) d.free0 - (double) ((size_t) o.reserve_mib << 20));
2154            if (exp_b > 1.5 * room_b) {
2155                o.dspark = false;
2156                std::fprintf(stderr, "ds4: DSpark not loaded: the routed experts (%.0f GB) are far more than the GPU holds (%.0f GB), where its verify "
2157                                     "rounds read 3.3x a token's bytes and gain nothing (--dspark on loads it anyway)\n", exp_b / 1e9, room_b / 1e9);
2158            }
2159        }
2160        if (!o.dspark) g.n_mtp = 0;
2161        if (o.dspark_block > 0 && std::getenv("DS4_DSPARK_MAX") == nullptr) max_drafts = o.dspark_block;   // (--dspark-block N: at most N drafts a round)
2162        L.resize((size_t) (g.nl + g.n_mtp));
2163        int last_src = -1;
2164        int experts_used = 1 << 20;
2165        for (int il = 0; il < g.nl + g.n_mtp; ++il) {
2166            Layer& l = L[(size_t) il];
2167            l.il = il;
2168            l.mtp = il >= g.nl;
2169            l.name = l.mtp ? "mtp." + std::to_string(il - g.nl) + "." : "layers." + std::to_string(il) + ".";
2170            l.n_exp = l.mtp ? g.d_n_exp : g.n_exp;
2171            l.k_exp = l.mtp ? g.d_k : g.k_exp;
2172            if (!l.mtp) {   // experts a word takes: --experts N / the faster-mode rule (ds4_experts_rule.hpp), DS4_TOPK=N over both (a test)
2173                if (il == 0) {
2174                    uint64_t vram_all = 0;
2175                    bool integrated = false;   // (a GPU that shares the PC's RAM: Strix Halo)
2176                    for (const Dev& dv : devs) {
2177                        vram_all += (uint64_t) dv.total;
2178                        cudaDeviceProp ip{};
2179                        if (cudaGetDeviceProperties(&ip, dv.id) == cudaSuccess && ip.integrated) integrated = true;
2180                    }
2181                    const int n = experts_test_override(experts_per_word(o.experts, vram_all, l.k_exp, integrated), l.k_exp);
2182                    experts_used = n;
2183                    if (n < l.k_exp)
2184                        std::fprintf(stderr, "ds4: experts per word: %d (%s; full quality: --experts %d)\n", n,
2185                                     o.experts >= 1 ? "as asked" : "faster mode", l.k_exp);
2186                    else if (o.experts >= 1)
2187                        std::fprintf(stderr, "ds4: experts per word: %d (full quality)\n", n);
2188                }
2189                l.k_exp = std::min(l.k_exp, experts_used);
2190            }
2191            l.ratio = g.ratios[(size_t) il];
2192            if (l.mtp) {   // window attention only: no compressor, indexer or Engram
2193                if (l.ratio != 0 || l.n_exp <= 0 || l.k_exp <= 0 || l.k_exp > kPicks) {
2194                    err = l.name + ": a DSpark block of compress ratio " + std::to_string(l.ratio) + ", " +
2195                          std::to_string(l.n_exp) + " experts / " + std::to_string(l.k_exp) + " is not covered";
2196                    return false;
2197                }
2198                if (!expert_layout(l, err)) return false;
2199                continue;
2200            }
2201            l.kv_src = std::find(g.kv_src.begin(), g.kv_src.end(), il) != g.kv_src.end();
2202            l.ix_src = std::find(g.ix_src.begin(), g.ix_src.end(), il) != g.ix_src.end();
2203            l.owns_k = l.kv_src;
2204            l.cand_src = il == g.cand_src;
2205            l.uses_cand = g.cand_src >= 0 && g.cand_src < il && l.ix_src;
2206            if (l.kv_src) {
2207                Src s;
2208                s.layer = il;
2209                s.ratio = l.ratio;
2210                s.cap = (o.max_context + l.ratio - 1) / l.ratio + 1;
2211                srcs.push_back(s);
2212                last_src = (int) srcs.size() - 1;
2213            }
2214            if (l.ratio > 0) {
2215                if (last_src < 0 || srcs[(size_t) last_src].ratio != l.ratio) {
2216                    err = "layer " + std::to_string(il) + ": compress ratio " + std::to_string(l.ratio) +
2217                          " without a KV source of that ratio before it";
2218                    return false;
2219                }
2220                l.src = last_src;
2221                l.ik_src = last_src;
2222            }
2223            auto eg = std::find(g.eg_layers.begin(), g.eg_layers.end(), il);
2224            if (eg != g.eg_layers.end()) l.eg = (int) (eg - g.eg_layers.begin());
2225            if (!expert_layout(l, err)) return false;
2226        }
2227
2228        // the split: each layer's dense weights + its experts, the head on the last GPU
2229        for (Layer& l : L) {
2230            const std::string& P = l.name;
2231            size_t b = 0;
2232            if (l.mtp && l.il == g.nl) b += mat_bytes("mtp.0.main_proj");
2233            for (const char* m : {"attn.wq_a", "attn.wq_b", "attn.wkv", "attn.wo_b", "ffn.shared_experts.w1",
2234                                  "ffn.shared_experts.w2", "ffn.shared_experts.w3", "attn.compressor.wkv",
2235                                  "attn.compressor.wgate", "attn.indexer.wq_b", "attn.indexer.wk", "engram.wkv"})
2236                b += mat_bytes(P + m);
2237            for (int gi = 0; gi < g.o_groups; ++gi) b += mat_bytes(P + "attn.wo_a.slice." + std::to_string(gi));
2238            b += tensor_bytes(P + "hc_attn_fn") + tensor_bytes(P + "hc_ffn_fn") + tensor_bytes(P + "ffn.gate.weight");
2239            b += (size_t) g.win * win_rb() + (2u << 20);
2240            l.dense_bytes = b;
2241        }
2242        const size_t head_b = mat_bytes("head") + (size_t) g.vocab * 4 + (16u << 20);
2243        const size_t per_dev_fixed = (size_t) o.reserve_mib << 20;
2244        const size_t kv_per_src_dev = 0;   // counted after the split
2245        (void) kv_per_src_dev;
2246        std::vector<double> avail(groups.size(), 0.0);
2247        double avail_sum = 0;
2248        for (size_t gi = 0; gi < groups.size(); ++gi) {
2249            for (int m : groups[gi].mem)
2250                avail[gi] += std::max(0.0, (double) devs[(size_t) m].free0 - (double) per_dev_fixed - 400.0 * (1 << 20));
2251            avail_sum += avail[gi];
2252        }
2253        double need_sum = (double) head_b;
2254        for (const Layer& l : L) need_sum += (double) l.dense_bytes + (double) l.blob * l.n_exp;
2255        {
2256            // contiguous layer ranges, each group's share of the total by its free memory
2257            size_t d = 0;
2258            double cum = 0, target = avail[0] / avail_sum * need_sum;
2259            std::vector<Layer*> order;   // the drafter's blocks first (the first GPU), then the trunk's layers
2260            for (Layer& l : L)
2261                if (l.mtp) order.push_back(&l);
2262            for (Layer& l : L)
2263                if (!l.mtp) order.push_back(&l);
2264            for (Layer* lp : order) {
2265                Layer& l = *lp;
2266                const double lb = (double) l.dense_bytes + (double) l.blob * l.n_exp;
2267                if (cum + lb / 2 > target && d + 1 < groups.size()) {
2268                    ++d;
2269                    target += avail[d] / avail_sum * need_sum;
2270                }
2271                l.grp = (int) d;
2272                cum += lb;
2273            }
2274            // with the chunked prompt path: the contiguous split that streams the least into its busiest member (its
2275            // VRAM short of its layers' experts, per member) - a chunk's groups run as a pipeline, its slowest stage
2276            // sets the pace; a token's decode passes every layer either way, the experts in VRAM the same in all
2277            if (chunk > 0 && groups.size() > 1 && groups.size() <= 6 && std::getenv("DS4_SPLIT") == nullptr) {
2278                const int G = (int) groups.size(), NL = g.nl;
2279                std::vector<double> cap(groups.size());
2280                for (int gi = 0; gi < G; ++gi) {
2281                    const int nm = (int) groups[(size_t) gi].mem.size();
2282                    double mn = 1e300;
2283                    for (int m : groups[(size_t) gi].mem)
2284                        mn = std::min(mn, std::max(0.0, (double) devs[(size_t) m].free0 - (double) per_dev_fixed -
2285                                                            400.0 * (1 << 20) - 1.1 * (1 << 30)));   // (the chunk's buffers)
2286                    cap[(size_t) gi] = mn * nm;
2287                }
2288                for (const Layer& l : L)
2289                    if (l.mtp) cap[0] -= (double) l.dense_bytes + (double) l.blob * l.n_exp;
2290                cap[(size_t) G - 1] -= (double) head_b;
2291                std::vector<double> pe(NL + 1, 0.0), pd(NL + 1, 0.0);   // prefix sums: experts, dense
2292                for (int il = 0; il < NL; ++il) {
2293                    pe[(size_t) il + 1] = pe[(size_t) il] + (double) L[(size_t) il].blob * L[(size_t) il].n_exp;
2294                    pd[(size_t) il + 1] = pd[(size_t) il] + (double) L[(size_t) il].dense_bytes;
2295                }
2296                auto cost = [&](int gi, int a, int b) {   // per-member streaming of layers [a, b) on group gi
2297                    const int nm = (int) groups[(size_t) gi].mem.size();
2298                    const double dense = (pd[(size_t) b] - pd[(size_t) a]) * (nm > 1 ? 1.3 : 1.0);
2299                    return std::max(0.0, pe[(size_t) b] - pe[(size_t) a] - (cap[(size_t) gi] - dense)) / nm;
2300                };
2301                // best[gi][b]: the least max cost of layers [0, b) over groups 0..gi (each at least one layer)
2302                std::vector<std::vector<double>> best((size_t) G, std::vector<double>((size_t) NL + 1, 1e300));
2303                std::vector<std::vector<int>> cut((size_t) G, std::vector<int>((size_t) NL + 1, 0));
2304                for (int b = 1; b <= NL; ++b) best[0][(size_t) b] = cost(0, 0, b);
2305                for (int gi = 1; gi < G; ++gi)
2306                    for (int b = gi + 1; b <= NL; ++b)
2307                        for (int a = gi; a < b; ++a) {
2308                            const double v = std::max(best[(size_t) gi - 1][(size_t) a], cost(gi, a, b));
2309                            if (v < best[(size_t) gi][(size_t) b]) {
2310                                best[(size_t) gi][(size_t) b] = v;
2311                                cut[(size_t) gi][(size_t) b] = a;
2312                            }
2313                        }
2314                int b = NL;
2315                for (int gi = G - 1; gi >= 0; --gi) {
2316                    const int a = gi > 0 ? cut[(size_t) gi][(size_t) b] : 0;
2317                    for (int il = a; il < b; ++il) L[(size_t) il].grp = gi;
2318                    b = a;
2319                }
2320            }
2321            // DS4_SPLIT=a,b,..: the trunk layers each group takes (the drafter stays with the first)
2322            if (const char* sp = std::getenv("DS4_SPLIT")) {
2323                std::vector<int> n;
2324                for (const char* q = sp; *q;) {
2325                    n.push_back(std::atoi(q));
2326                    while (*q && *q != ',') ++q;
2327                    if (*q == ',') ++q;
2328                }
2329                int il = 0;
2330                for (size_t gi = 0; gi < n.size() && gi < groups.size(); ++gi)
2331                    for (int j = 0; j < n[gi] && il < g.nl; ++j) L[(size_t) il++].grp = (int) gi;
2332                for (; il < g.nl; ++il) L[(size_t) il].grp = (int) groups.size() - 1;
2333            }
2334            for (Layer& l : L) {
2335                l.dev = groups[(size_t) l.grp].mem[0];
2336                l.nm = l.mtp ? 1 : (int) groups[(size_t) l.grp].mem.size();   // (the drafter's blocks: on the lead alone)
2337            }
2338            head_dev = L[(size_t) g.nl - 1].dev;
2339            d_dev = g.n_mtp > 0 ? L[(size_t) g.nl].dev : 0;
2340        }
2341        // the groups' members: copies of each layer's device state, a member's part of an expert
2342        for (Layer& l : L) {
2343            l.ff0 = 0;
2344            l.ffn = g.ff;
2345            l.ah0 = l.og0 = 0;
2346            l.ahn = g.heads;
2347            l.ogn = g.o_groups;
2348            if (l.nm == 1) continue;
2349            const int na = head_members(l.nm);
2350            if (g.heads % na != 0 || g.o_groups % na != 0 || g.ff % 128 != 0 || g.ff / 128 < l.nm) {
2351                err = "tensor parallel " + std::to_string(l.nm) + ": the heads, output groups or FFN do not split";
2352                return false;
2353            }
2354            for (int m = 1; m < l.nm; ++m) {
2355                Layer c = l;
2356                c.mates.clear();
2357                c.mi = m;
2358                c.dev = groups[(size_t) l.grp].mem[(size_t) m];
2359                l.mates.push_back(std::move(c));
2360            }
2361            // each member's FFN columns and its part of an expert's layout: an EXL3 expert's in whole 128-blocks, as even
2362            // as they go (split128, the odd blocks going round the members layer by layer); a GGUF's in even shares (its
2363            // groups are only as wide as its experts' blocks split evenly: mx_blob_to_half's n_ff / nm)
2364            const bool gguf_x = l.lay.fmt == gg::kFmtMXFP4;
2365            for (int m = 0; m < l.nm; ++m) {
2366                Layer& x = member(l, m);
2367                const int ha = m - (l.nm - na);   // (its place among the members with heads)
2368                x.ahn = ha < 0 ? 0 : g.heads / na;
2369                x.ah0 = ha < 0 ? 0 : ha * x.ahn;
2370                x.ogn = ha < 0 ? 0 : g.o_groups / na;
2371                x.og0 = ha < 0 ? 0 : ha * x.ogn;
2372                if (gguf_x) {
2373                    x.ffn = g.ff / l.nm;
2374                    x.ff0 = m * x.ffn;
2375                } else
2376                    split128(g.ff, l.nm, m, x.ff0, x.ffn, l.il % l.nm);   // (rot: the odd blocks go round the members)
2377                size_t off = 0;
2378                for (int r = 0; r < 3; ++r) {
2379                    const int k = r < 2 ? g.dim : x.ffn, n = r < 2 ? x.ffn : g.dim;
2380                    x.hlay.K[r] = l.lay.K[r];
2381                    x.hlay.trellis[r] = off;
2382                    if (gguf_x) {   // gate / up rows, down inputs: [n][k / block] blocks
2383                        const int ty = gg::expert_type(l.lay, r);
2384                        if (k % gg::type_block(ty) != 0) {
2385                            err = "tensor parallel " + std::to_string(l.nm) + ": the experts' " + gg::type_name(ty) +
2386                                  " blocks do not split";
2387                            return false;
2388                        }
2389                        x.hlay.suh[r] = x.hlay.svh[r] = off;
2390                        off += align256((size_t) n * gg::type_row_bytes(ty, k));
2391                        continue;
2392                    }
2393                    off += align256(x3::trellis_bytes(k, n, l.lay.K[r]));
2394                    x.hlay.suh[r] = off;
2395                    off += align256((size_t) k * 2);
2396                    x.hlay.svh[r] = off;
2397                    off += align256((size_t) n * 2);
2398                }
2399                x.hlay.cb = l.lay.cb;
2400                x.hlay.fmt = l.lay.fmt;
2401                x.hblob = off;
2402            }
2403        }
2404        // which devices hold each source's compressed KV / index keys
2405        for (Src& s : srcs) {
2406            s.ckv.assign(devs.size(), nullptr);
2407            s.ik.assign(devs.size(), nullptr);
2408            if (scr_master) {
2409                s.master.assign(devs.size(), nullptr);
2410                s.master_ik.assign(devs.size(), nullptr);
2411                s.master_valid.assign(devs.size(), nullptr);
2412                s.master_ik_valid.assign(devs.size(), nullptr);
2413            }
2414        }
2415        for (const Layer& l0 : L)
2416            for (int m = 0; m < l0.nm; ++m) {
2417                const Layer& l = member(l0, m);
2418                if (l.src >= 0) {
2419                    srcs[(size_t) l.src].ckv[(size_t) l.dev] = (uint8_t*) 1;
2420                    if (l0.grp != L[(size_t) srcs[(size_t) l.src].layer].grp) srcs[(size_t) l.src].remote = true;
2421                }
2422                if (l.ix_src && l.ik_src >= 0) {
2423                    srcs[(size_t) l.ik_src].ik[(size_t) l.dev] = (uint8_t*) 1;
2424                    if (l0.grp != L[(size_t) srcs[(size_t) l.ik_src].layer].grp) srcs[(size_t) l.ik_src].remote = true;
2425                }
2426            }
2427
2428        // per device: the scratch, the caches, the dense weights
2429        for (size_t di = 0; di < devs.size(); ++di) {
2430            Dev& d = devs[di];
2431            const int D = g.dim, H = g.hc;
2432            const size_t W = kWin, P = (size_t) kWin * kPicks, cap = (size_t) o.max_context + 64;
2433            bool ok = dalloc(d, d.h, W * H * D, err) && dalloc(d, d.h2, W * H * D, err) && dalloc(d, d.x, W * D, err) &&
2434                      dalloc(d, d.qr, W * g.q_lora, err) && dalloc(d, d.q, W * g.heads * g.hd, err) &&
2435                      dalloc(d, d.kvr, W * g.hd, err) && dalloc(d, d.ckr, W * g.hd, err) &&
2436                      dalloc(d, d.cgr, W * g.hd, err) && dalloc(d, d.latent, W * g.hd, err) &&
2437                      dalloc(d, d.ikr, W * g.ix_hd, err) && dalloc(d, d.iq, W * g.ix_heads * g.ix_hd, err) &&
2438                      dalloc(d, d.iw, W * 64, err) && dalloc(d, d.scores, W * cap, err) &&
2439                      dalloc(d, d.bm, W * bm_stride(), err) && dalloc(d, d.o, W * g.heads * g.hd, err) &&
2440                      dalloc(d, d.oa, W * g.o_groups * g.o_lora, err) && dalloc(d, d.ao, W * D, err) &&
2441                      dalloc(d, d.mix, W * 32, err) && dalloc(d, d.a_pre, W * 8, err) && dalloc(d, d.a_post, W * 8, err) &&
2442                      dalloc(d, d.a_comb, W * 64, err) && dalloc(d, d.f_pre, W * 8, err) &&
2443                      dalloc(d, d.f_post, W * 8, err) && dalloc(d, d.f_comb, W * 64, err) && dalloc(d, d.pre, W * 8, err) &&
2444                      dalloc(d, d.glog, W * 1024, err) && dalloc(d, d.glog_a, 2 * W * 1024, err) &&
2445                      dalloc(d, d.rw, W * kPicks, err) &&
2446                      dalloc(d, d.ridx, W * kPicks, err) && dalloc(d, d.moe_out, W * D, err) &&
2447                      dalloc(d, d.sg, W * g.ff, err) && dalloc(d, d.su, W * g.ff, err) && dalloc(d, d.sh, W * g.ff, err) &&
2448                      dalloc(d, d.sh_out, W * D, err) && dalloc(d, d.cpu_part, W * D, err) &&
2449                      dalloc(d, d.freqs_win, 64, err) && dalloc(d, d.freqs_comp, 64, err) &&
2450                      dalloc(d, d.topk, W * topk_stride(), err) && dalloc(d, d.cand, W * cand_stride(), err) &&
2451                      dalloc(d, d.tok, 16, err) && dalloc(d, d.emb_rows, W * D, err) &&
2452                      dalloc(d, d.ext, ((size_t) g.win + W) * g.hd, err) && dalloc(d, d.xe, P * D, err) &&
2453                      dalloc(d, d.xg, P * g.ff, err) && dalloc(d, d.xu, P * g.ff, err) && dalloc(d, d.xhh, P * g.ff, err) &&
2454                      dalloc(d, d.ed, P * D, err) && dalloc(d, d.plan_ptr, P, err);
2455            if (!ok) return false;
2456            d.attn_scr.max_t = kAttnScratchT;
2457            d.attn_scr.cap = (int) topk_stride();
2458            if (!dalloc(d, d.attn_scr.rows, (size_t) kAttnScratchT * topk_stride() * g.hd, err)) return false;
2459            if (!g.eg_layers.empty()) {
2460                const int cols = (pk.eg_ngram - 1) * pk.eg_heads;
2461                ok = dalloc(d, d.eg_rows, W * cols * (pk.eg_hd + pk.eg_hd / 32), err) &&
2462                     dalloc(d, d.eg_x, W * cols * pk.eg_hd, err) && dalloc(d, d.eg_kv, W * (g.hc + 1) * D, err);
2463                if (!ok) return false;
2464            }
2465            if ((int) di == head_dev && !dalloc(d, d.logits, (size_t) kWin * g.vocab, err)) return false;
2466            if (!halloc(d.bounce, bounce_bytes(), err)) return false;
2467            if (!dalloc(d, d.xcnt, 4, err) || !dalloc(d, d.hccnt, kWin, err) || !hmap(d.hand, bounce_bytes(), err) || !hmap(d.hand_flag, 32, err) ||
2468                !dalloc(d, d.grp_ptr, P, err) || !dalloc(d, d.grp_start, P + 1, err) || !dalloc(d, d.grp_ent, P, err) ||
2469                !dalloc(d, d.n_groups, 4, err))
2470                return false;
2471            if (g.n_mtp > 0 && !dalloc(d, d.tap, (size_t) tap_cap * D, err)) return false;
2472            if ((g.n_mtp > 0 || o.spec_buffers) && (int) di == head_dev &&
2473                (!dalloc(d, d_confv, kWin, err) || !dalloc(d, d_ints, 64, err) || !dalloc(d, d_specq, kWin, err)))
2474                return false;
2475            CK(cudaEventCreateWithFlags(&d.ev_out, cudaEventDisableTiming));
2476            cudaSetDevice(d.id);
2477            CK(cudaMemcpy(d.freqs_win, freqs_win.data(), freqs_win.size() * 4, cudaMemcpyHostToDevice));
2478            CK(cudaMemcpy(d.freqs_comp, freqs_comp.data(), freqs_comp.size() * 4, cudaMemcpyHostToDevice));
2479            for (Src& s : srcs) {
2480                if (s.h_ckv == nullptr) {   // (its events belong to the source layer's device: it records them)
2481                    if (!halloc(s.h_ckv, (size_t) kWin * ckv_rb(), err) || !halloc(s.h_ik, (size_t) kWin * ik_rb(), err))
2482                        return false;
2483                    CK(cudaSetDevice(devs[(size_t) L[(size_t) s.layer].dev].id));
2484                    CK(cudaEventCreateWithFlags(&s.ev_ckv, cudaEventDisableTiming));
2485                    CK(cudaEventCreateWithFlags(&s.ev_ik, cudaEventDisableTiming));
2486                    CK(cudaSetDevice(d.id));
2487                }
2488                if (s.ckv[di] != nullptr && !dalloc(d, s.ckv[di], (size_t) s.cap * ckv_rb(), err, &d.caches))
2489                    return false;
2490                if (s.ik[di] != nullptr && !dalloc(d, s.ik[di], (size_t) s.cap * ik_rb(), err, &d.caches))
2491                    return false;
2492                // (SCR's masters in host-mapped memory, not VRAM: the device's expert slots, so its answers, stay
2493                //  what they are without SCR; a row's master is 256 bytes over PCIe as the row is written)
2494                auto mapped = [&](auto*& p, size_t bytes) {
2495                    void* h = nullptr;
2496                    if (cudaHostAlloc(&h, bytes, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) {
2497                        (void) cudaGetLastError();
2498                        err = "SCR: host memory for the masters";
2499                        return false;
2500                    }
2501                    std::memset(h, 0, bytes);
2502                    host_allocs.push_back(h);
2503                    void* dp = nullptr;
2504                    if (cudaHostGetDevicePointer(&dp, h, 0) != cudaSuccess || dp != h) {   // (a slot copies them as host memory)
2505                        (void) cudaGetLastError();
2506                        err = "SCR: the masters' memory is not one address for host and device";
2507                        return false;
2508                    }
2509                    p = (std::remove_reference_t<decltype(p)>) dp;
2510                    return true;
2511                };
2512                if (scr_master && s.ckv[di] != nullptr &&
2513                    (!mapped(s.master[di], (size_t) s.cap * (size_t) g.rd * sizeof(float)) ||
2514                     !mapped(s.master_valid[di], (size_t) s.cap)))
2515                    return false;
2516                if (scr_master && s.ik[di] != nullptr &&
2517                    (!mapped(s.master_ik[di], (size_t) s.cap * (size_t) g.rd * sizeof(float)) ||
2518                     !mapped(s.master_ik_valid[di], (size_t) s.cap)))
2519                    return false;
2520            }
2521        }
2522        for (Src& sr : srcs) {
2523            if (sr.remote && (!hmap(sr.x_stage, x_cap() * (ckv_rb() + ik_rb()), err) || !hmap(sr.x_flag, 32, err)))
2524                return false;
2525            if (sr.remote && chunk > 0 &&
2526                (!hmap(sr.x_stage1, x_cap() * (ckv_rb() + ik_rb()), err) || !hmap(sr.x_flag1, 32, err) ||
2527                 !hmap(sr.x_ack, (size_t) 2 * devs.size() * 32, err)))
2528                return false;
2529            const int sg = L[(size_t) sr.layer].grp;
2530            for (size_t di = 0; di < devs.size(); ++di)
2531                if ((sr.ckv[di] != nullptr || sr.ik[di] != nullptr) && devs[di].grp != sg) sr.readers.push_back((int) di);
2532        }
2533        for (Group& G : groups) {
2534            G.ar.nm = (int) G.mem.size();
2535            G.ar.slots = 4;
2536            G.ar.stride = (size_t) kWin * g.dim;
2537            if (G.ar.nm > 1 && (!hmap(G.ar.data, (size_t) G.ar.nm * G.ar.slots * G.ar.stride, err) ||
2538                                !hmap(G.ar.flags, (size_t) G.ar.nm * G.ar.slots * 32, err)))
2539                return false;
2540            // three members or more: the reduce-scatter's sums and its per-block flags (allreduce)
2541            if (G.ar.nm > 2 && (!hmap(G.ar.sums, (size_t) G.ar.slots * G.ar.stride, err) ||
2542                                !hmap(G.ar.bflags, (size_t) 2 * G.ar.nm * G.ar.slots * kArBlocks * 8, err)))
2543                return false;
2544            if (G.ar.nm > 1 && &G == &groups[(size_t) devs[(size_t) head_dev].grp] &&
2545                (!hmap(G.lg_stage, (size_t) 2 * (G.ar.nm - 1) * kWin * ((g.vocab / 128 + G.ar.nm - 1) / G.ar.nm * 128), err) ||
2546                 !hmap(G.lg_flag, (size_t) 2 * (G.ar.nm - 1) * 32, err) || !hmap(G.lg_ack, (size_t) 2 * 32, err)))
2547                return false;
2548            G.arb = G.ar;   // (a chunk's: two slots of chunk rows)
2549            G.arb.slots = 2;
2550            G.arb.stride = (size_t) chunk * g.dim;
2551            if (chunk > 0 && G.arb.nm > 1 && (!hmap(G.arb.data, (size_t) G.arb.nm * G.arb.slots * G.arb.stride, err) ||
2552                                              !hmap(G.arb.flags, (size_t) G.arb.nm * G.arb.slots * 32, err)))
2553                return false;
2554            if (chunk > 0 && G.arb.nm > 2 &&
2555                (!hmap(G.arb.sums, (size_t) G.arb.slots * G.arb.stride, err) ||
2556                 !hmap(G.arb.bflags, (size_t) 2 * G.arb.nm * G.arb.slots * kArBlocks * 8, err)))
2557                return false;
2558        }
2559        if (g.n_mtp > 0) {
2560            if (!halloc(h_taps, (size_t) tap_cap * g.d_targets.size() * g.dim, err)) return false;
2561            CK(cudaSetDevice(devs[(size_t) d_dev].id));
2562            CK(cudaEventCreateWithFlags(&ev_seed, cudaEventDisableTiming));
2563            CK(cudaEventRecord(ev_seed, devs[(size_t) d_dev].st));
2564        }
2565        // the dense weights, each device's layers by a thread of its own
2566        {
2567            std::vector<std::string> errs(devs.size());
2568            std::vector<std::thread> th;
2569            for (size_t di = 0; di < devs.size(); ++di)
2570                th.emplace_back([this, di, &errs] {
2571                    std::string e;
2572                    if (!load_dense((int) di, e)) errs[di] = e;
2573                });
2574            for (auto& t : th) t.join();
2575            for (auto& e : errs)
2576                if (!e.empty()) {
2577                    err = e;
2578                    return false;
2579                }
2580        }
2581        if (o.verbose)
2582            std::fprintf(stderr, "ds4: dense weights loaded in %.1f s\n", (now_ms() - t0) / 1000.0);
2583        // the markov steps over a head group of two or more (DS4_MK_SPLIT=0: the lead's whole rows, as before): E
2584        // host-mapped, the steps' slots
2585        // (only where every member holds its rows of the markov head: a type load_dense does not take keeps the lead's)
2586        bool mk_rows = g.n_mtp > 0 && head_nm() > 1;
2587        for (int m : groups[(size_t) devs[(size_t) head_dev].grp].mem) mk_rows = mk_rows && devs[(size_t) m].mk_share != nullptr;
2588        if (mk_rows && !(std::getenv("DS4_MK_SPLIT") != nullptr && std::atoi(std::getenv("DS4_MK_SPLIT")) == 0)) {
2589            const Tensor* te = pk.get("mtp." + std::to_string(g.n_mtp - 1) + ".markov_head.embed.weight");
2590            if (te == nullptr || te->dtype != "BF16" || te->bytes != (uint64_t) g.vocab * g.d_rank * 2) {
2591                err = "the markov embed: not a BF16 [vocab][rank] table";
2592                return false;
2593            }
2594            if (!hmap(h_mk_embed, (size_t) g.vocab * g.d_rank, err) || !pk.read(*te, h_mk_embed) ||
2595                !hmap(mk_slots, (size_t) kWin * head_nm() * 4, err)) {
2596                if (err.empty()) err = "the markov embed: read failed";
2597                return false;
2598            }
2599            devs[(size_t) head_dev].mk_ints = d_ints;   // (the lead's drafted tokens: where the confidence head reads them)
2600            mk_split = true;
2601        }
2602
2603        // the embedding table, pinned on the host
2604        {
2605            const Tensor* t = pk.get("embed.weight");
2606            const size_t nv = (size_t) g.vocab * g.dim;
2607            const bool q8 = t != nullptr && t->dtype == "Q8_0" && t->bytes == nv / 32 * gg::kQ8Bytes;
2608            // other block types (a GGUF whose dense tensors are Q4_K / Q5_K / Q6_K: the IST-DAS sets' Q5_K embed.weight):
2609            // each row through ggml's to_float, to the same BF16 the host table holds
2610            const int ety = t != nullptr ? gg_type_of(t->dtype) : -1;
2611            const size_t erb = ety > 0 ? gg::type_row_bytes(ety, g.dim) : 0;
2612            const bool qrow = t != nullptr && !(t->dtype == "BF16") && erb > 0 && t->bytes == (size_t) g.vocab * erb;
2613            if (t == nullptr || (!q8 && !qrow && (t->dtype != "BF16" || t->bytes != nv * 2))) {
2614                err = "embed.weight: not a BF16 (or Q8_0 / a ggml block type) [vocab][dim] table";
2615                return false;
2616            }
2617            if (!halloc(embed_pinned, nv, err)) return false;
2618            if (qrow) {   // (ggml's decode of each row, rounded to BF16 as the Q8_0 path rounds)
2619                std::vector<uint8_t> row(erb);
2620                for (size_t r = 0; r < (size_t) g.vocab; ++r) {
2621                    if (!pk.read_at(t->file, t->off + r * erb, erb, row.data())) {
2622                        err = "embed.weight: read failed";
2623                        return false;
2624                    }
2625                    if (!gg::gg_row_to_bf16(ety, row.data(), g.dim, embed_pinned + r * g.dim)) {
2626                        err = "embed.weight: ggml has no decode for " + t->dtype;
2627                        return false;
2628                    }
2629                }
2630            } else if (q8) {   // (a GGUF's: each value rounded to BF16, a row at a time)
2631                std::vector<uint8_t> row((size_t) g.dim / 32 * gg::kQ8Bytes);
2632                for (size_t r = 0; r < (size_t) g.vocab; ++r) {
2633                    if (!pk.read_at(t->file, t->off + r * row.size(), row.size(), row.data())) {
2634                        err = "embed.weight: read failed";
2635                        return false;
2636                    }
2637                    const std::vector<float> v = q8_values(row.data(), (size_t) g.dim);
2638                    for (size_t c = 0; c < (size_t) g.dim; ++c) {
2639                        uint32_t u;
2640                        std::memcpy(&u, &v[c], 4);
2641                        u += 0x7fffu + ((u >> 16) & 1u);   // round to nearest even
2642                        embed_pinned[r * g.dim + c] = (uint16_t) (u >> 16);
2643                    }
2644                }
2645            } else if (!pk.read(*t, embed_pinned)) {
2646                err = "embed.weight: read failed";
2647                return false;
2648            }
2649        }
2650        // the host side of the CPU lane and the Engram rows
2651        const int cols = (pk.eg_ngram - 1) * pk.eg_heads;
2652        if (!halloc(h_x, (size_t) kWin * g.dim, err) || !halloc(h_w, (size_t) kWin * kPicks, err) ||
2653            !halloc(h_part, (size_t) kWin * g.dim, err) || !halloc(h_idx, (size_t) kWin * kPicks, err) ||
2654            !halloc(h_emb, (size_t) std::max(kWin, chunk) * g.dim, err) ||
2655            !halloc(h_eg, (size_t) std::max(1, pk.eg_layers) * eg_cap * cols * (pk.eg_hd + pk.eg_hd / 32) + 64, err))
2656            return false;
2657        if (pk.eg_layers > 0) {
2658            // the Engram rows' reader: threads enough to keep an SSD's queue busy (reads from the page cache need few);
2659            // the row cache a small share of the RAM free (DS4_ENGRAM_CACHE_MB: its size, 0 off; DS4_ENGRAM_THREADS)
2660            const size_t row = (size_t) pk.eg_hd + pk.eg_hd / 32;
2661#if defined(_WIN32)
2662            // (Windows: each thread's ReadFile is synchronous, so the threads are the queue depth - Project Maya: a 28K-token
2663            //  prompt in one chunk, 10 threads 17.1 s, 64 13.4 s on a 20-core PC.  Here (6 cores, shipped profile) 64 readers
2664            //  gave +4.5% on a 4K prompt but no decode gain in every pair: DS4_ENGRAM_THREADS=64 turns them on)
2665#endif
2666            const unsigned hw = std::max(1u, std::thread::hardware_concurrency());
2667            int nth = (int) std::min(16u, std::max(4u, hw / 2));
2668            if (const char* e = std::getenv("DS4_ENGRAM_THREADS")) nth = std::max(1, std::atoi(e));
2669            const uint64_t avail = ram_avail();
2670            uint64_t mb = avail == ~uint64_t{0} ? 64 : std::min<uint64_t>(256, std::max<uint64_t>(16, (avail >> 20) / 64));
2671            if (const char* e = std::getenv("DS4_ENGRAM_CACHE_MB")) mb = std::strtoull(e, nullptr, 10);
2672            eg_cache.init((size_t) ((mb << 20) / row), row);
2673            std::vector<std::string> paths;
2674            for (const std::string& fn : pk.files) paths.push_back(pk.model_dir + "/" + fn);
2675            // Windows: the Engram tables' files that hold nothing else are unmapped and read unbuffered - an SSD's
2676            // queue kept by the reader threads instead of the page cache's (whose reads of one file from many threads
2677            // went ~255K rows a second here); unbuffered reads of a mapped file take a slow path, so only unmapped
2678            // ones (off by default: -8% on a 4K prompt here; DS4_EG_DIRECT=1 turns it on)
2679            std::vector<char> eg_direct(pk.files.size(), 0);
2680#if defined(_WIN32)
2681            if (pk.gguf && std::getenv("DS4_EG_DIRECT") != nullptr && std::atoi(std::getenv("DS4_EG_DIRECT")) != 0) {
2682                std::vector<char> eg_file(pk.files.size(), 0), other(pk.files.size(), 0);
2683                for (const auto& kt : pk.t)
2684                    if (kt.second.file >= 0 && (size_t) kt.second.file < pk.files.size())
2685                        (kt.first.find(".engram.embed.") != std::string::npos ? eg_file : other)[(size_t) kt.second.file] = 1;
2686                for (size_t i = 0; i < pk.files.size(); ++i)
2687                    if (eg_file[i] && !other[i]) {
2688                        if (i < pk.maps.size() && pk.maps[i].first != nullptr) {
2689                            os::unmap(pk.maps[i].first, pk.maps[i].second);
2690                            pk.maps[i] = {nullptr, 0};
2691                        }
2692                        eg_direct[i] = 1;
2693                        if (o.verbose) std::fprintf(stderr, "ds4: %s unmapped, its Engram rows read unbuffered\n",
2694                                                    pk.files[i].c_str());
2695                    }
2696            }
2697#endif
2698            eg_io.start(paths, nth, eg_direct);
2699            for (int li = 0; li < pk.eg_layers; ++li) {
2700                eg_win.emplace_back(new EgBatch());
2701                const std::string id = std::to_string(g.eg_layers[(size_t) li]);
2702                const Tensor* tw = pk.get("layers." + id + ".engram.embed.weight");
2703                // The row layout the reader and the dequant take.  A type not here (or no tensor at all) would be read
2704                // as some other format's bytes - the old code then read the scale tensor of a pack that has none and
2705                // crashed in eg_issue - so refuse the pack once, with the type's name, before any token is read.
2706                int fmt;
2707                if (tw == nullptr) {
2708                    std::fprintf(stderr, "ds4: Engram layer %s: engram.embed.weight is missing from the pack\n", id.c_str());
2709                    std::exit(2);
2710                } else if (tw->dtype == "MXFP8") {
2711                    fmt = 0;
2712                } else if (tw->dtype == "Q6_K") {
2713                    fmt = 1;
2714                } else if (tw->dtype == "IQ4_NL") {
2715                    fmt = 2;
2716                } else if (pk.get("layers." + id + ".engram.embed.scale") != nullptr) {
2717                    fmt = 3;   // (an old pack: FP8 codes in one tensor, their E8M0 scales in another)
2718                } else {
2719                    std::fprintf(stderr,
2720                                 "ds4: Engram layer %s: engram.embed.weight type %s is not one the Engram reader handles "
2721                                 "(MXFP8, Q6_K, IQ4_NL)\n",
2722                                 id.c_str(), tw->dtype.c_str());
2723                    std::exit(2);
2724                }
2725                if (fmt == 1 && pk.eg_hd % 256 != 0) {
2726                    err = "Engram layer " + id + ": Q6_K rows of " + std::to_string(pk.eg_hd) +
2727                          " values (not whole superblocks of 256)";
2728                    return false;
2729                }
2730                if (fmt == 2 && pk.eg_hd % 32 != 0) {
2731                    err = "Engram layer " + id + ": IQ4_NL rows of " + std::to_string(pk.eg_hd) +
2732                          " values (not whole blocks of 32)";
2733                    return false;
2734                }
2735                eg_fmt.push_back((uint8_t) fmt);
2736            }
2737            if (o.verbose)
2738                std::fprintf(stderr, "ds4: Engram rows read on %d threads, issued with the tokens, collected before "
2739                                     "their layer; row cache %llu MB (%zu rows)\n",
2740                             nth, (unsigned long long) mb, eg_cache.capacity());
2741        }
2742        prof.assign((size_t) (g.nl + g.n_mtp) * g.n_exp, 0u);
2743        if (!o.profile.empty()) {
2744            std::FILE* f = std::fopen(o.profile.c_str(), "rb");
2745            if (f != nullptr) {
2746                std::vector<uint32_t> p(prof.size());
2747                const size_t n = std::fread(p.data(), 4, p.size(), f);
2748                if (n == p.size() || n == (size_t) g.nl * g.n_exp) std::copy(p.begin(), p.begin() + (long) n, prof.begin());
2749                std::fclose(f);
2750            }
2751        }
2752
2753        // the chunked prompt path's buffers (before the experts: they take what is left)
2754        if (chunk > 0) {
2755            // recommend, never force: a chunk the cards cannot hold in buffers is halved (down to 256 rows) and then the
2756            // prompt runs in windows of 16, said in one line - the load only fails for a reason that is not this
2757            std::vector<size_t> na0, sc0;
2758            for (Dev& d : devs) {
2759                na0.push_back(d.allocs.size());
2760                sc0.push_back(d.scratch);
2761            }
2762            const size_t nh = host_allocs.size();
2763            std::string aerr;
2764            while (chunk > 0 && !alloc_chunks(aerr)) {
2765                for (size_t di = 0; di < devs.size(); ++di) {
2766                    Dev& d = devs[di];
2767                    cudaSetDevice(d.id);
2768                    cudaDeviceSynchronize();
2769                    if (di < chunks.size() && chunks[di]) {
2770                        if (chunks[di]->blas) cublasDestroy(chunks[di]->blas);
2771                        if (chunks[di]->cs) cudaStreamDestroy(chunks[di]->cs);
2772                    }
2773                    while (d.allocs.size() > na0[di]) {
2774                        cudaFree(d.allocs.back());
2775                        d.allocs.pop_back();
2776                    }
2777                    d.scratch = sc0[di];
2778                }
2779                while (host_allocs.size() > nh) {
2780                    cudaFreeHost(host_allocs.back());
2781                    host_allocs.pop_back();
2782                }
2783                chunks.clear();
2784                const int was = chunk;
2785                chunk = chunk > 512 ? chunk / 2 / 16 * 16 : 0;
2786                if (chunk > 0) {
2787                    eg_cap = (size_t) chunk;
2788                    std::fprintf(stderr, "ds4: the prompt path's buffers for chunks of %d rows did not fit (%s): trying %d\n",
2789                                 was, aerr.c_str(), chunk);
2790                } else {
2791                    prompt_par = false;
2792                    eg_cap = (size_t) kWin;
2793                    tap_cap = kWin;
2794                    std::fprintf(stderr, "ds4: the prompt path's buffers did not fit (%s): prompts run in windows of %d "
2795                                         "tokens (slower on long prompts; more free GPU memory or a lower --reserve-mib "
2796                                         "brings the chunks back)\n", aerr.c_str(), kWin);
2797                }
2798                aerr.clear();
2799            }
2800            if (chunk > 0 && aerr.empty()) err.clear();
2801        }
2802        // the CPU lane's experts read in place (decided above): how much of them the load reads ahead, from what VRAM
2803        // now leaves over
2804        if (file_experts) {
2805            double room = 0, all = 0;   // the VRAM place_experts will find for experts; every expert's bytes
2806            for (Dev& d : devs) {
2807                cudaSetDevice(d.id);
2808                size_t fr = 0, tot = 0;
2809                CK(cudaMemGetInfo(&fr, &tot));
2810                room += std::max(0.0, (double) fr - (double) ((size_t) o.reserve_mib << 20)) * o.vram_experts;
2811            }
2812            for (const Layer& l : L) all += (double) l.blob * l.n_exp;
2813            const double need = std::max(0.0, all - room);
2814            const uint64_t avail = ram_avail();
2815            warm_bytes = avail > kRamMargin ? std::min<uint64_t>(avail - kRamMargin, (uint64_t) need) : 0;
2816            if (avail == ~uint64_t{0}) warm_bytes = (uint64_t) need;
2817            if (store_gb() > 0) warm_bytes = 0;   // (the store is the RAM tier: nothing to warm in the OS cache)
2818            std::fprintf(stderr,
2819                         "ds4: the experts VRAM leaves over (~%.1f GB) are read in place from the model's files%s "
2820                         "(%.1f GB of RAM free to keep them: the most-routed %.1f GB read ahead; prompts in chunks of %d)\n",
2821                         need / 1e9, o.mmap_experts > 0 ? " (--mmap-experts on)"
2822                                     : pk.gguf ? " (--mmap-experts off copies them into RAM)" : ", not copied into RAM",
2823                         avail == ~uint64_t{0} ? 0.0 : avail / 1e9, warm_bytes / 1e9, chunk);
2824        }
2825        // the CPU lane: one pool of workers per NUMA node, each expert split in NH column parts (part X on node X); in
2826        // place, one part (the files' layout) and one pool over every node's cores (the pages lie where the cache put them)
2827        cores = node_cores();
2828        NH = file_experts ? 1 : (int) std::min<size_t>(2, cores.size());
2829        if (NH > 1 && ((g.ff / NH) % 128 != 0 || (g.dim / NH) % 128 != 0)) NH = 1;
2830        if (!pk.gguf) make_pools();   // (a GGUF's after its experts: copy_experts decides NH)
2831        {
2832            const size_t E = (size_t) g.dim, FF = (size_t) g.ff, GQ = E / 256, DQ = FF / 128, S = kSlots;
2833            c_xh.resize((size_t) NH * S * 2 * E);
2834            c_xsb.resize((size_t) NH * S * 2 * (E / 128));
2835            c_acc.resize((size_t) NH * S * 2 * GQ * (FF / NH));
2836            c_xhd.resize(S * FF);
2837            c_xsd.resize(S * (FF / 128));
2838            c_accd.resize((size_t) NH * S * DQ * (E / NH));
2839            c_yd.resize(S * E);
2840        }
2841        // the experts: VRAM slots in what each device has left, the rest on the host
2842        if (!place_experts(err)) return false;
2843        if (!load_experts(err)) return false;
2844        if (pk.gguf) make_pools();
2845        if (!aux_init(err)) return false;
2846        if (chunk > 0) {
2847            // the CPU lane's parts pinned (the chunks stream them to the GPUs by DMA), each layer's virtual slots
2848            const double tr = now_ms();
2849            for (auto& m : host_maps)
2850                if (cudaHostRegister(m.first, m.second, cudaHostRegisterPortable) != cudaSuccess) {
2851                    err = "pinning the CPU lane's experts (" + std::to_string(m.second >> 20) + " MiB) failed";
2852                    return false;
2853                }
2854            if (o.verbose) std::fprintf(stderr, "ds4: CPU lane's experts pinned in %.1f s\n", (now_ms() - tr) / 1000.0);
2855            if (file_experts) {   // in place: each device's staging for its ring, and its readers (DS4_READERS, 8)
2856                size_t mr = 0;
2857                for (const Layer& l : L)
2858                    if (!l.mtp) {
2859                        for (uint64_t r : l.region_bytes) mr = std::max<size_t>(mr, r);
2860                        if (l.lay.fmt == gg::kFmtMXFP4) {   // (a GGUF's: read as its blob)
2861                            mr = std::max(mr, l.blob);
2862                            for (int r = 0; r < 3; ++r) flow_part[r] = std::max(flow_part[r], mx_part_bytes(l, r));
2863                        }
2864                    }
2865                const char* nr = std::getenv("DS4_READERS");
2866                const int n_readers = std::max(1, nr != nullptr ? std::atoi(nr) : 8);
2867                const bool flow_on = std::getenv("DS4_FLOW") == nullptr || std::atoi(std::getenv("DS4_FLOW")) != 0;
2868                // (a tensor-parallel group's members on the flow only with DS4_FLOW_TP=1 for now: each reads the
2869                // whole down of every expert it streams, 25 MB an expert for a pair, 18.8 alone - 3x V100, the
2870                // 17-token prompt from the page cache: 2.5-2.7 s on the flow, 1.3-1.6 s in the group's windows)
2871                const bool flow_tp = std::getenv("DS4_FLOW_TP") != nullptr && std::atoi(std::getenv("DS4_FLOW_TP")) != 0;
2872                for (size_t di = 0; di < chunks.size(); ++di) {
2873                    auto& cp = chunks[di];
2874                    if (cp == nullptr || cp->ring == nullptr) continue;
2875                    cp->stage_stride = (mr + 4095) & ~(size_t) 4095;
2876                    // the flow: every trunk layer of the device a GGUF's (alone or a tensor-parallel group's member)
2877                    bool fl = flow_on;
2878                    int n_exp_max = 0;
2879                    for (const Layer& l : L)
2880                        if (!l.mtp)
2881                            for (int m = 0; m < l.nm; ++m)
2882                                if (member(l, m).dev == (int) di) {
2883                                    // (a group's members: each its share of the down's blocks in every row)
2884                                    fl = fl && l.lay.fmt == gg::kFmtMXFP4 &&
2885                                         (l.nm == 1 || (flow_tp && (g.ff / l.nm) %
2886                                                        std::max(1, gg::type_block(gg::expert_type(l.lay, 2))) == 0));
2887                                    n_exp_max = std::max(n_exp_max, l.n_exp);
2888                                }
2889                    if (fl)   // (each part read unbuffered from its offset rounded down: a page more each)
2890                        cp->stage_stride = std::max(cp->stage_stride, flow_stride());
2891                    cp->S = cp->ring_n;
2892                    if (const char* sm = std::getenv("DS4_STAGE_MB"))   // (pinned RAM: the reads run that far ahead of the ring)
2893                        cp->S = std::max(cp->S, (int) (((size_t) std::atoll(sm) << 20) / cp->stage_stride));
2894                    if (!halloc(cp->stage, (size_t) cp->S * cp->stage_stride, err)) return false;
2895                    cp->readers = std::make_unique<Pool>(n_readers - 1, std::vector<int>{}, 50);
2896                    if (!fl) continue;
2897                    cudaSetDevice(devs[di].id);
2898                    cp->flow = true;
2899                    cp->dev = (int) di;
2900                    cp->io = std::make_unique<IoQueue>(n_readers);
2901                    cp->stage_item.assign((size_t) cp->S, -1);
2902                    cp->stage_ev.resize((size_t) cp->S);
2903                    cp->ring_fill.resize((size_t) cp->ring_n);
2904                    cp->ring_free.resize((size_t) cp->ring_n);
2905                    for (auto* v : {&cp->stage_ev, &cp->ring_fill, &cp->ring_free})
2906                        for (cudaEvent_t& e : *v) CK(cudaEventCreateWithFlags(&e, cudaEventDisableTiming));
2907                    // (a region is written again only bc_n batches later - more than a layer's items, so after that
2908                    // layer's bounds wait, which every copy from it precedes)
2909                    cp->bc_n = n_exp_max + 2;
2910                    cp->bc_w = cp->ring_n + 1;
2911                    if (!halloc(cp->bc_pin, (size_t) cp->bc_n * cp->bc_w, err) ||
2912                        !dalloc(devs[di], cp->bc_dev, (size_t) cp->bc_n * cp->bc_w, err))
2913                        return false;
2914                }
2915                // every device with layers on the flow: a prompt reads only the experts it picks, once, so a short one
2916                // takes the chunked path too (one pass, where windows of 16 read the CPU lane's picks again for each
2917                // window, a page fault at a time) - DS4_CHUNK_MIN still overrides
2918                bool all_flow = true;
2919                for (const auto& cp : chunks) all_flow = all_flow && (cp == nullptr || cp->ring == nullptr || cp->flow);
2920                if (all_flow && std::getenv("DS4_CHUNK_MIN") == nullptr) chunk_min = kFlowChunkMin;
2921            }
2922            for (Layer& l : L) {
2923                if (l.mtp) continue;
2924                for (int m = 0; m < l.nm; ++m) {   // (each member its own: the flow's members decide them each)
2925                    Layer& x = member(l, m);
2926                    if (!halloc(x.vs_pin, (size_t) l.n_exp, err)) return false;
2927                    if (!dalloc(devs[(size_t) x.dev], x.vs_dev, (size_t) l.n_exp, err)) return false;
2928                }
2929            }
2930        }
2931        {
2932            void* m = nullptr;
2933            if (cudaHostAlloc(&m, sizeof(Req) * kRing, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) {
2934                err = "host-mapped memory for the decode path's requests";
2935                return false;
2936            }
2937            host_allocs.push_back(m);
2938            reqs = (Req*) m;
2939            if (cudaHostAlloc(&m, sizeof(Resp) * kRing, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) {
2940                err = "host-mapped memory for the decode path's answers";
2941                return false;
2942            }
2943            host_allocs.push_back(m);
2944            resps = (Resp*) m;
2945            std::memset((void*) reqs, 0, sizeof(Req) * kRing);
2946            std::memset((void*) resps, 0, sizeof(Resp) * kRing);
2947            for (auto& x : layer_of) x.store(-1);
2948            ahead_fl.assign(L.size() * 1024, 0);
2949            ahead_rank.assign(L.size() * 1024, 0);
2950            ahead_for.assign(L.size(), 0);
2951            const int core = !cores.empty() && !cores[0].empty() ? cores[0][0] : -1;
2952            service = std::thread([this, core] {
2953                if (core >= 0) pin_self(core);
2954                serve_lane();
2955            });
2956            if (ahead_mode > 0) pf_th = std::thread([this] { prefetch_loop(); });
2957        }
2958        if (o.expert_cache) {
2959            size_t maxb = 0;
2960            for (const Layer& l : L) maxb = std::max(maxb, l.blob);
2961            const int nt = std::max(1, std::min(c_inflight, std::getenv("DS4_CACHE_THREADS") ? std::atoi(std::getenv("DS4_CACHE_THREADS")) : 1));
2962            sw_bufs.resize((size_t) nt);
2963            for (SwapBufs& B : sw_bufs) {
2964                if (!halloc(B.a, maxb, err) || !halloc(B.b, maxb, err) || !halloc(B.h, maxb, err)) return false;
2965                for (Dev& d : devs) {
2966                    cudaSetDevice(d.id);
2967                    cudaStream_t cs = nullptr;
2968                    CK(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking));
2969                    B.st.push_back(cs);
2970                }
2971            }
2972            for (SwapBufs& B : sw_bufs) cache_ths.emplace_back([this, &B] { cache_loop(B); });
2973        }
2974        for (Dev& d : devs) {
2975            cudaSetDevice(d.id);
2976            CK(cudaStreamSynchronize(d.st));
2977        }
2978        if (par || chunk > 0)   // (the windows' threads; the prompt path's, whatever mode the windows take)
2979            for (size_t di = 0; di < devs.size(); ++di) {
2980                workers.push_back(std::make_unique<Worker>());
2981                workers.back()->start();
2982            }
2983        calibrate_paths();
2984        init_store();      // (last: the store's arena is registered with the driver - page-locked memory the other pinned allocations must come before)
2985        preload_store();
2986        if (o.verbose) std::fprintf(stderr, "ds4: loaded in %.1f s\n%s", (now_ms() - t0) / 1000.0, describe().c_str());
2987        if (chunk > 0) (void) pick_flow_min();   // (the startup line)
2988        reset();
2989        start_warm();
2990        return true;
2991    }
2992
2993
2994    // the caches' row bytes, packed as DeepSeek keeps them (ds4_kernels.cuh): the window ring's (FP8), the compressed
2995    // KV's (FP4 + E4M3 scales), the index keys' (FP4 + power-of-two scales)
2996    size_t win_rb() const { return kv_row_bytes(kKvFp8, g.hd); }
2997    size_t ckv_rb() const { return kv_row_bytes(kKvFp4, g.hd); }
2998    size_t ik_rb() const { return kv_row_bytes(kKvFp4p, g.ix_hd); }
2999
3000    // The chunked prompt's first GEMM of each kind pays the BLAS library's start (its handle's heuristics, the code objects of its
3001    // kernels loaded on first use): ~1 s of hipModuleLoad plus ~2.5 s of library time on the R9700 (rocprofv3), 1-2 s on CUDA, once a
3002    // process - 3.6 s on the first prompt that went through the flow, measured as 4.9 s for a 25-token pass against 1.0 s for the
3003    // next one.  Paid here instead, at load, on a thread beside the store's read: the chunk GEMMs on tiny inputs into the chunk's own
3004    // scratch buffers (the mHC mix GEMM in F32, the FP16 GEMM the projections and the indexer weights use) - no engine state is
3005    // touched (heat, profile, stats, positions, KV), so the answers are what they were.  DS4_WARM=0 turns it off.
3006    void warm_flow() {
3007        const int T = 16, D = g.dim, hcd = g.hc * g.dim, n_mix = (2 + g.hc) * g.hc;
3008        const float one = 1.0f, zero = 0.0f;
3009        for (size_t di = 0; di < chunks.size(); ++di) {
3010            if (!chunks[di] || chunks[di]->blas == nullptr) continue;
3011            Chunk& c = *chunks[di];
3012            if (c.C < T) continue;
3013            cudaSetDevice(devs[di].id);
3014            (void) cublasSgemm(c.blas, CUBLAS_OP_T, CUBLAS_OP_N, n_mix, T, hcd, &one, c.h, hcd, c.h, hcd, &zero, c.mix, 32);
3015            const int ns[2] = {256, 32};
3016            for (int n : ns)
3017                (void) cublasGemmEx(c.blas, CUBLAS_OP_T, CUBLAS_OP_N, n, T, D, &one, c.w16, CUDA_R_16F, D, c.x16, CUDA_R_16F, D, &zero,
3018                                    c.y, CUDA_R_32F, n, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP);
3019            (void) cudaStreamSynchronize(devs[di].st);
3020            (void) cudaGetLastError();
3021        }
3022    }
3023    // The warm-up runs once the model is loaded, on a thread of its own: HIP serialises the BLAS start with the store's page-locked
3024    // arena (measured: beside the store's read it finished only when the read did, 21 s, and load still grew by its 3.5 s), so
3025    // it cannot hide inside the load; after it, a person typing gives it the seconds it needs.  A chunked pass that starts first
3026    // waits for it (warm_mu) - never later than that pass would have been without it - and a warm-up that finds the flow already
3027    // used does nothing.  DS4_WARM=0 turns it off.
3028    std::mutex warm_mu;
3029    std::atomic<bool> flow_used{false};
3030    std::thread warm_bg;
3031    void start_warm() {
3032        if (chunk <= 0 || (std::getenv("DS4_WARM") && std::atoi(std::getenv("DS4_WARM")) == 0)) return;
3033        warm_bg = std::thread([this] {
3034            std::lock_guard<std::mutex> lk(warm_mu);
3035            if (flow_used.load() || quit.load()) return;
3036            const double tw = now_ms();
3037            warm_flow();
3038            if (o.verbose) std::fprintf(stderr, "ds4: prompt path warmed up in %.0f ms\n", now_ms() - tw);
3039        });
3040    }
3041    // ---- the chunked prompt path
3042    size_t x_cap() const { return (size_t) std::max<int>(kWin, chunk + 2); }   // a window's / chunk's new source rows
3043    size_t chunk_hand_bytes() const {
3044        return (size_t) chunk * ((size_t) g.hc * g.dim * 4 + 8 * 4 + topk_stride() * 4 + cand_stride() * 4);
3045    }
3046
3047    // the staging ring's size (MB) for the experts a chunk streams from the CPU lane: 400 where a good part of them are
3048    // streamed; 16 where the cards hold most of the experts (they are within 30% of fitting) (a 4-card box) - the ring's VRAM is then worth more
3049    // as expert slots, and the decode after a prompt keeps the windowed path's speed (R9700 x4: 29.6 -> 31.7 tok/s)
3050    // The share of the routed experts the GPUs can hold, from what is known at layout (their free memory less the reserve, the
3051    // prompt path's buffers and the dense weights; the trunk's experts only when no drafter is loaded): 1 = all of them.
3052    double gpu_expert_share(double* exp_out = nullptr, double* room_out = nullptr, double* other_out = nullptr) const {
3053        double exp_b = 0, other_b = 0, room = 0;
3054        for (const auto& kt : pk.t) {
3055            const std::string& n = kt.first;
3056            if (n.find(".engram.embed.") != std::string::npos || n.rfind("vision.", 0) == 0 || n == "embed.weight" ||
3057                (!o.dspark && n.rfind("mtp.", 0) == 0))
3058                continue;
3059            (n.find(".ffn.experts.") != std::string::npos ? exp_b : other_b) += (double) kt.second.bytes;
3060        }
3061        for (const Dev& d : devs)
3062            room += std::max(0.0, (double) d.free0 - (double) ((size_t) o.reserve_mib << 20) - 1.5 * (1 << 30)) * o.vram_experts;
3063        if (exp_out) *exp_out = exp_b;
3064        if (room_out) *room_out = room;
3065        if (other_out) *other_out = other_b;
3066        return exp_b > 0 ? std::min(1.0, std::max(0.0, room - other_b) / exp_b) : 1.0;
3067    }
3068    size_t ring_mb_auto() const {
3069        double exp_b = 0, other_b = 0, room = 0;
3070        const double share = gpu_expert_share(&exp_b, &room, &other_b);
3071        const bool fit = exp_b > 0 && share >= 1.0 / 1.3;   // (R9700 x4: 0.86 -> ring 16: decode -1.8% after a prompt, 64: -4.4%, 400: -4.6%)
3072        if (o.verbose)
3073            std::fprintf(stderr, "ds4: staging ring: experts %.1f GB, VRAM room %.1f GB, dense %.1f GB -> %d MB\n", exp_b / 1e9,
3074                         room / 1e9, other_b / 1e9, fit ? 16 : 400);
3075        return fit ? 16 : 400;
3076    }
3077    bool alloc_chunks(std::string& err) {
3078        chunks.resize(devs.size());
3079        const int D = g.dim, H = g.hc, HD = g.hd;
3080        const int cols = (pk.eg_ngram - 1) * pk.eg_heads, ehd = pk.eg_hd;
3081        for (size_t di = 0; di < devs.size(); ++di) {
3082            Dev& d = devs[di];
3083            cudaSetDevice(d.id);
3084            chunks[di] = std::make_unique<Chunk>();
3085            Chunk& c = *chunks[di];
3086            const int nm = (int) groups[(size_t) d.grp].mem.size();
3087            const int NHL = g.heads / head_members(nm), HQ = NHL * HD, OG = g.o_groups / head_members(nm);
3088            int FF = 0, ff0_ = 0;
3089            split128(g.ff, nm, 0, ff0_, FF);   // (the widest member's share: member 0 takes the odd blocks)
3090            const size_t C = (size_t) (lend_min_ > 0 ? chunk_small_ : chunk);   // (the host buffers: `chunk`'s)
3091            c.C = (int) C;
3092            c.A = std::max(64, (int) (((size_t) 8 << 20) / (size_t) HQ) / 64 * 64);
3093            // (DS4_ATTN_SLAB=N: N rows a slab - every slab dequantizes wq_b, wo_a and wo_b again, so fewer slabs are
3094            //  fewer dequants, for A * HQ * 10 more bytes of VRAM)
3095            if (const char* v = std::getenv("DS4_ATTN_SLAB")) c.A = std::max(64, std::min(c.C, std::atoi(v)) / 64 * 64);
3096            // (the indexer's slab: its scores rows are the context wide - about 64 MB of them)
3097            c.AI = std::max(32, std::min(128, (int) (((size_t) 64 << 20) / (((size_t) o.max_context + 64) * 4)) / 32 * 32));
3098            c.w16_elems = (size_t) 8 << 20;
3099            bool has_eg = false, has_first = false;
3100            size_t stride = 0;
3101            for (const Layer& l : L)
3102                for (int m = 0; m < l.nm; ++m)
3103                    if (member(l, m).dev == (int) di && !l.mtp) {
3104                        has_eg = has_eg || l.eg >= 0;
3105                        has_first = has_first || l.il == 0;
3106                        stride = std::max(stride, align256(unit(member(l, m))));
3107                    }
3108            const size_t A = (size_t) c.A, AI = (size_t) c.AI, ss = (size_t) o.max_context + 64;
3109            bool ok = dalloc(d, c.h, C * H * D, err) && dalloc(d, c.x, C * D, err) && dalloc(d, c.acc, C * D, err) &&
3110                      dalloc(d, c.x16, C * D, err) && dalloc(d, c.qr, C * g.q_lora, err) &&
3111                      dalloc(d, c.qr16, C * g.q_lora, err) && dalloc(d, c.kvr, C * HD, err) &&
3112                      dalloc(d, c.ckr, C * HD, err) && dalloc(d, c.cgr, C * HD, err) &&
3113                      dalloc(d, c.latent, (C + 2) * HD, err) && dalloc(d, c.lat16, (C + 2) * HD, err) &&
3114                      dalloc(d, c.ikr, (C + 2) * g.ix_hd, err) && dalloc(d, c.ext, ((size_t) g.win + C) * HD, err) &&
3115                      dalloc(d, c.q, A * HQ, err) && dalloc(d, c.o, A * HQ, err) && dalloc(d, c.o16, A * HQ, err) &&
3116                      dalloc(d, c.oa, A * OG * g.o_lora, err) && dalloc(d, c.oa16, A * OG * g.o_lora, err) &&
3117                      dalloc(d, c.iq, AI * g.ix_heads * g.ix_hd, err) && dalloc(d, c.iw, C * 64, err) &&
3118                      dalloc(d, c.scores, AI * ss, err) && dalloc(d, c.bm, AI * bm_stride(), err) &&
3119                      dalloc(d, c.topk, C * topk_stride(), err) && dalloc(d, c.cand, C * cand_stride(), err) &&
3120                      dalloc(d, c.mix, C * 32, err) && dalloc(d, c.a_pre, C * 8, err) && dalloc(d, c.a_post, C * 8, err) &&
3121                      dalloc(d, c.a_comb, C * 64, err) && dalloc(d, c.f_pre, C * 8, err) &&
3122                      dalloc(d, c.f_post, C * 8, err) && dalloc(d, c.f_comb, C * 64, err) && dalloc(d, c.pre, C * 8, err) &&
3123                      dalloc(d, c.glog, C * 1024, err) && dalloc(d, c.ridx, C * kPicks, err) &&
3124                      dalloc(d, c.rw, C * kPicks, err) && dalloc(d, c.bounds, 2048, err) &&
3125                      dalloc(d, c.row_tok, C * kPicks, err) && dalloc(d, c.pos, C * kPicks, err) &&
3126                      dalloc(d, c.sg, C * FF, err) && dalloc(d, c.su, C * FF, err) && dalloc(d, c.sh16, C * FF, err) &&
3127                      dalloc(d, c.h16, C * FF, err) && dalloc(d, c.y, C * D, err) && dalloc(d, c.w16, c.w16_elems, err) &&
3128                      halloc(c.bounds_pin, 2048, err);
3129            if (!ok) return false;
3130            if (has_first && !dalloc(d, c.emb, C * D, err)) return false;
3131            if (lend_min_ == 0 && std::getenv("DS4_ATTN_WCACHE") != nullptr && std::atoi(std::getenv("DS4_ATTN_WCACHE")) != 0 &&
3132                !dalloc(d, c.wc, (size_t) HQ * g.q_lora + (size_t) HQ * g.o_lora + (size_t) D * OG * g.o_lora, err))
3133                return false;
3134            if (has_eg) {
3135                const size_t ES = 256, per = (size_t) cols * (ehd + ehd / 32);
3136                if (!dalloc(d, c.eg_x, ES * cols * ehd, err) || !dalloc(d, c.eg_x16, ES * cols * ehd, err) ||
3137                    !dalloc(d, c.eg_kv, ES * (H + 1) * D, err) || !dalloc(d, c.eg_rows, C * per, err))
3138                    return false;
3139            }
3140            if (stride > 0) {   // DS4_RING_MB (400) of slots in kParts batches
3141                const size_t mb = std::getenv("DS4_RING_MB") ? (size_t) std::atoi(std::getenv("DS4_RING_MB")) : ring_mb_auto();
3142                c.ring_stride = stride;
3143                c.ring_n = std::max(Chunk::kParts, (int) ((mb << 20) / stride) / Chunk::kParts * Chunk::kParts);
3144                if (!dalloc(d, c.ring, (size_t) c.ring_n * stride, err)) return false;
3145            }
3146            CK(cudaStreamCreateWithFlags(&c.cs, cudaStreamNonBlocking));
3147            for (int i = 0; i < Chunk::kParts; ++i) {
3148                CK(cudaEventCreateWithFlags(&c.filled[i], cudaEventDisableTiming));
3149                CK(cudaEventCreateWithFlags(&c.freed[i], cudaEventDisableTiming));
3150            }
3151            if (cublasCreate(&c.blas) != CUBLAS_STATUS_SUCCESS || cublasSetStream(c.blas, d.st) != CUBLAS_STATUS_SUCCESS) {
3152                err = "cuBLAS on CUDA" + std::to_string(d.id);
3153                return false;
3154            }
3155            for (int sl = 0; sl < 2; ++sl) {
3156                // (DS4_HAND_SKIP=1: none with one group - nothing hands a chunk on; they are 2 x 1.4 GB of pinned RAM at 16K rows)
3157                static const bool hand_skip = std::getenv("DS4_HAND_SKIP") != nullptr && std::atoi(std::getenv("DS4_HAND_SKIP")) != 0;
3158                if (d.mi == 0 && !(hand_skip && groups.size() == 1) &&
3159                    (!hmap(c.hand[sl], chunk_hand_bytes(), err) || !hmap(c.hand_flag[sl], 32, err)))
3160                    return false;
3161                if (has_first && !halloc(c.emb_host[sl], (size_t) chunk * D, err)) return false;
3162                if (has_eg && !halloc(c.eg_host[sl], (size_t) chunk * pk.eg_layers * (size_t) cols * (ehd + ehd / 32), err))
3163                    return false;
3164                CK(cudaEventCreateWithFlags(&c.emb_ev[sl], cudaEventDisableTiming));
3165                CK(cudaEventCreateWithFlags(&c.eg_ev[sl], cudaEventDisableTiming));
3166            }
3167            if (d.mi == 0 && !hmap(c.hand_ack, (size_t) 2 * 8 * 32, err)) return false;
3168        }
3169        return true;
3170    }
3171
3172    // y[r][c] = x16[r] . W[:, c] (+ beta y) for r < rows: W reconstructed to FP16 in whole 128-column blocks, cuBLAS
3173    bool gemm(Dev& d, Chunk& c, const x3::Mat& m, const uint16_t* x16, int ldx, int rows, float* y, int ldy, float beta,
3174              std::string& err) {
3175        if (rows <= 0) return true;
3176        const int cols = std::max(128, (int) std::min<size_t>((size_t) m.n, c.w16_elems / (size_t) m.k) / 128 * 128);
3177        for (int c0 = 0; c0 < m.n; c0 += cols) {
3178            const int nc = std::min(cols, m.n - c0);
3179            if (m.fmt != 0) gg::rows(nc == m.n ? m : gg::view(m, c0, nc), c.w16, false, d.st);   // (a GGUF's)
3180            else x3::reconstruct_rows(nc == m.n ? m : x3::view(m, c0, nc), c.w16, false, d.st);
3181            const float one = 1.0f;
3182            const cublasStatus_t st = cublasGemmEx(c.blas, CUBLAS_OP_T, CUBLAS_OP_N, nc, rows, m.k, &one, c.w16, CUDA_R_16F,
3183                                                   m.k, x16, CUDA_R_16F, ldx, &beta, y + c0, CUDA_R_32F, ldy,
3184                                                   CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT_TENSOR_OP);
3185            if (st != CUBLAS_STATUS_SUCCESS) {
3186                err = "cublasGemmEx: status " + std::to_string((int) st);
3187                return false;
3188            }
3189        }
3190        return true;
3191    }
3192    // gemm() with the FP16 reconstruction kept in w (its tag: the matrix it holds) - built only when another matrix
3193    // is asked for, so a layer's slabs share one; the same column blocks, the same cuBLAS calls, the same bits
3194    bool gemm_kept(Dev& d, Chunk& c, const x3::Mat& m, uint16_t* w, const void*& tag, const uint16_t* x16, int ldx,
3195                   int rows, float* y, int ldy, float beta, std::string& err) {
3196        if (w == nullptr) return gemm(d, c, m, x16, ldx, rows, y, ldy, beta, err);
3197        if (rows <= 0) return true;
3198        const int cols = std::max(128, (int) std::min<size_t>((size_t) m.n, c.w16_elems / (size_t) m.k) / 128 * 128);
3199        const void* id = m.fmt != 0 ? m.raw : (const void*) m.trellis;
3200        if (tag != id) {
3201            for (int c0 = 0; c0 < m.n; c0 += cols) {
3202                const int nc = std::min(cols, m.n - c0);
3203                uint16_t* dst = w + (size_t) c0 * m.k;
3204                if (m.fmt != 0) gg::rows(nc == m.n ? m : gg::view(m, c0, nc), dst, false, d.st);
3205                else x3::reconstruct_rows(nc == m.n ? m : x3::view(m, c0, nc), dst, false, d.st);
3206            }
3207            tag = id;
3208        }
3209        for (int c0 = 0; c0 < m.n; c0 += cols) {
3210            const int nc = std::min(cols, m.n - c0);
3211            const float one = 1.0f;
3212            const cublasStatus_t st = cublasGemmEx(c.blas, CUBLAS_OP_T, CUBLAS_OP_N, nc, rows, m.k, &one,
3213                                                   w + (size_t) c0 * m.k, CUDA_R_16F, m.k, x16, CUDA_R_16F, ldx, &beta,
3214                                                   y + c0, CUDA_R_32F, ldy, CUBLAS_COMPUTE_32F,
3215                                                   CUBLAS_GEMM_DEFAULT_TENSOR_OP);
3216            if (st != CUBLAS_STATUS_SUCCESS) {
3217                err = "cublasGemmEx: status " + std::to_string((int) st);
3218                return false;
3219            }
3220        }
3221        return true;
3222    }
3223    // y[r][c] = alpha x16[r] . W[c] for F16 weights W [n][k] (the indexer's weights_proj)
3224    bool gemm_f16w(Chunk& c, const uint16_t* W, int n, int k, const uint16_t* x16, int ldx, int rows, float alpha,
3225                   float* y, int ldy, std::string& err) {
3226        const float zero = 0.0f;
3227        const cublasStatus_t st = cublasGemmEx(c.blas, CUBLAS_OP_T, CUBLAS_OP_N, n, rows, k, &alpha, W, CUDA_R_16F, k,
3228                                               x16, CUDA_R_16F, ldx, &zero, y, CUDA_R_32F, ldy, CUBLAS_COMPUTE_32F,
3229                                               CUBLAS_GEMM_DEFAULT_TENSOR_OP);
3230        if (st != CUBLAS_STATUS_SUCCESS) {
3231            err = "cublasGemmEx (F16 weights): status " + std::to_string((int) st);
3232            return false;
3233        }
3234        return true;
3235    }
3236    // hc_mix over a chunk: the dots by an F32 GEMM, then the rms scale
3237    bool hc_mix_chunk(Dev& d, Chunk& c, const float* h, const float* fn, int T, float* mixes, std::string& err) {
3238        const int hcd = g.hc * g.dim, n_mix = (2 + g.hc) * g.hc;
3239        const float one = 1.0f, zero = 0.0f;
3240        if (cublasSgemm(c.blas, CUBLAS_OP_T, CUBLAS_OP_N, n_mix, T, hcd, &one, fn, hcd, h, hcd, &zero, mixes, 32) !=
3241            CUBLAS_STATUS_SUCCESS) {
3242            err = "cublasSgemm (mHC mixes)";
3243            return false;
3244        }
3245        hc_mix_scale(h, hcd, n_mix, T, g.eps, mixes, d.st);
3246        return true;
3247    }
3248
3249    // expert e of l (on the CPU lane: its NH column parts) -> member m's VRAM copy at dst, in the GPU layout (the full
3250    // blob, or a group member's part), by DMA from the pinned parts on the copy stream (in place: from `src`, its file
3251    // region read into pinned staging)
3252    bool stream_expert(const Layer& l, int m, int e, uint8_t* dst, cudaStream_t cs, std::string& err,
3253                       const uint8_t* src = nullptr) {
3254        if (l.lay.fmt == gg::kFmtMXFP4) {   // the blob, or member m's rows / blocks: from `src` (the expert read into
3255            // pinned staging as its blob) or from the file's mapping
3256            auto mat_r = [&](int r) { return src != nullptr ? src + l.lay.trellis[r] : mx_mat(l, e, r); };
3257            bool ok = true;
3258            if (l.nm == 1) {
3259                if (src != nullptr)
3260                    ok = cudaMemcpyAsync(dst, src, l.blob, cudaMemcpyHostToDevice, cs) == cudaSuccess;
3261                else
3262                    for (int r = 0; r < 3; ++r)
3263                        ok = ok && cudaMemcpyAsync(dst + l.lay.trellis[r], mat_r(r), mx_part_bytes(l, r),
3264                                                   cudaMemcpyHostToDevice, cs) == cudaSuccess;
3265            } else {
3266                const int ffh = g.ff / l.nm;
3267                const size_t gr = gg::type_row_bytes(gg::expert_type(l.lay, 0), g.dim),
3268                             dr = gg::type_row_bytes(gg::expert_type(l.lay, 2), g.ff),
3269                             dh = gg::type_row_bytes(gg::expert_type(l.lay, 2), ffh);
3270                for (int r = 0; r < 2; ++r)
3271                    ok = ok && cudaMemcpyAsync(dst + l.hlay.trellis[r], mat_r(r) + (size_t) m * ffh * gr,
3272                                               (size_t) ffh * gr, cudaMemcpyHostToDevice, cs) == cudaSuccess;
3273                ok = ok && cudaMemcpy2DAsync(dst + l.hlay.trellis[2], dh, mat_r(2) + (size_t) m * dh, dr, dh,
3274                                             (size_t) g.dim, cudaMemcpyHostToDevice, cs) == cudaSuccess;
3275            }
3276            if (!ok) err = "streaming layer " + std::to_string(l.il) + " expert " + std::to_string(e) + " failed";
3277            return ok;
3278        }
3279        const auto& parts = l.hh[(size_t) e];
3280        const int D = g.dim, FF = g.ff;
3281        auto cp2 = [&](uint8_t* d0, size_t dp, const uint8_t* s0, size_t sp, size_t w, size_t h) {
3282            return cudaMemcpy2DAsync(d0, dp, s0, sp, w, h, cudaMemcpyHostToDevice, cs) == cudaSuccess;
3283        };
3284        auto cp = [&](uint8_t* d0, const uint8_t* s0, size_t n) {
3285            return cudaMemcpyAsync(d0, s0, n, cudaMemcpyHostToDevice, cs) == cudaSuccess;
3286        };
3287        bool ok = true;
3288        if (NH == 1) {   // one part: the whole expert in exllamav3's layout, its pieces at hl's offsets
3289            const uint8_t* p = src != nullptr ? src : parts[0];
3290            if (l.nm == 1) {
3291                for (int r = 0; r < 3; ++r)
3292                    ok = ok && cp(dst + l.lay.trellis[r], p + l.hl.trellis[r], l.piece_bytes[r][0]) &&
3293                         cp(dst + l.lay.suh[r], p + l.hl.suh[r], (size_t) l.hl.k[r] * 2) &&
3294                         cp(dst + l.lay.svh[r], p + l.hl.svh[r], (size_t) l.hl.n[r] * 2);
3295            } else {   // member m's part (its FFN columns [f0, f0 + fn)), cut as blob_to_half cuts a blob
3296                const Layer& x = member(l, m);
3297                const int f0 = x.ff0, fn = x.ffn;
3298                for (int r = 0; r < 2; ++r) {
3299                    const size_t tile = (size_t) 32 * l.lay.K[r], nt = (size_t) FF / 16, nth = (size_t) fn / 16;
3300                    ok = ok && cp2(dst + x.hlay.trellis[r], nth * tile, p + l.hl.trellis[r] + (size_t) (f0 / 16) * tile,
3301                                   nt * tile, nth * tile, (size_t) D / 16) &&
3302                         cp(dst + x.hlay.suh[r], p + l.hl.suh[r], (size_t) D * 2) &&
3303                         cp(dst + x.hlay.svh[r], p + l.hl.svh[r] + (size_t) f0 * 2, (size_t) fn * 2);
3304                }
3305                const size_t row = (size_t) (D / 16) * 32 * l.lay.K[2];
3306                ok = ok && cp(dst + x.hlay.trellis[2], p + l.hl.trellis[2] + (size_t) (f0 / 16) * row,
3307                              (size_t) (fn / 16) * row) &&
3308                     cp(dst + x.hlay.suh[2], p + l.hl.suh[2] + (size_t) f0 * 2, (size_t) fn * 2) &&
3309                     cp(dst + x.hlay.svh[2], p + l.hl.svh[2], (size_t) D * 2);
3310            }
3311        } else if (l.nm == 1) {   // the full blob: each matrix's columns from the two parts side by side
3312            for (int r = 0; r < 3; ++r) {
3313                const size_t tile = (size_t) 32 * l.lay.K[r];
3314                const int k = l.hl.k[r], nh = l.hl.n[r];   // part: k x nh
3315                for (int X = 0; X < 2; ++X) {
3316                    ok = ok && cp2(dst + l.lay.trellis[r] + (size_t) X * (nh / 16) * tile, (size_t) (2 * nh / 16) * tile,
3317                                   parts[(size_t) X] + l.hl.trellis[r], (size_t) (nh / 16) * tile, (size_t) (nh / 16) * tile,
3318                                   (size_t) (k / 16));
3319                    ok = ok && cp(dst + l.lay.svh[r] + (size_t) X * nh * 2, parts[(size_t) X] + l.hl.svh[r], (size_t) nh * 2);
3320                }
3321                ok = ok && cp(dst + l.lay.suh[r], parts[0] + l.hl.suh[r], (size_t) k * 2);
3322            }
3323        } else {   // member m (FFN columns [f0, f0 + fn)): gate / up from the parts holding them; down rows [f0, ..) of
3324                   // both parts' columns
3325            const Layer& x = member(l, m);
3326            const int f0 = x.ff0, fn = x.ffn;
3327            for (int r = 0; r < 2; ++r) {
3328                const size_t tile = (size_t) 32 * l.lay.K[r];
3329                const int hn = l.hl.n[r];   // part X: columns [X hn, (X + 1) hn)
3330                for (int X = 0; X < 2; ++X) {
3331                    const int a = std::max(f0, X * hn), b = std::min(f0 + fn, (X + 1) * hn);
3332                    if (a >= b) continue;
3333                    ok = ok && cp2(dst + x.hlay.trellis[r] + (size_t) ((a - f0) / 16) * tile, (size_t) (fn / 16) * tile,
3334                                   parts[(size_t) X] + l.hl.trellis[r] + (size_t) ((a - X * hn) / 16) * tile,
3335                                   (size_t) (hn / 16) * tile, (size_t) ((b - a) / 16) * tile, (size_t) (D / 16)) &&
3336                         cp(dst + x.hlay.svh[r] + (size_t) (a - f0) * 2, parts[(size_t) X] + l.hl.svh[r] + (size_t) (a - X * hn) * 2,
3337                            (size_t) (b - a) * 2);
3338                }
3339                ok = ok && cp(dst + x.hlay.suh[r], parts[0] + l.hl.suh[r], (size_t) D * 2);
3340            }
3341            const size_t tile = (size_t) 32 * l.lay.K[2];
3342            const int nh = D / 2;
3343            for (int X = 0; X < 2; ++X) {
3344                ok = ok && cp2(dst + x.hlay.trellis[2] + (size_t) X * (nh / 16) * tile, (size_t) (D / 16) * tile,
3345                               parts[(size_t) X] + l.hl.trellis[2] + (size_t) (f0 / 16) * (nh / 16) * tile,
3346                               (size_t) (nh / 16) * tile, (size_t) (nh / 16) * tile, (size_t) (fn / 16));
3347                ok = ok && cp(dst + x.hlay.svh[2] + (size_t) X * nh * 2, parts[(size_t) X] + l.hl.svh[2], (size_t) nh * 2);
3348            }
3349            ok = ok && cp(dst + x.hlay.suh[2], parts[0] + l.hl.suh[2] + (size_t) f0 * 2, (size_t) fn * 2);
3350        }
3351        if (!ok) err = "streaming layer " + std::to_string(l.il) + " expert " + std::to_string(e) + " failed";
3352        return ok;
3353    }
3354
3355    // a device's streamed experts: batches of ring_n / kParts of each of its layers' CPU-lane experts, chunk by chunk
3356    // in layer order; the copies run at most kParts batches ahead of the compute
3357    struct Batch {
3358        int k = 0, il = 0, j0 = 0, n = 0;   // chunk, layer, its host_list range
3359    };
3360    struct Streamer {
3361        std::vector<Batch> b;
3362        size_t cp = 0, kp = 0;        // the next batch to copy, to compute
3363        std::atomic<size_t> done{0};  // cp, for read_ahead's thread
3364    };
3365    // in place (file_experts): the batches' file regions read ahead of their copies - POSIX_FADV_WILLNEED, the kernel
3366    // reading them in the background in large requests, where the copies alone fault the pages in a few at a time -
3367    // at most DS4_READAHEAD_MB (2048) beyond the batch being copied; each region by its layer's first member alone
3368    void read_ahead(const Streamer& S, int di, const std::atomic<bool>& stop) const {
3369        static const double cap = (std::getenv("DS4_READAHEAD_MB") ? std::atof(std::getenv("DS4_READAHEAD_MB")) : 2048.0) *
3370                                  1048576.0;
3371        std::deque<std::pair<size_t, double>> issued;   // (batch, bytes) not yet copied
3372        double ahead = 0;
3373        for (size_t q = 0; q < S.b.size() && !stop.load(std::memory_order_relaxed);) {
3374            const size_t done = S.done.load(std::memory_order_relaxed);
3375            while (!issued.empty() && issued.front().first < done) {
3376                ahead -= issued.front().second;
3377                issued.pop_front();
3378            }
3379            if (ahead > cap) {
3380                std::this_thread::sleep_for(std::chrono::microseconds(500));
3381                continue;
3382            }
3383            const Batch& bt = S.b[q];
3384            const Layer& l0 = L[(size_t) bt.il];
3385            double nb = 0;
3386            if (l0.dev == di)
3387                for (int i = 0; i < bt.n; ++i) {
3388                    const int e = l0.host_list[(size_t) (bt.j0 + i)];
3389                    if (l0.lay.fmt == gg::kFmtMXFP4) {
3390                        if (copy_mode && l0.ram[(size_t) e] >= 0) continue;   // (in RAM: nothing to read)
3391                        for (int r = 0; r < 3; ++r)
3392                            os::advise(pk.fds[(size_t) l0.mx_file[r]], (l0.mx_off[r] + (uint64_t) e * l0.mx_stride[r]), mx_part_bytes(l0, r), true);
3393                        nb += (double) l0.blob;
3394                        continue;
3395                    }
3396                    os::advise(pk.fds[(size_t) l0.region_file[(size_t) e]], l0.region_off[(size_t) e], l0.region_bytes[(size_t) e], true);
3397                    nb += (double) l0.region_bytes[(size_t) e];
3398                }
3399            issued.push_back({q++, nb});
3400            ahead += nb;
3401        }
3402    }
3403    bool copy_ahead(Dev& d, Chunk& c, Streamer& S, int di, std::string& err) {
3404        const int P = Chunk::kParts;
3405        while (S.cp < S.b.size() && S.cp < S.kp + P) {
3406            const Batch& bt = S.b[S.cp];
3407            const int half = (int) (S.cp % P);
3408            const Layer& l0 = L[(size_t) bt.il];
3409            int mi = 0;
3410            for (int m = 0; m < l0.nm; ++m)
3411                if (member(l0, m).dev == di) mi = m;
3412            if (S.cp >= (size_t) P) CK(cudaStreamWaitEvent(c.cs, c.freed[half], 0));
3413            uint8_t* sb = nullptr;   // in place: the batch's regions in the part's staging slots
3414            if (c.stage != nullptr) {
3415                if (S.cp >= (size_t) P) CK(cudaEventSynchronize(c.filled[half]));   // (its last batch's copies out)
3416                sb = c.stage + (size_t) half * (c.ring_n / P) * c.stage_stride;
3417                std::atomic<bool> bad{false};
3418                c.readers->run(bt.n, [&](int i) {
3419                    const int e = l0.host_list[(size_t) (bt.j0 + i)];
3420                    if (l0.lay.fmt == gg::kFmtMXFP4 ? !read_mx(l0, e, sb + (size_t) i * c.stage_stride)
3421                                                    : !pk.read_at(l0.region_file[(size_t) e], l0.region_off[(size_t) e],
3422                                                                  l0.region_bytes[(size_t) e],
3423                                                                  sb + (size_t) i * c.stage_stride))
3424                        bad.store(true);
3425                });
3426                if (bad.load()) {
3427                    err = "reading layer " + std::to_string(l0.il) + "'s experts from the model's files failed";
3428                    return false;
3429                }
3430            }
3431            for (int i = 0; i < bt.n; ++i) {
3432                uint8_t* dst = c.ring + ((size_t) half * (c.ring_n / P) + i) * c.ring_stride;
3433                if (!stream_expert(l0, mi, l0.host_list[(size_t) (bt.j0 + i)], dst, c.cs, err,
3434                                   sb != nullptr ? sb + (size_t) i * c.stage_stride : nullptr))
3435                    return false;
3436                c.stream_bytes += (double) unit(member(l0, mi));
3437            }
3438            CK(cudaEventRecord(c.filled[half], c.cs));
3439            ++S.cp;
3440            S.done.store(S.cp, std::memory_order_relaxed);
3441        }
3442        return true;
3443    }
3444
3445    // ---- the flow (see Chunk)
3446    // Windows (WDDM: HIP's runtime and CUDA's driver alike) submits queued work only when the host waits on the GPU:
3447    // the flow's copies and the compute it queued between its waits are submitted at once (win_submit); elsewhere
3448    // nothing.  (CUDA too since #303: two RTX 3080s hung before the first layer, one GPU spinning on the other's flow)
3449    static void kick(cudaStream_t s) { win_submit(s); }
3450    size_t flow_region(int r) const {   // a part's room in a staging slot (read from its offset rounded down)
3451        return ((flow_part[r] + os::kDirectAlign - 1) & ~(size_t) (os::kDirectAlign - 1)) + os::kDirectAlign;
3452    }
3453    size_t flow_stride() const { return flow_region(0) + flow_region(1) + flow_region(2); }
3454    static Chunk::Item& fit(Chunk& c, size_t i) { return c.items[i - c.base]; }
3455    // what member m of l's group reads of matrix r of an expert: gate / up its rows [m n_ff / nm, ..) - one run, from
3456    // this offset in the matrix, this long; the down the whole matrix (its part, the blocks [m n_ff / nm / 32, ..) of
3457    // every row, is DMA'd out of it row by row); alone (nm 1) every matrix whole
3458    size_t mx_read_off(const Layer& l, int m, int r) const {
3459        return r < 2 && l.nm > 1 ? (size_t) m * (size_t) (g.ff / l.nm) * gg::type_row_bytes(gg::expert_type(l.lay, r), g.dim)
3460                                 : 0;
3461    }
3462    size_t mx_read_len(const Layer& l, int r) const {
3463        return r < 2 && l.nm > 1 ? (size_t) (g.ff / l.nm) * gg::type_row_bytes(gg::expert_type(l.lay, r), g.dim)
3464                                 : mx_part_bytes(l, r);
3465    }
3466    // the device's member index in L0's group (0 alone)
3467    int flow_mi(const Chunk& c, const Layer& L0) const {
3468        for (int m = 0; m < L0.nm; ++m)
3469            if (member(L0, m).dev == c.dev) return m;
3470        return 0;
3471    }
3472    void flow_push(Chunk& c, const Layer& l, int mi, int k, int e, int v) {
3473        c.items.emplace_back();
3474        Chunk::Item& it = c.items.back();
3475        it.il = l.il;
3476        it.mi = mi;
3477        it.k = k;
3478        it.e = e;
3479        it.v = v;
3480        bool in_ram = !l.ram.empty() && l.ram[(size_t) e] >= 0;
3481        int store_slot = -1;   // store matrices are copied into staging without a file read
3482        if (!in_ram && store && l.nm == 1) {
3483            const int ss = store->find(l.il, e);
3484            if (ss >= 0) {
3485                store_slot = ss;
3486                for (int r = 0; r < 3; ++r) it.store_src[r] = store->mat(ss, r);
3487                in_ram = true;
3488            }
3489        }
3490        if (in_ram && ram_pinned && store_slot < 0) {   // (DMA'd from where it lies)
3491            const uint8_t* p = ram_slots[(size_t) l.ram[(size_t) e]];
3492            for (int r = 0; r < 3; ++r) it.src[r] = p + l.lay.trellis[r] + mx_read_off(l, mi, r);
3493            ++c.it_ram;
3494            return;
3495        }
3496        if (in_ram && store_slot < 0)   // copied into staging by io, then DMA'd
3497            it.ram = copy_mode ? ram_part[(size_t) l.ram[(size_t) e]][0] : ram_slots[(size_t) l.ram[(size_t) e]];
3498        bool hit = false;
3499        if (!in_ram && c.lc != nullptr && l.nm == 1) {   // layer-major: from the layer cache, or kept for the chunks after
3500            const size_t i = c.base + c.items.size() - 1, stride = (l.blob + 63) & ~(size_t) 63;
3501            if (c.lc_il != l.il) {   // (a layer's first item: the slots the layer before used are its own again
3502                c.lc_il = l.il;      // once that layer's items are all read - `after` below)
3503                c.lc_used = 0;
3504                c.lc_n = (int) std::min<size_t>(c.lc_of.size(), c.lc_bytes / stride);
3505                c.lc_first = i;
3506                std::fill(c.lc_of.begin(), c.lc_of.end(), -1);
3507            }
3508            const int j = c.lc_of[(size_t) e];
3509            if (j >= 0) {   // (copied into staging by io once its reader is done, then DMA'd)
3510                it.ram = c.lc + (size_t) j * stride;
3511                it.after = c.lc_writer[(size_t) j];
3512                hit = true;
3513            } else if (k + 1 < (int) c.fl_T.size() && c.lc_used < c.lc_n) {   // (a later chunk may pick it)
3514                const int jn = c.lc_used++;
3515                c.lc_of[(size_t) e] = jn;
3516                c.lc_writer[(size_t) jn] = (int64_t) i;
3517                it.keep = c.lc + (size_t) jn * stride;
3518                it.after = (int64_t) c.lc_first - 1;
3519            }
3520        }
3521        it.stage = (int) (c.n_file++ % (uint64_t) c.S);
3522        uint8_t* sb = c.stage + (size_t) it.stage * c.stage_stride;
3523        for (int r = 0; r < 3; ++r) {
3524            const uint64_t off = l.mx_off[r] + (uint64_t) e * l.mx_stride[r] + mx_read_off(l, mi, r);
3525            it.src[r] = sb + (in_ram || hit ? 0 : off % os::kDirectAlign);
3526            sb += flow_region(r);
3527        }
3528        it.left.store(in_ram && copy_mode && store_slot < 0 ? 3 * NH : 3, std::memory_order_relaxed);
3529        ++(in_ram ? c.it_ram : hit ? c.it_lc : c.it_file);
3530    }
3531    // the likely experts of (chunk k, layer il) for T tokens, first in its stream: the CPU lane's experts whose chance
3532    // to be picked at least once, 1 - (1 - share)^(picks), is at least DS4_SPEC_Q (0.9: the reads are what takes the
3533    // time, an unpicked one costs a whole read, and the routing is known a few ms after the layer before is done -
3534    // early reads pay where a chunk's long attention keeps the disk otherwise idle, and there nearly every expert is
3535    // that likely), likeliest first, at most what the staging and the ring hold (no more can be read before the layer
3536    // routes); the layer's virtual slots put them first, then its other CPU-lane experts in index order (the order the
3537    // rest of its picks are streamed in)
3538    // (a tensor-parallel group's members each decide their own stream and virtual slots - the same, from the same
3539    // profile and the same routing - and each reads only its part of every expert)
3540    void flow_spec(Chunk& c, int k, int il, int T) {
3541        static const double spec_q = std::getenv("DS4_SPEC_Q") ? std::atof(std::getenv("DS4_SPEC_Q")) : 0.9;
3542        Layer& l = L[(size_t) il];
3543        const int mi = flow_mi(c, l);
3544        int* vs = member(l, mi).vs_pin;
3545        c.spec_k = k;
3546        c.spec_il = il;
3547        c.spec_begin = c.base + c.items.size();
3548        const uint32_t* pr = prof.data() + (size_t) il * g.n_exp;
3549        double sum = 0;
3550        for (int e = 0; e < l.n_exp; ++e) sum += pr[e];
3551        std::vector<std::pair<double, int>> cand;
3552        const double picks = (double) l.k_exp * T;
3553        // (early reads only while they hit: once a run's likely ones went unpicked more often than DS4_SPEC_WASTE
3554        // (0.2) of the time, the rest of the run reads only what the routing picked - an unpicked one costs a whole
3555        // read, and how well the profile guesses depends on the PC's history and the prompt: V100, 64 tokens - 376
3556        // of 921 likely ones unpicked, 7 GB of 84 read for nothing; Radeon 8065S, 128 and 512 tokens - 44 of 945 and
3557        // 21 of 1568, the early reads 9-12% faster there)
3558        // (DS4_SPEC_WASTE_MIN=N: DS4_SPEC_WASTE only for chunks of N rows or more, 0.2 below - a 512-token turn with
3559        //  waste 1 read 3811 of 7880 likely ones for nothing, 68 GB against 36)
3560        static const double waste_set = std::getenv("DS4_SPEC_WASTE") ? std::atof(std::getenv("DS4_SPEC_WASTE")) : 0.2;
3561        static const int waste_min = std::getenv("DS4_SPEC_WASTE_MIN") ? std::atoi(std::getenv("DS4_SPEC_WASTE_MIN")) : 0;
3562        const double waste = T >= waste_min ? waste_set : 0.2;
3563        const bool early = c.it_spec < 2u * (uint64_t) c.ring_n || (double) c.it_spec_unused <= waste * (double) c.it_spec;
3564        for (int e : l.host_list) {
3565            if (!early) break;
3566            const double p = sum > 0 ? pr[e] / sum : 0.0;
3567            const double q = p >= 1.0 ? 1.0 : 1.0 - std::exp(picks * std::log1p(-p));
3568            if (q >= spec_q && spec_q <= 1.0) cand.push_back({q, e});
3569        }
3570        std::stable_sort(cand.begin(), cand.end(), [](const std::pair<double, int>& a, const std::pair<double, int>& b) {
3571            return a.first > b.first;
3572        });
3573        if (cand.size() > (size_t) (c.S + c.ring_n)) cand.resize((size_t) (c.S + c.ring_n));
3574        std::vector<char> is((size_t) l.n_exp, 0);
3575        int j = 0;
3576        for (const auto& x : cand) {
3577            vs[x.second] = l.n_slots + j++;
3578            is[(size_t) x.second] = 1;
3579        }
3580        for (int e : l.host_list)
3581            if (!is[(size_t) e]) vs[e] = l.n_slots + j++;
3582        for (const auto& x : cand) flow_push(c, l, mi, k, x.second, vs[x.second]);
3583        c.n_spec = (int) cand.size();
3584        c.it_spec += cand.size();
3585    }
3586    // (chunk k, layer il) routed (bounds b by virtual slot): the rest of its picks after its likely ones
3587    void flow_rest(Chunk& c, int k, int il, const std::vector<int>& b) {
3588        const Layer& l = L[(size_t) il];
3589        const int mi = flow_mi(c, l);
3590        const int* vs = member(l, mi).vs_pin;
3591        for (int v = 0; v < l.n_slots; ++v) c.it_vram += b[(size_t) v + 1] > b[(size_t) v];
3592        for (size_t i = c.spec_begin; i < c.spec_begin + (size_t) c.n_spec; ++i) {
3593            const int v = fit(c, i).v;
3594            if (b[(size_t) v + 1] == b[(size_t) v]) ++c.it_spec_unused;
3595        }
3596        for (int e : l.host_list) {   // (index order: their virtual slots ascending)
3597            const int v = vs[e];
3598            if (v >= l.n_slots + c.n_spec && b[(size_t) v + 1] > b[(size_t) v]) flow_push(c, l, mi, k, e, v);
3599        }
3600    }
3601    // the next (chunk, layer) of the device after (k, il) in the run's order that streams experts (false: none) - a
3602    // long prompt's skip leaves out its early chunks' layers from Run::yoco on (kv_only there: no experts)
3603    bool flow_next(const Chunk& c, int k, int il, int& k2, int& il2) const {
3604        while (flow_next1(c, k, il, k2, il2)) {
3605            if (c.fl_yoco < 0 || k2 >= c.fl_cut_k || il2 < c.fl_yoco) return true;
3606            k = k2;
3607            il = il2;
3608        }
3609        return false;
3610    }
3611    // the rows chunk k runs layer il on (a long prompt's skip: the cut chunk's from cut_r on, from the yoco layer on)
3612    static int fl_rows(const Chunk& c, int k, int il) {
3613        const int T = c.fl_T[(size_t) k];
3614        return c.fl_yoco >= 0 && k == c.fl_cut_k && il >= c.fl_yoco ? T - c.fl_cut_r : T;
3615    }
3616    bool flow_next1(const Chunk& c, int k, int il, int& k2, int& il2) const {
3617        const auto it = std::find(c.fl_layers.begin(), c.fl_layers.end(), il);
3618        const size_t i = (size_t) (it - c.fl_layers.begin());
3619        if (c.lm) {   // (layer-major: the layer's next chunk, then the next layer's first)
3620            if (k + 1 < (int) c.fl_T.size()) {
3621                k2 = k + 1;
3622                il2 = il;
3623                return true;
3624            }
3625            if (i + 1 >= c.fl_layers.size()) return false;
3626            k2 = 0;
3627            il2 = c.fl_layers[i + 1];
3628            return true;
3629        }
3630        if (i + 1 < c.fl_layers.size()) {
3631            k2 = k;
3632            il2 = c.fl_layers[i + 1];
3633            return true;
3634        }
3635        if (k + 1 < (int) c.fl_T.size() && !c.fl_layers.empty()) {
3636            k2 = k + 1;
3637            il2 = c.fl_layers[0];
3638            return true;
3639        }
3640        return false;
3641    }
3642    // the reads (in order, each into its staging slot once that slot's last DMA is done) and the DMAs (in order, each
3643    // into its ring slot once that slot's last use is queued: the copy stream waits for it) as far as they can go now
3644    bool flow_pump(Chunk& c, std::string& err) {
3645        const size_t end = c.base + c.items.size();
3646        IoQueue::Job jobs[6];
3647        while (c.n_read < end) {
3648            Chunk::Item& it = fit(c, c.n_read);
3649            if (it.after >= 0) {   // layer-major: a slot's expert copied out of it once its reader is done; a slot
3650                // written again once the layer before's items are all read (none still copies out of it)
3651                bool wait = false;
3652                if (it.keep == nullptr)
3653                    wait = (size_t) it.after >= c.base && fit(c, (size_t) it.after).left.load(std::memory_order_acquire) != 0;
3654                else {
3655                    while (c.lc_chk < c.n_read &&
3656                           (c.lc_chk < c.base || fit(c, c.lc_chk).left.load(std::memory_order_acquire) == 0))
3657                        ++c.lc_chk;
3658                    wait = c.lc_chk <= (size_t) it.after;
3659                }
3660                if (wait) break;
3661            }
3662            if (it.stage >= 0) {
3663                const int64_t prev = c.stage_item[(size_t) it.stage];
3664                if (prev >= 0) {
3665                    if ((size_t) prev >= c.n_dma) break;
3666                    const cudaError_t q = cudaEventQuery(c.stage_ev[(size_t) it.stage]);
3667                    if (q == cudaErrorNotReady) break;
3668                    CK(q);
3669                }
3670                c.stage_item[(size_t) it.stage] = (int64_t) c.n_read;
3671                const Layer& l = L[(size_t) it.il];
3672                uint8_t* sb = c.stage + (size_t) it.stage * c.stage_stride;
3673                const int cs = copy_mode && it.ram != nullptr ? l.ram[(size_t) it.e] : -1;   // (a copy's slot)
3674                int nj = 0;
3675                for (int r = 0; r < 3; ++r) {
3676                    if (cs >= 0) {   // a copy: each matrix's NH parts of rows, side by side into staging
3677                        const size_t nb = (size_t) (mx_n(r) / NH) * mx_row_b(l, r);
3678                        for (int X = 0; X < NH; ++X) {
3679                            IoQueue::Job& j = jobs[nj++];
3680                            j = IoQueue::Job{};
3681                            j.len = nb;
3682                            j.dst = sb + (size_t) X * nb;
3683                            j.left = &it.left;
3684                            j.bad = &it.bad;
3685                            j.mem = ram_part[(size_t) cs][(size_t) X] + cp_lay[(size_t) l.il][(size_t) r];
3686                        }
3687                        sb += flow_region(r);
3688                        continue;
3689                    }
3690                    IoQueue::Job& j = jobs[nj++];
3691                    const os::fd_t pf = pk.pfds.empty() ? os::kBadFd : pk.pfds[(size_t) l.mx_file[r]];
3692                    j.fd = pf != os::kBadFd ? pf : pk.fds[(size_t) l.mx_file[r]];
3693                    j.dfd = pk.dfds.empty() ? os::kBadFd : pk.dfds[(size_t) l.mx_file[r]];
3694                    j.off = l.mx_off[r] + (uint64_t) it.e * l.mx_stride[r] + mx_read_off(l, it.mi, r);
3695                    j.len = mx_read_len(l, r);
3696                    j.dst = sb;
3697                    j.left = &it.left;
3698                    j.bad = &it.bad;
3699                    j.mem = it.store_src[r] != nullptr ? it.store_src[r] + mx_read_off(l, it.mi, r)
3700                            : it.ram != nullptr ? it.ram + l.lay.trellis[r] + mx_read_off(l, it.mi, r) : nullptr;
3701                    j.map = pk.at(l.mx_file[r], j.off);
3702                    j.keep = it.keep != nullptr ? it.keep + l.lay.trellis[r] : nullptr;
3703                    sb += flow_region(r);
3704                }
3705                c.io->push(jobs, nj);
3706            }
3707            ++c.n_read;
3708        }
3709        const size_t R = (size_t) c.ring_n, dma0 = c.n_dma;
3710        struct Kick {   // (every way out: what was queued is submitted)
3711            cudaStream_t s;
3712            const size_t &a, b;
3713            ~Kick() {
3714                if (a != b) kick(s);
3715            }
3716        } kq{c.cs, c.n_dma, dma0};
3717        while (c.n_dma < c.n_read && c.n_dma < c.n_comp + R) {
3718            Chunk::Item& it = fit(c, c.n_dma);
3719            if (it.left.load(std::memory_order_acquire) != 0) break;
3720            if (it.bad.load(std::memory_order_acquire)) {
3721                err = "reading layer " + std::to_string(it.il) + " expert " + std::to_string(it.e) +
3722                      " from the model's files failed";
3723                return false;
3724            }
3725            const size_t r = c.n_dma % R;
3726            if (c.n_dma >= R) CK(cudaStreamWaitEvent(c.cs, c.ring_free[r], 0));
3727            const Layer& l = L[(size_t) it.il];
3728            uint8_t* dst = c.ring + r * c.ring_stride;
3729            const x3::ExpertLayout& lay = l.nm > 1 ? l.hlay : l.lay;
3730            for (int p = 0; p < 2; ++p)
3731                CK(cudaMemcpyAsync(dst + lay.trellis[p], it.src[p], mx_read_len(l, p), cudaMemcpyHostToDevice, c.cs));
3732            if (l.nm > 1) {   // (the down's part: in each of its rows the member's blocks)
3733                const int t2 = gg::expert_type(l.lay, 2);
3734                const size_t dr = gg::type_row_bytes(t2, g.ff), dh = gg::type_row_bytes(t2, g.ff / l.nm);
3735                CK(cudaMemcpy2DAsync(dst + lay.trellis[2], dh, it.src[2] + (size_t) it.mi * dh, dr, dh, (size_t) g.dim,
3736                                     cudaMemcpyHostToDevice, c.cs));
3737            } else
3738                CK(cudaMemcpyAsync(dst + lay.trellis[2], it.src[2], mx_part_bytes(l, 2), cudaMemcpyHostToDevice, c.cs));
3739            CK(cudaEventRecord(c.ring_fill[r], c.cs));
3740            if (it.stage >= 0) CK(cudaEventRecord(c.stage_ev[(size_t) it.stage], c.cs));
3741            c.stream_bytes += (double) unit(l);
3742            ++c.n_dma;
3743        }
3744        return true;
3745    }
3746    // layer L0 of chunk k routed (bounds b, the device's copy d_bounds): its streamed experts as they land, the VRAM
3747    // ones in shares between them (the device works while the reads run)
3748    bool flow_layer(Dev& d, Chunk& c, Layer& L0, int mi, int k, int T, const std::vector<int>& b, std::string& err) {
3749        cudaStream_t s = d.st;
3750        const uint8_t* vbase = member(L0, mi).vram_base;   // (a member's: its part of each VRAM expert, L0's slots)
3751        if (c.spec_k != k || c.spec_il != L0.il) {
3752            err = "the prompt path's expert stream is out of step (layer " + std::to_string(L0.il) + ")";
3753            return false;
3754        }
3755        flow_rest(c, k, L0.il, b);
3756        const size_t lb = c.spec_begin, le = c.base + c.items.size(), n_lay = le - lb;
3757        int k2 = 0, il2 = 0;
3758        if (flow_next(c, k, L0.il, k2, il2)) flow_spec(c, k2, il2, fl_rows(c, k2, il2));
3759        const size_t R = (size_t) c.ring_n, bmax = std::max<size_t>(1, R / 2);
3760        int v_done = 0;
3761        while (c.n_comp < le) {
3762            // a batch's bounds are fixed by the stream alone (bmax items, never across the ring's end), never by what
3763            // has landed: the experts' outputs are summed batch after batch (the VRAM ones' shares between them), so
3764            // the sums come out the same on every run whatever the reads' timing
3765            const size_t i0 = c.n_comp, i1 = std::min({le, i0 + bmax, (i0 / R + 1) * R});
3766            if (!flow_pump(c, err)) return false;
3767            if (c.n_dma < i1) {   // not all of the batch landed: wait for a read, or for a staging slot's copy
3768                const double tw = now_ms();
3769                kick(s);
3770                if (c.n_read > c.n_dma) c.io->wait_any(500);
3771                else {
3772                    const Chunk::Item& it = fit(c, c.n_read);
3773                    if (it.stage >= 0) CK(cudaEventSynchronize(c.stage_ev[(size_t) it.stage]));
3774                }
3775                c.wait_ms += now_ms() - tw;
3776                continue;
3777            }
3778            const int n = (int) (i1 - i0);
3779            int* bc = c.bc_pin + (size_t) (c.n_batch % (uint64_t) c.bc_n) * c.bc_w;
3780            int* bcd = c.bc_dev + (size_t) (c.n_batch % (uint64_t) c.bc_n) * c.bc_w;
3781            ++c.n_batch;
3782            // (the items' virtual slots ascend and the slots between them have no rows: their bounds side by side)
3783            for (int m = 0; m < n; ++m) bc[m] = b[(size_t) fit(c, i0 + (size_t) m).v];
3784            bc[n] = b[(size_t) fit(c, i1 - 1).v + 1];
3785            if (bc[n] > bc[0]) {
3786                CK(cudaStreamWaitEvent(s, c.ring_fill[(i1 - 1) % R], 0));
3787                CK(cudaMemcpyAsync(bcd, bc, (size_t) (n + 1) * 4, cudaMemcpyHostToDevice, s));
3788                if (!run_set(d, c, L0, c.ring + (i0 % R) * c.ring_stride, 0, c.ring_stride, bcd, bc, 0, n, T, err))
3789                    return false;
3790            }
3791            for (size_t i = i0; i < i1; ++i) CK(cudaEventRecord(c.ring_free[i % R], s));
3792            kick(s);
3793            c.n_comp = i1;
3794            if (!flow_pump(c, err)) return false;
3795            const int v_to = (int) ((int64_t) L0.n_slots * (int64_t) (c.n_comp - lb) / (int64_t) std::max<size_t>(1, n_lay));
3796            if (!run_set(d, c, L0, vbase, 0, unit(L0), c.bounds, b.data(), v_done, v_to, T, err)) return false;
3797            v_done = v_to;
3798        }
3799        if (!run_set(d, c, L0, vbase, 0, unit(L0), c.bounds, b.data(), v_done, L0.n_slots, T, err)) return false;
3800        while (c.base < c.n_comp && c.items.size() > 4096) {   // (done with: read, copied and used)
3801            c.items.pop_front();
3802            ++c.base;
3803        }
3804        return true;
3805    }
3806
3807    // the experts [i0, i1) of a sorted set (blobs at wbase + i * stride; bounds b on the host, d_bounds on the device)
3808    // over the chunk's rows, in pieces of at most C rows, each added into acc in pick order
3809    bool run_set(Dev& d, Chunk& c, const Layer& l, const uint8_t* wbase, int wb0, size_t stride, const int* d_bounds,
3810                 const int* b, int i0, int i1, int T, std::string& err) {
3811        const int D = g.dim, FF = l.ffn;
3812        while (i0 < i1) {
3813            int j = i0 + 1;
3814            while (j < i1 && b[j + 1] - b[i0] <= c.C) ++j;
3815            const int a = b[i0], nrows = b[j] - a;
3816            int max_rows = 0;
3817            for (int i = i0; i < j; ++i) max_rows = std::max(max_rows, b[i + 1] - b[i]);
3818            if (nrows > 0) {
3819                x3::SetArgs sa;
3820                sa.wbase = wbase + (size_t) (i0 - wb0) * stride;   // (wbase: set member wb0's blob)
3821                sa.stride = stride;
3822                sa.lay = l.nm > 1 ? l.hlay : l.lay;
3823                sa.n_exp = j - i0;
3824                sa.bounds = d_bounds + i0;
3825                sa.row0 = a;
3826                sa.max_rows = max_rows;
3827                sa.n_embd = D;
3828                sa.n_ff = FF;
3829                sa.limit = g.lim;
3830                EkMark ek{};
3831                const bool ekp = prof_chunk;
3832                if (ekp) {
3833                    std::lock_guard<std::mutex> lk(prof_mu);
3834                    ek.e0 = ek_ev();
3835                    ek.e1 = ek_ev();
3836                    ek.e2 = ek_ev();
3837                    ek.tg = gg::expert_type(sa.lay, 0);
3838                    ek.td = gg::expert_type(sa.lay, 2);
3839                    ek.nrows = nrows;
3840                    ek.nexp = j - i0;
3841                    ek.maxrows = max_rows;
3842                    ek.ff = FF;
3843                    cudaGetDevice(&ek.dev);
3844                    cudaEventRecord(ek.e0, d.st);
3845                }
3846                if (sa.lay.fmt == gg::kFmtMXFP4) {
3847                    gg::set_gate_up(sa, c.x, D, c.row_tok + a, c.h16, FF, d.st);
3848                    if (ekp) cudaEventRecord(ek.e1, d.st);
3849                    gg::set_down(sa, c.h16, FF, c.y, D, d.st);
3850                } else {
3851                    x3::set_gate_up(sa, c.x, D, c.row_tok + a, c.h16, FF, d.st);
3852                    if (ekp) cudaEventRecord(ek.e1, d.st);
3853                    x3::set_down(sa, c.h16, FF, c.y, D, d.st);
3854                }
3855                if (ekp) {
3856                    cudaEventRecord(ek.e2, d.st);
3857                    std::lock_guard<std::mutex> lk(prof_mu);
3858                    ek_marks.push_back(ek);
3859                }
3860                if (dump_y != nullptr && (dump_y_layer < 0 || l.il == dump_y_layer)) {
3861                    std::vector<int> bb(b + i0, b + j + 1);
3862                    std::vector<uint16_t> hv((size_t) nrows * FF);
3863                    std::vector<float> yv((size_t) nrows * D);
3864                    CK(cudaStreamSynchronize(d.st));
3865                    CK(cudaMemcpy(hv.data(), c.h16, hv.size() * 2, cudaMemcpyDeviceToHost));
3866                    CK(cudaMemcpy(yv.data(), c.y, yv.size() * 4, cudaMemcpyDeviceToHost));
3867                    std::lock_guard<std::mutex> lk(dump_mu);
3868                    const int64_t hdr[6] = {l.il, a, nrows, j - i0, wbase == c.ring || (wbase > c.ring &&
3869                                            wbase < c.ring + (size_t) c.ring_n * c.ring_stride) ? 1 : 0, max_rows};
3870                    std::fwrite(hdr, 8, 6, dump_y);
3871                    std::fwrite(bb.data(), 4, bb.size(), dump_y);
3872                    std::fwrite(hv.data(), 2, hv.size(), dump_y);
3873                    std::fwrite(yv.data(), 4, yv.size(), dump_y);
3874                    std::fflush(dump_y);
3875                }
3876                moe_combine(c.acc, c.y, c.pos, c.rw, T, l.k_exp, a, a + nrows, D, d.st);
3877            }
3878            i0 = j;
3879        }
3880        (void) err;
3881        return true;
3882    }
3883
3884    bool load_dense(int di, std::string& err) {
3885        Dev& d = devs[(size_t) di];
3886        cudaSetDevice(d.id);
3887        size_t* acct = &d.weights;
3888        for (Layer& l0 : L)
3889          for (int mi = 0; mi < l0.nm; ++mi) {
3890            Layer& l = member(l0, mi);
3891            if (l.dev != di) continue;
3892            // (a group's member: its share of the heads (wq_b columns, the sinks), of wo_a's groups and wo_b's rows,
3893            // of the shared expert's FFN; the rest whole)
3894            const int nm = l0.nm, na = g.heads / std::max(1, l.ahn), ha = l.ah0 / std::max(1, l.ahn);
3895            const std::string& P = l.name;
3896            const std::string A = P + "attn.";
3897            bool ok = mat(d, A + "wq_a", l.wq_a, err, acct) &&
3898                      (l.ahn == 0 || mat(d, A + "wq_b", l.wq_b, err, acct, ha, na, true)) &&
3899                      mat(d, A + "wkv", l.wkv, err, acct) &&
3900                      (l.ahn == 0 || mat(d, A + "wo_b", l.wo_b, err, acct, ha, na, false)) &&
3901                      f32(d, A + "q_norm.weight", l.q_norm, err, acct, (size_t) g.q_lora) &&
3902                      f32(d, A + "kv_norm.weight", l.kv_norm, err, acct, (size_t) g.hd) &&
3903                      f32(d, A + "attn_sink", l.sink, err, acct, (size_t) g.heads) &&
3904                      f32(d, P + "attn_norm.weight", l.attn_norm, err, acct, (size_t) g.dim) &&
3905                      f32(d, P + "ffn_norm.weight", l.ffn_norm, err, acct, (size_t) g.dim) &&
3906                      f32(d, P + "hc_attn_fn", l.hca_fn, err, acct) && f32(d, P + "hc_attn_scale", l.hca_scale, err, acct) &&
3907                      f32(d, P + "hc_attn_base", l.hca_base, err, acct) && f32(d, P + "hc_ffn_fn", l.hcf_fn, err, acct) &&
3908                      f32(d, P + "hc_ffn_scale", l.hcf_scale, err, acct) &&
3909                      f32(d, P + "hc_ffn_base", l.hcf_base, err, acct) &&
3910                      f32(d, P + "ffn.gate.weight", l.gate_w, err, acct, (size_t) l.n_exp * g.dim) &&
3911                      f32(d, P + "ffn.gate.bias", l.gate_bias, err, acct, (size_t) l.n_exp) &&
3912                      (l.mtp || img_tok < 0 || pk.get(P + "ffn.gate.bias_vl") == nullptr ||
3913                       f32(d, P + "ffn.gate.bias_vl", l.gate_bias_vl, err, acct, (size_t) l.n_exp)) &&
3914                      mat(d, P + "ffn.shared_experts.w1", l.s1, err, acct, mi, nm, true, l.il % nm) &&
3915                      mat(d, P + "ffn.shared_experts.w2", l.s2, err, acct, mi, nm, false, l.il % nm) &&
3916                      mat(d, P + "ffn.shared_experts.w3", l.s3, err, acct, mi, nm, true, l.il % nm);
3917            if (!ok) return false;
3918            l.sink += (size_t) l.ah0;
3919            for (int gi = 0; gi < l.ogn; ++gi)
3920                if (!mat(d, A + "wo_a.slice." + std::to_string(l.og0 + gi), l.wo_a[gi], err, acct)) return false;
3921            if (l.kv_src) {
3922                const std::string C = A + "compressor.";
3923                if (!mat(d, C + "wkv", l.c_wkv, err, acct) || !f32(d, C + "norm.weight", l.c_norm, err, acct)) return false;
3924                if (l.ratio > 1 && !mat(d, C + "wgate", l.c_wgate, err, acct)) return false;
3925                if (l.ratio > 1 && (!dalloc(d, l.c_kv, (size_t) l.ratio * g.hd, err) ||
3926                                    !dalloc(d, l.c_score, (size_t) l.ratio * g.hd, err)))
3927                    return false;
3928            }
3929            if (l.ix_src) {
3930                const std::string I = A + "indexer.";
3931                if (!mat(d, I + "wq_b", l.i_wq_b, err, acct) || !f16raw(d, I + "weights_proj.weight", l.i_wproj, err, acct))
3932                    return false;
3933                if (l.owns_k && (!mat(d, I + "wk", l.i_wk, err, acct) || !f32(d, I + "k_norm.weight", l.ik_norm, err, acct)))
3934                    return false;
3935            }
3936            if (l.eg >= 0) {
3937                if (!mat(d, P + "engram.wkv", l.eg_wkv, err, acct)) return false;
3938                if (pk.get(P + "engram.gate.weight") != nullptr) {   // a GGUF: q_weight * k_weight, folded already
3939                    if (!f32(d, P + "engram.gate.weight", l.eg_w, err, acct, (size_t) g.hc * g.dim)) return false;
3940                } else {
3941                    float *qw = nullptr, *kw = nullptr;
3942                    if (!f32(d, P + "engram.q_weight", qw, err, acct) || !f32(d, P + "engram.k_weight", kw, err, acct))
3943                        return false;
3944                    std::vector<float> a((size_t) g.hc * g.dim), b(a.size());
3945                    CK(cudaMemcpy(a.data(), qw, a.size() * 4, cudaMemcpyDeviceToHost));
3946                    CK(cudaMemcpy(b.data(), kw, b.size() * 4, cudaMemcpyDeviceToHost));
3947                    for (size_t i = 0; i < a.size(); ++i) a[i] *= b[i];   // only ever used as a product
3948                    CK(cudaMemcpy(qw, a.data(), a.size() * 4, cudaMemcpyHostToDevice));
3949                    l.eg_w = qw;
3950                }
3951            }
3952            if (!dalloc(d, l.win, (size_t) g.win * win_rb(), err, &d.caches)) return false;
3953            if ((g.n_mtp > 0 || o.spec_buffers) && !l.mtp) {
3954                if (!dalloc(d, l.ring_bak, (size_t) kWin * win_rb(), err)) return false;
3955                if (l.kv_src && l.ratio > 1 && (!dalloc(d, l.c_snap, (size_t) 2 * l.ratio * g.hd, err) ||
3956                                                !dalloc(d, l.c_rows, (size_t) 2 * kWin * g.hd, err)))
3957                    return false;
3958            }
3959            if (!dalloc(d, l.vram_tab, (size_t) l.n_exp, err, acct)) return false;
3960          }
3961        if (d.grp == devs[(size_t) head_dev].grp) {   // the head: each member of its group a share of the columns
3962            const int hn = head_nm();
3963            if (!mat(d, "head", d.head, err, acct, d.mi, hn, true) || !f32(d, "norm.weight", d.norm_w, err, acct, (size_t) g.dim))
3964                return false;
3965            if (g.n_mtp > 0 && !f32(d, "mtp." + std::to_string(g.n_mtp - 1) + ".norm.weight", d.d_norm, err, acct, (size_t) g.dim))
3966                return false;
3967            if (!dalloc(d, d.logits_part, (size_t) kWin * ((g.vocab / 128 + hn - 1) / hn * 128), err)) return false;
3968            if (g.n_mtp > 0 && hn > 1) {   // the markov steps over the group (mk_split): this member's rows of the head
3969                const Tensor* th = pk.get("mtp." + std::to_string(g.n_mtp - 1) + ".markov_head.head.weight");
3970                const int R = g.d_rank;
3971                head_cols(hn, d.mi, d.mk_v0, d.mk_vn);   // (its share of the head's columns: the same rows)
3972                // F16 as the pack holds it, or a GGUF drafter's BF16 rounded to F16 as f16raw rounds d_mk_head (the same
3973                // values as the lead's whole rows); another type: no mk_split (the lead's whole rows)
3974                if (th != nullptr && (th->dtype == "F16" || th->dtype == "BF16") && th->bytes == (uint64_t) g.vocab * R * 2) {
3975                    std::vector<uint16_t> rows((size_t) d.mk_vn * R);
3976                    if (!pk.read_at(th->file, th->off + (uint64_t) d.mk_v0 * R * 2, rows.size() * 2, rows.data())) {
3977                        err = "the markov head: read failed";
3978                        return false;
3979                    }
3980                    if (th->dtype == "BF16")
3981                        for (uint16_t& h : rows) h = strata::kernels::f16_from_f32(bf16_to_f32(h));
3982                    if (!dalloc(d, d.mk_share, rows.size(), err, acct) || !dalloc(d, d.mk_erow, (size_t) R, err) ||
3983                        !dalloc(d, d.mk_ints, (size_t) kWin + 2, err))
3984                        return false;
3985                    CK(cudaMemcpy(d.mk_share, rows.data(), rows.size() * 2, cudaMemcpyHostToDevice));
3986                }
3987            }
3988        }
3989        if (di == head_dev) {
3990            head = d.head;
3991            norm_w = d.norm_w;
3992            d_norm = d.d_norm;
3993            if (g.n_mtp > 0) {
3994                const std::string Z = "mtp." + std::to_string(g.n_mtp - 1) + ".";
3995                if (!f32(d, Z + "confidence_head.proj.weight", d_conf, err, acct, (size_t) (g.dim + g.d_rank)))
3996                    return false;
3997                const Tensor* te = pk.get(Z + "markov_head.embed.weight");
3998                const Tensor* th = pk.get(Z + "markov_head.head.weight");
3999                if (te == nullptr || th == nullptr || te->dtype != "BF16" || (th->dtype != "F16" && th->dtype != "BF16")) {
4000                    err = Z + "markov_head: not the BF16 embed and F16 / BF16 head expected";
4001                    return false;
4002                }
4003                if (!dalloc(d, d_mk_embed, te->bytes / 2, err, acct) || !upload(d, *te, d_mk_embed, err) ||
4004                    !f16raw(d, Z + "markov_head.head.weight", d_mk_head, err, acct))
4005                    return false;
4006            }
4007        }
4008        if (g.n_mtp > 0 && di == d_dev) {
4009            if (!mat(d, "mtp.0.main_proj", d_main_proj, err, acct) ||
4010                !f32(d, "mtp.0.main_norm.weight", d_main_norm, err, acct, (size_t) g.dim))
4011                return false;
4012        }
4013        return true;
4014    }
4015
4016    void set_vm(Layer& l, int e, int slot) {
4017        uint8_t* b = l.vram_base + (size_t) slot * l.blob;
4018        if (l.lay.fmt == gg::kFmtMXFP4) {
4019            for (int r = 0; r < 3; ++r) {
4020                x3::Mat& m = l.vm[(size_t) e][(size_t) r];
4021                m = x3::Mat{};
4022                m.K = gg::expert_type(l.lay, r);   // (a low-bit type: its GEMV, ds4_iq's)
4023                m.fmt = m.K == gg::kTypeMXFP4 ? gg::kFmtMXFP4 : gg::kFmtGG;
4024                m.raw = b + l.lay.trellis[r];
4025                m.k = r < 2 ? g.dim : g.ff;
4026                m.n = r < 2 ? g.ff : g.dim;
4027            }
4028            return;
4029        }
4030        for (int r = 0; r < 3; ++r) {
4031            x3::Mat& m = l.vm[(size_t) e][(size_t) r];
4032            m.trellis = (const uint32_t*) (b + l.lay.trellis[r]);
4033            m.suh = (const uint16_t*) (b + l.lay.suh[r]);
4034            m.svh = (const uint16_t*) (b + l.lay.svh[r]);
4035            m.k = r < 2 ? g.dim : g.ff;
4036            m.n = r < 2 ? g.ff : g.dim;
4037            m.K = l.lay.K[r];
4038            m.cb = 2;
4039            m.ld = 0;
4040        }
4041    }
4042    // an expert's VRAM blob -> its CPU-lane part X, and its NH parts -> the blob (the cache's swaps)
4043    void blob_to_part(const Layer& l, const uint8_t* blob, int X, uint8_t* dst) const {
4044        for (int r = 0; r < 3; ++r) {
4045            const size_t tile = (size_t) 32 * l.lay.K[r];
4046            const int k = l.hl.k[r], nt = l.hl.n[r] * NH / 16, nth = l.hl.n[r] / 16;
4047            const uint8_t* tr = blob + l.lay.trellis[r];
4048            for (int sl = 0; sl < k / 16; ++sl)
4049                std::memcpy(dst + l.hl.trellis[r] + (size_t) sl * nth * tile, tr + ((size_t) sl * nt + (size_t) X * nth) * tile,
4050                            (size_t) nth * tile);
4051            std::memcpy(dst + l.hl.suh[r], blob + l.lay.suh[r], (size_t) k * 2);
4052            std::memcpy(dst + l.hl.svh[r], blob + l.lay.svh[r] + (size_t) X * l.hl.n[r] * 2, (size_t) l.hl.n[r] * 2);
4053        }
4054    }
4055    void parts_to_blob(const Layer& l, const std::array<uint8_t*, 4>& parts, uint8_t* blob) const {
4056        for (int r = 0; r < 3; ++r) {
4057            const size_t tile = (size_t) 32 * l.lay.K[r];
4058            const int k = l.hl.k[r], nt = l.hl.n[r] * NH / 16, nth = l.hl.n[r] / 16;
4059            uint8_t* tr = blob + l.lay.trellis[r];
4060            for (int X = 0; X < NH; ++X)
4061                for (int sl = 0; sl < k / 16; ++sl)
4062                    std::memcpy(tr + ((size_t) sl * nt + (size_t) X * nth) * tile,
4063                                parts[(size_t) X] + l.hl.trellis[r] + (size_t) sl * nth * tile, (size_t) nth * tile);
4064            std::memcpy(blob + l.lay.suh[r], parts[0] + l.hl.suh[r], (size_t) k * 2);
4065            for (int X = 0; X < NH; ++X)
4066                std::memcpy(blob + l.lay.svh[r] + (size_t) X * l.hl.n[r] * 2, parts[(size_t) X] + l.hl.svh[r],
4067                            (size_t) l.hl.n[r] * 2);
4068        }
4069    }
4070
4071    // an expert's blob -> member m's part (gate / up columns [ff0, ff0 + ffn), down rows of the same), and back
4072    void blob_to_half(const Layer& l, const uint8_t* blob, int m, uint8_t* dst) const {
4073        if (l.lay.fmt == gg::kFmtMXFP4) return mx_blob_to_half(l, blob, m, dst);
4074        const Layer& x = member(l, m);
4075        const int f0 = x.ff0, fn = x.ffn;
4076        for (int r = 0; r < 2; ++r) {
4077            const size_t tile = (size_t) 32 * l.lay.K[r], nt = (size_t) g.ff / 16, nth = (size_t) fn / 16;
4078            for (size_t sl = 0; sl < (size_t) g.dim / 16; ++sl)
4079                std::memcpy(dst + x.hlay.trellis[r] + sl * nth * tile,
4080                            blob + l.lay.trellis[r] + (sl * nt + (size_t) f0 / 16) * tile, nth * tile);
4081            std::memcpy(dst + x.hlay.suh[r], blob + l.lay.suh[r], (size_t) g.dim * 2);
4082            std::memcpy(dst + x.hlay.svh[r], blob + l.lay.svh[r] + (size_t) f0 * 2, (size_t) fn * 2);
4083        }
4084        const size_t row = (size_t) (g.dim / 16) * 32 * l.lay.K[2];
4085        std::memcpy(dst + x.hlay.trellis[2], blob + l.lay.trellis[2] + (size_t) (f0 / 16) * row, (size_t) (fn / 16) * row);
4086        std::memcpy(dst + x.hlay.suh[2], blob + l.lay.suh[2] + (size_t) f0 * 2, (size_t) fn * 2);
4087        std::memcpy(dst + x.hlay.svh[2], blob + l.lay.svh[2], (size_t) g.dim * 2);
4088    }
4089    void half_to_blob(const Layer& l, const uint8_t* src, int m, uint8_t* blob) const {
4090        if (l.lay.fmt == gg::kFmtMXFP4) return mx_half_to_blob(l, src, m, blob);
4091        const Layer& x = member(l, m);
4092        const int f0 = x.ff0, fn = x.ffn;
4093        for (int r = 0; r < 2; ++r) {
4094            const size_t tile = (size_t) 32 * l.lay.K[r], nt = (size_t) g.ff / 16, nth = (size_t) fn / 16;
4095            for (size_t sl = 0; sl < (size_t) g.dim / 16; ++sl)
4096                std::memcpy(blob + l.lay.trellis[r] + (sl * nt + (size_t) f0 / 16) * tile,
4097                            src + x.hlay.trellis[r] + sl * nth * tile, nth * tile);
4098            if (m == 0) std::memcpy(blob + l.lay.suh[r], src + x.hlay.suh[r], (size_t) g.dim * 2);
4099            std::memcpy(blob + l.lay.svh[r] + (size_t) f0 * 2, src + x.hlay.svh[r], (size_t) fn * 2);
4100        }
4101        const size_t row = (size_t) (g.dim / 16) * 32 * l.lay.K[2];
4102        std::memcpy(blob + l.lay.trellis[2] + (size_t) (f0 / 16) * row, src + x.hlay.trellis[2], (size_t) (fn / 16) * row);
4103        std::memcpy(blob + l.lay.suh[2] + (size_t) f0 * 2, src + x.hlay.suh[2], (size_t) fn * 2);
4104        if (m == 0) std::memcpy(blob + l.lay.svh[2], src + x.hlay.svh[2], (size_t) g.dim * 2);
4105    }
4106
4107    bool place_experts(std::string& err) {
4108        // (Windows, an integrated GPU: what its experts may commit - commit_room - and what that kept off the GPU)
4109        double room = 1e300, kept = 0;
4110        for (const Dev& d : devs)
4111            if (commit_charged(d)) room = commit_room();
4112        const double room0 = room;
4113        // per group: what its tightest member has left (each member holds its part of every VRAM expert of the
4114        // group's layers, its unit bytes a slot - counted at the members' mean: an uneven split's odd blocks go round
4115        // the members layer by layer, so each member's total comes to about the mean's)
4116        auto ucount = [](const Layer& l) {
4117            double s = 0;
4118            for (int m = 0; m < l.nm; ++m) s += (double) unit(member(l, m));
4119            return s / l.nm;
4120        };
4121        for (size_t gi = 0; gi < groups.size(); ++gi) {
4122            double budget = 1e300;
4123            bool charged = false;
4124            for (int m : groups[gi].mem) {
4125                cudaSetDevice(devs[(size_t) m].id);
4126                size_t fr = 0, tot = 0;
4127                CK(cudaMemGetInfo(&fr, &tot));
4128                // (an integrated GPU, Windows: its memory is the system's.  What it allocates after the experts - the long
4129                // prompt's buffers, the GEMM workspaces - spills into RAM when the experts took every byte of the GPU's
4130                // address space, and on a 32K prompt that ran the machine out of RAM.  So the experts leave room for them,
4131                // growing with the context.  DS4_UMA_GPU_RESERVE_GB: that room, tests)
4132                double uma_extra = 0.0;
4133                if (commit_charged(devs[(size_t) m])) {
4134                    uma_extra = (4.0 + 2.0e-4 * std::max(0.0, (double) o.max_context - 16384.0)) * (double) (1ull << 30);
4135                    if (const char* v = std::getenv("DS4_UMA_GPU_RESERVE_GB")) uma_extra = std::atof(v) * (double) (1ull << 30);
4136                }
4137                budget = std::min(budget, std::max(0.0, ((double) fr - (double) ((size_t) o.reserve_mib << 20) - uma_extra)) *
4138                                              o.vram_experts);
4139                charged = charged || commit_charged(devs[(size_t) m]);
4140            }
4141            if (charged && room < 1e300) {   // (each member's slots charged: the group's share of the room)
4142                double all = 0;
4143                for (const Layer& l : L)
4144                    if (l.grp == (int) gi) all += (double) unit(l) * l.n_exp;
4145                const double nm = (double) groups[gi].mem.size(), capped = std::min(budget, room / nm);
4146                kept += std::max(0.0, std::min(budget, all) - std::min(capped, all)) * nm;
4147                budget = capped;
4148                room = std::max(0.0, room - std::min(budget, all) * nm);
4149            }
4150            double budget_t = budget;   // the drafter's experts first, all of them (every draft uses its blocks)
4151            for (Layer& l : L)
4152                if (l.grp == (int) gi && l.mtp) {
4153                    l.n_vram = std::min(l.n_exp, (int) std::floor(budget_t / (double) ucount(l)));
4154                    budget_t -= (double) l.n_vram * ucount(l);
4155                }
4156            double want = 0;
4157            for (const Layer& l : L)
4158                if (l.grp == (int) gi && !l.mtp && !l.cpu_only) want += (double) ucount(l) * l.n_exp;
4159            const double frac = want > 0 ? std::min(1.0, std::max(0.0, budget_t) / want) : 0.0;
4160            for (Layer& l : L) {
4161                if (l.grp != (int) gi || l.mtp) continue;
4162                if (l.cpu_only) {   // (its type has no device kernel: the CPU lane reads every expert of it)
4163                    l.n_vram = 0;
4164                    continue;
4165                }
4166                l.n_vram = std::min(l.n_exp, (int) std::floor(frac * l.n_exp));
4167                // never more than fits: the floor of each layer's share can still round up the total
4168                while (l.n_vram > 0 && (double) ucount(l) * l.n_vram > budget) --l.n_vram;
4169            }
4170            double used = 0;
4171            for (Layer& l : L)
4172                if (l.grp == (int) gi) used += (double) ucount(l) * l.n_vram;
4173            // what the floors left: whole experts, layer by layer
4174            for (Layer& l : L) {
4175                if (l.grp != (int) gi || l.cpu_only) continue;
4176                while (l.n_vram < l.n_exp && used + (double) ucount(l) <= budget) {
4177                    ++l.n_vram;
4178                    used += (double) ucount(l);
4179                }
4180            }
4181        }
4182        if (kept > 0) {   // the commit kept experts off the GPU: say so, and the page file that keeps them on it
4183            const os::Commit c = os::commit();
4184            const double gib = (double) (1ull << 30);
4185            const double pf = c.limit != ~uint64_t{0} && c.ram != ~uint64_t{0} && c.limit > c.ram ? (double) (c.limit - c.ram) : 0.0;
4186            commit_kept = kept;
4187            pagefile_hint = std::ceil((pf + kept) / gib);
4188            std::fprintf(stderr,
4189                         "ds4: WARNING: %.1f GB of experts stay off the GPU - Windows charges the GPU's memory to its "
4190                         "commit (RAM + page file) and can commit only %.1f GB more for them (%.0f GB kept for the "
4191                         "other programs). A page file of %.0f GB (%.0f MB; now %.0f GB) keeps them on the GPU: System "
4192                         "> About > Advanced system settings > Performance > Advanced > Virtual memory, then restart\n",
4193                         kept / 1e9, room0 / 1e9, commit_margin() / 1e9, pagefile_hint, pagefile_hint * 1024.0, pf / gib);
4194        } else if (room0 < 1e300 && o.verbose) {
4195            std::fprintf(stderr, "ds4: Windows' commit has room for the GPU's experts (%.1f GB beside %.0f GB for the other "
4196                                 "programs)\n", room0 / 1e9, commit_margin() / 1e9);
4197        }
4198        size_t lend_off = 0;
4199        if (lend_min_ > 0) {   // (DS4_LEND) one arena for the VRAM experts of the trunk's layers
4200            const bool can = devs.size() == 1 && chunks.size() == 1 && chunks[0] && file_experts && !L.empty() &&
4201                             L[0].lay.fmt == gg::kFmtMXFP4;
4202            size_t tot = 0;
4203            for (const Layer& l : L)
4204                if (can && !l.mtp && l.nm == 1) tot += align256((size_t) std::min(l.n_vram, l.n_exp) * unit(l));
4205            void* a = nullptr;
4206            if (tot > 0 && cudaMalloc(&a, tot) == cudaSuccess) {
4207                devs[0].allocs.push_back(a);
4208                lend_arena_ = (uint8_t*) a;
4209                lend_bytes_ = tot;
4210            } else {
4211                cudaGetLastError();
4212                lend_min_ = 0;
4213            }
4214            lend_of_.assign(L.size(), 0);
4215        }
4216        for (Layer& l : L) {
4217            // the hottest experts of the profile first, then by index
4218            std::vector<int> order((size_t) l.n_exp);
4219            std::iota(order.begin(), order.end(), 0);
4220            const uint32_t* p = prof.data() + (size_t) l.il * g.n_exp;
4221            std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return p[a] > p[b]; });
4222            l.slot.assign((size_t) l.n_exp, -1);
4223            l.host.assign((size_t) l.n_exp, nullptr);
4224            // a layer with experts on both sides keeps one VRAM slot free for the cache's swaps
4225            l.n_slots = std::min(l.n_vram, l.n_exp);
4226            if (o.expert_cache && l.n_slots >= 2 && l.n_slots < l.n_exp) {   // (every expert fits: nothing to swap)
4227                l.n_vram = l.n_slots - 1;
4228                l.spare_vram = l.n_slots - 1;
4229            } else {
4230                l.n_vram = l.n_slots;
4231                l.spare_vram = -1;
4232            }
4233            for (int i = 0; i < l.n_vram; ++i) l.slot[(size_t) order[(size_t) i]] = i;
4234            if (lend_arena_ != nullptr && !l.mtp && l.nm == 1 && l.n_slots > 0) {
4235                l.vram_base = lend_arena_ + lend_off;
4236                lend_off += align256((size_t) l.n_slots * unit(l));
4237                devs[(size_t) l.dev].experts += (size_t) l.n_slots * unit(l);
4238                lend_of_[(size_t) l.il] = 1;
4239            }
4240            for (int m = 0; m < l.nm && l.n_slots > 0 && !(lend_arena_ != nullptr && lend_of_[(size_t) l.il]); ++m) {
4241                Layer& x = member(l, m);
4242                Dev& d = devs[(size_t) x.dev];
4243                cudaSetDevice(d.id);
4244                void* v = nullptr;
4245                if (cudaMalloc(&v, (size_t) l.n_slots * unit(x)) != cudaSuccess) {
4246                    err = "cudaMalloc of layer " + std::to_string(l.il) + "'s " + std::to_string(l.n_slots) +
4247                          " experts on CUDA" + std::to_string(d.id) + " failed";
4248                    return false;
4249                }
4250                d.allocs.push_back(v);
4251                d.experts += (size_t) l.n_slots * unit(x);
4252                x.vram_base = (uint8_t*) v;
4253            }
4254            l.heat.assign((size_t) l.n_exp, 0.0f);
4255            {   // the profile as the starting heat: its counts scaled to ~512 hits a layer
4256                double sum = 0;
4257                for (int e = 0; e < l.n_exp; ++e) sum += p[e];
4258                const double sc = sum > 0 ? 512.0 / sum : 0.0;
4259                for (int e = 0; e < l.n_exp; ++e) l.heat[(size_t) e] = (float) (p[e] * sc);
4260            }
4261            const int n_host = l.n_exp - l.n_vram;
4262            {   // the CPU lane's parts of an expert (in place: the whole expert, its pieces where the file has them)
4263                size_t off = 0;
4264                for (int r = 0; r < 3; ++r) {
4265                    const int k = r < 2 ? g.dim : g.ff, nf = r < 2 ? g.ff : g.dim, n = nf / NH;
4266                    l.hl.k[r] = k;
4267                    l.hl.n[r] = n;
4268                    l.hl.trellis[r] = file_experts ? l.piece_src[r][0] : off;
4269                    off += align256((size_t) (k / 16) * (n / 16) * 32 * l.lay.K[r]);
4270                    l.hl.suh[r] = file_experts ? l.piece_src[r][1] : off;
4271                    off += align256((size_t) k * 2);
4272                    l.hl.svh[r] = file_experts ? l.piece_src[r][2] : off;
4273                    off += align256((size_t) n * 2);
4274                }
4275                l.hl.bytes = off;
4276            }
4277            l.hh.assign((size_t) l.n_exp, {nullptr, nullptr, nullptr, nullptr});
4278            if (l.lay.fmt == gg::kFmtMXFP4) {   // a GGUF's: read in place from the file's mapping
4279                for (int e = 0; e < l.n_exp; ++e)
4280                    if (l.slot[(size_t) e] < 0) l.host[(size_t) e] = (uint8_t*) mx_mat(l, e, 0);
4281            } else if (file_experts) {   // every expert's file mapped (the cache's swaps hand VRAM experts back to the files)
4282                for (int e = 0; e < l.n_exp; ++e)
4283                    if (pk.map(l.region_file[(size_t) e]) == nullptr) {
4284                        err = "mapping " + pk.files[(size_t) l.region_file[(size_t) e]] + " failed";
4285                        return false;
4286                    }
4287                for (int e = 0; e < l.n_exp; ++e)
4288                    if (l.slot[(size_t) e] < 0) {
4289                        l.hh[(size_t) e][0] = file_part(l, e);
4290                        l.host[(size_t) e] = l.hh[(size_t) e][0];
4291                    }
4292            } else if (n_host > 0) {
4293                const int n_parts = n_host + (l.spare_vram >= 0 ? 1 : 0);   // (+ the cache's spare)
4294                const size_t bytes = (size_t) n_parts * l.hl.bytes;
4295                for (int X = 0; X < NH; ++X) {
4296                    void* m = node_map(bytes, X, NH);
4297                    if (m == nullptr) {
4298                        err = "host memory for layer " + std::to_string(l.il) + "'s " + std::to_string(n_host) +
4299                              " CPU experts (" + std::to_string(bytes >> 20) + " MiB on node " + std::to_string(X) + ")";
4300                        return false;
4301                    }
4302                    host_maps.emplace_back(m, bytes);
4303                    int hi = 0;
4304                    for (int e = 0; e < l.n_exp; ++e)
4305                        if (l.slot[(size_t) e] < 0) l.hh[(size_t) e][(size_t) X] = (uint8_t*) m + (size_t) (hi++) * l.hl.bytes;
4306                    if (l.spare_vram >= 0) l.spare_host[(size_t) X] = (uint8_t*) m + (size_t) hi * l.hl.bytes;
4307                }
4308                for (int e = 0; e < l.n_exp; ++e)
4309                    if (l.slot[(size_t) e] < 0) l.host[(size_t) e] = l.hh[(size_t) e][0];
4310            }
4311            l.vm.assign((size_t) l.n_exp, {});
4312            if (l.nm == 1)   // (the host-routed window path's views: a group's members take the device-routed path)
4313                for (int e = 0; e < l.n_exp; ++e)
4314                    if (l.slot[(size_t) e] >= 0) set_vm(l, e, l.slot[(size_t) e]);
4315            if (!halloc(l.tab_pin, (size_t) 2 * l.nm, err)) return false;
4316            for (int m = 0; m < l.nm; ++m) {
4317                Layer& x = member(l, m);
4318                std::vector<unsigned long long> tab((size_t) l.n_exp, 0ull);
4319                for (int e = 0; e < l.n_exp; ++e)
4320                    if (l.slot[(size_t) e] >= 0)
4321                        tab[(size_t) e] = (unsigned long long) (x.vram_base + (size_t) l.slot[(size_t) e] * unit(x));
4322                cudaSetDevice(devs[(size_t) x.dev].id);
4323                CK(cudaMemcpy(x.vram_tab, tab.data(), tab.size() * 8, cudaMemcpyHostToDevice));
4324            }
4325        }
4326        if (lend_arena_ != nullptr) {   // the long prompts' chunk: as large as the arena holds (whole 1024s)
4327            const int was = chunk;
4328            while (chunk > chunk_small_ && lend_need(chunk) > lend_bytes_) chunk -= 1024;
4329            if (chunk <= chunk_small_) lend_min_ = 0;
4330            std::fprintf(stderr, "ds4: lent prompts: %s (VRAM experts' arena %.2f GB, chunks of %d needing %.2f GB%s)\n",
4331                         lend_min_ > 0 ? ("from " + std::to_string(lend_min_) + " tokens").c_str() : "off",
4332                         lend_bytes_ / 1e9, chunk, lend_need(chunk) / 1e9, chunk < was ? ", cut to fit" : "");
4333        }
4334        return true;
4335    }
4336
4337    // the chunk buffers whose size goes with its rows (C) or its attention slab (A), and the attention weights' FP16
4338    // (DS4_ATTN_WCACHE): what a lent prompt carves out of the experts' arena, (field, bytes)
4339    std::vector<std::pair<void**, size_t>> lend_bufs(Chunk& c, size_t C, size_t A) const {
4340        const size_t D = g.dim, H = g.hc, HD = g.hd, HQ = (size_t) g.heads * HD, OG = g.o_groups, FF = g.ff;
4341        const size_t eg_per = (size_t) (pk.eg_ngram - 1) * pk.eg_heads * (pk.eg_hd + pk.eg_hd / 32);
4342        std::vector<std::pair<void**, size_t>> v;
4343        auto f = [&v](auto*& p, size_t n) { v.push_back({(void**) &p, n * sizeof(*p)}); };
4344        f(c.h, C * H * D), f(c.x, C * D), f(c.acc, C * D), f(c.x16, C * D), f(c.qr, C * g.q_lora), f(c.qr16, C * g.q_lora);
4345        f(c.kvr, C * HD), f(c.ckr, C * HD), f(c.cgr, C * HD), f(c.latent, (C + 2) * HD), f(c.lat16, (C + 2) * HD);
4346        f(c.ikr, (C + 2) * g.ix_hd), f(c.ext, ((size_t) g.win + C) * HD);
4347        f(c.q, A * HQ), f(c.o, A * HQ), f(c.o16, A * HQ), f(c.oa, A * OG * g.o_lora), f(c.oa16, A * OG * g.o_lora);
4348        f(c.iw, C * 64), f(c.topk, C * topk_stride()), f(c.cand, C * cand_stride()), f(c.mix, C * 32);
4349        f(c.a_pre, C * 8), f(c.a_post, C * 8), f(c.a_comb, C * 64), f(c.f_pre, C * 8), f(c.f_post, C * 8);
4350        f(c.f_comb, C * 64), f(c.pre, C * 8), f(c.glog, C * 1024), f(c.ridx, C * kPicks), f(c.rw, C * kPicks);
4351        f(c.row_tok, C * kPicks), f(c.pos, C * kPicks), f(c.sg, C * FF), f(c.su, C * FF), f(c.sh16, C * FF);
4352        f(c.h16, C * FF), f(c.y, C * D);
4353        if (c.emb != nullptr) f(c.emb, C * D);
4354        if (c.eg_rows != nullptr) f(c.eg_rows, C * eg_per);
4355        if (std::getenv("DS4_ATTN_WCACHE") != nullptr && std::atoi(std::getenv("DS4_ATTN_WCACHE")) != 0)
4356            f(c.wc, HQ * g.q_lora + HQ * g.o_lora + D * OG * g.o_lora);
4357        return v;
4358    }
4359    size_t lend_need(int C) const {
4360        size_t n = 0;
4361        for (const auto& b : lend_bufs(*chunks[0], (size_t) C, (size_t) std::min(lend_slab_, C))) n += align256(b.second);
4362        return n;
4363    }
4364    // a lent prompt starts: the cache's swaps land (they write VRAM slots), the trunk's VRAM experts stream like the CPU
4365    // lane's (plan_streams), the chunk's buffers are carved out of the arena
4366    void lend_begin() {
4367        {
4368            std::unique_lock<std::mutex> lk(sw_mu);
4369            sw_done_cv.wait(lk, [&] { return sw_ready.size() >= (size_t) sw_inflight || quit.load(); });
4370        }
4371        cudaSetDevice(devs[0].id);
4372        cudaDeviceSynchronize();
4373        lend_nslots_.assign(L.size(), 0);
4374        for (Layer& l : L)
4375            if (lend_of_[(size_t) l.il]) {
4376                lend_nslots_[(size_t) l.il] = l.n_slots;
4377                l.n_slots = 0;
4378            }
4379        Chunk& c = *chunks[0];
4380        lend_saved_C_ = c.C;
4381        lend_saved_A_ = c.A;
4382        const int A = std::min(lend_slab_, chunk);
4383        size_t off = 0;
4384        for (const auto& b : lend_bufs(c, (size_t) chunk, (size_t) A)) {
4385            lend_saved_.push_back({b.first, *b.first});
4386            *b.first = lend_arena_ + off;
4387            off += align256(b.second);
4388        }
4389        c.C = chunk;
4390        c.A = A;
4391        std::fill(std::begin(c.wc_tag), std::end(c.wc_tag), nullptr);
4392        lent_ = true;
4393    }
4394    // its run is over: the chunk's own buffers back; the experts come back at the next forward (lend_restore)
4395    void lend_end_bufs() {
4396        Chunk& c = *chunks[0];
4397        cudaSetDevice(devs[0].id);
4398        cudaDeviceSynchronize();
4399        for (const auto& s : lend_saved_) *s.first = s.second;
4400        lend_saved_.clear();
4401        c.C = lend_saved_C_;
4402        c.A = lend_saved_A_;
4403        std::fill(std::begin(c.wc_tag), std::end(c.wc_tag), nullptr);
4404        lend_due_ = true;
4405    }
4406    // the trunk's VRAM experts read back into their slots (and the spare slot of a swap that landed before the prompt
4407    // but is not applied yet), then the cache tick the prompt left
4408    bool lend_restore(std::string& err) {
4409        if (!lend_due_) return true;
4410        lend_due_ = false;
4411        const double t0 = now_ms();
4412        struct Job {
4413            int layer, e, slot;
4414        };
4415        std::vector<Job> jobs;
4416        size_t maxb = 0;
4417        for (const Layer& l : L) {
4418            if (!lend_of_[(size_t) l.il]) continue;
4419            maxb = std::max(maxb, unit(l));
4420            for (int e = 0; e < l.n_exp; ++e)
4421                if (l.slot[(size_t) e] >= 0) jobs.push_back({l.il, e, l.slot[(size_t) e]});
4422        }
4423        {
4424            std::lock_guard<std::mutex> lk(sw_mu);
4425            for (const Swap& sw : sw_ready)
4426                if (lend_of_[(size_t) sw.layer] && L[(size_t) sw.layer].spare_vram >= 0)
4427                    jobs.push_back({sw.layer, sw.in, L[(size_t) sw.layer].spare_vram});
4428        }
4429        std::atomic<size_t> next{0};
4430        std::atomic<bool> failed{false};
4431        std::vector<std::thread> th;
4432        for (int t = 0; t < 12; ++t)
4433            th.emplace_back([&] {
4434                uint8_t* stage = nullptr;
4435                if (cudaHostAlloc((void**) &stage, maxb, cudaHostAllocPortable) != cudaSuccess) {
4436                    failed.store(true);
4437                    return;
4438                }
4439                cudaSetDevice(devs[0].id);
4440                for (;;) {
4441                    const size_t i = next.fetch_add(1);
4442                    if (i >= jobs.size() || failed.load()) break;
4443                    const Layer& l = L[(size_t) jobs[i].layer];
4444                    if (!read_mx(l, jobs[i].e, stage) ||
4445                        cudaMemcpy(l.vram_base + (size_t) jobs[i].slot * unit(l), stage, unit(l), cudaMemcpyHostToDevice) !=
4446                            cudaSuccess)
4447                        failed.store(true);
4448                }
4449                cudaFreeHost(stage);
4450            });
4451        for (auto& x : th) x.join();
4452        if (failed.load()) {
4453            err = "reading the VRAM experts back after a lent prompt failed";
4454            return false;
4455        }
4456        for (Layer& l : L)
4457            if (lend_of_[(size_t) l.il]) l.n_slots = lend_nslots_[(size_t) l.il];
4458        lent_ = false;
4459        cache_tick((int) lend_tick_n_);
4460        if (o.verbose)
4461            std::fprintf(stderr, "ds4: lent prompt: %zu VRAM experts read back in %.0f ms\n", jobs.size(), now_ms() - t0);
4462        return true;
4463    }
4464
4465    // a GGUF's VRAM experts, in file order, by a few threads through pinned staging blobs (the CPU lane's stay in the
4466    // file: the mapping reads them on first use)
4467    bool load_experts_mx(std::string& err) {
4468        struct Job {
4469            int layer, e;
4470        };
4471        std::vector<Job> jobs;
4472        size_t maxb = 0;
4473        for (const Layer& l : L) {
4474            maxb = std::max(maxb, l.blob);
4475            for (int e = 0; e < l.n_exp; ++e)
4476                if (l.slot[(size_t) e] >= 0) jobs.push_back({l.il, e});
4477        }
4478        std::sort(jobs.begin(), jobs.end(), [&](const Job& a, const Job& b) {
4479            const Layer &la = L[(size_t) a.layer], &lb = L[(size_t) b.layer];
4480            if (la.mx_file[0] != lb.mx_file[0]) return la.mx_file[0] < lb.mx_file[0];
4481            return la.mx_off[0] + (uint64_t) a.e * la.mx_stride[0] < lb.mx_off[0] + (uint64_t) b.e * lb.mx_stride[0];
4482        });
4483        std::atomic<size_t> next{0};
4484        std::atomic<bool> failed{false};
4485        std::mutex emu;
4486        std::string ferr;
4487        std::atomic<int64_t> done_bytes{0};
4488        const double t0 = now_ms();
4489        std::vector<std::thread> th;
4490        for (int t = 0; t < 12; ++t)
4491            th.emplace_back([&] {
4492                uint8_t *stage = nullptr, *stage2 = nullptr;
4493                cudaHostAlloc((void**) &stage, maxb, cudaHostAllocPortable);
4494                cudaHostAlloc((void**) &stage2, maxb, cudaHostAllocPortable);
4495                for (;;) {
4496                    const size_t i = next.fetch_add(1);
4497                    if (i >= jobs.size() || failed.load()) break;
4498                    const Layer& l = L[(size_t) jobs[i].layer];
4499                    const int e = jobs[i].e;
4500                    bool ok = stage != nullptr && stage2 != nullptr && read_mx(l, e, stage);
4501                    for (int m = 0; m < l.nm && ok; ++m) {   // (a group: each member its part)
4502                        const Layer& x = member(l, m);
4503                        cudaSetDevice(devs[(size_t) x.dev].id);
4504                        if (l.nm > 1) blob_to_half(l, stage, m, stage2);
4505                        ok = cudaMemcpy(x.vram_base + (size_t) l.slot[(size_t) e] * unit(l), l.nm > 1 ? stage2 : stage,
4506                                        unit(l), cudaMemcpyHostToDevice) == cudaSuccess;
4507                    }
4508                    if (!ok) {
4509                        std::lock_guard<std::mutex> lk(emu);
4510                        ferr = "loading layer " + std::to_string(l.il) + " expert " + std::to_string(e) + " failed";
4511                        failed.store(true);
4512                        break;
4513                    }
4514                    const int64_t db = done_bytes.fetch_add((int64_t) l.blob) + (int64_t) l.blob;
4515                    if (o.verbose && (i % 1024) == 0)
4516                        std::fprintf(stderr, "ds4: experts %zu / %zu (%.1f GB, %.2f GB/s)\n", i, jobs.size(), db / 1e9,
4517                                     db / 1e6 / std::max(1.0, now_ms() - t0));
4518                }
4519                if (stage) cudaFreeHost(stage);
4520                if (stage2) cudaFreeHost(stage2);
4521            });
4522        for (auto& t : th) t.join();
4523        if (failed.load()) {
4524            err = ferr;
4525            return false;
4526        }
4527        // as load_experts in place: the VRAM experts' pages leave the cache, the most-routed of the others (the
4528        // profile's share of their layer, then by index) are read once, up to warm_bytes, so the cache starts with them
4529        struct Warm {
4530            int layer, e;
4531            double share;
4532        };
4533        std::vector<Warm> warm;
4534        for (const Layer& l : L) {
4535            const uint32_t* p = prof.data() + (size_t) l.il * g.n_exp;
4536            double sum = 0;
4537            for (int e = 0; e < l.n_exp; ++e) sum += p[e];
4538            for (int e = 0; e < l.n_exp; ++e) {
4539                if (l.slot[(size_t) e] >= 0) {
4540                    for (int r = 0; r < 3; ++r)
4541                        os::advise(pk.fds[(size_t) l.mx_file[r]], (l.mx_off[r] + (uint64_t) e * l.mx_stride[r]), mx_part_bytes(l, r), false);
4542                } else {
4543                    warm.push_back({l.il, e, sum > 0 ? p[e] / sum : 0.0});
4544                }
4545            }
4546        }
4547        std::stable_sort(warm.begin(), warm.end(), [](const Warm& a, const Warm& b) { return a.share > b.share; });
4548        if (!ram_tier && !warm.empty()) {   // copied into RAM (copy_experts decides), the rest read ahead into what is left
4549            std::vector<std::pair<int, int>> hot;
4550            for (const Warm& w : warm) hot.push_back({w.layer, w.e});
4551            if (!copy_experts(hot, err)) return false;
4552            if (copy_mode) {
4553                warm.erase(std::remove_if(warm.begin(), warm.end(),
4554                                          [&](const Warm& w) { return L[(size_t) w.layer].ram[(size_t) w.e] >= 0; }),
4555                           warm.end());
4556                const uint64_t av = ram_avail();
4557                if (av != ~uint64_t{0}) warm_bytes = av > kRamMargin ? std::min<uint64_t>(warm_bytes, av - kRamMargin) : 0;
4558            }
4559        }
4560        if (ram_tier && warm_bytes > 0 && !warm.empty()) {
4561            // chunks of 32 slots up to warm_bytes (all the RAM the rest leaves, kRamMargin kept), one slot kept free for
4562            // a move in; the hottest experts read in, their pages then dropped from the page cache.  Plain memory, not
4563            // pinned: only the CPU reads it (what goes to a GPU passes the pinned staging), and pinned memory is capped on
4564            // Windows - the engine's own pinned buffers come after this
4565            const size_t want = std::min(warm.size(), (size_t) (warm_bytes / maxb));
4566            while (ram_slots.size() < want + 1) {
4567                const size_t n = std::min<size_t>(32, want + 1 - ram_slots.size());
4568                uint8_t* c = (uint8_t*) os::anon_alloc(n * maxb, -1, 1);
4569                if (c == nullptr) break;
4570                ram_chunks.push_back(c);
4571                ram_chunk_bytes.push_back(n * maxb);
4572                for (size_t i = 0; i < n; ++i) ram_slots.push_back(c + i * maxb);
4573            }
4574            ram_held = ram_slots.empty() ? 0 : (int) ram_slots.size() - 1;
4575            for (Layer& l : L)
4576                if (l.lay.fmt == gg::kFmtMXFP4) l.ram.assign((size_t) l.n_exp, -1);
4577            std::atomic<size_t> ri{0};
4578            std::atomic<bool> rfail{false};
4579            std::vector<std::thread> rt;
4580            for (int t = 0; t < 12 && ram_held > 0; ++t)
4581                rt.emplace_back([&] {
4582                    for (size_t i; (i = ri.fetch_add(1)) < (size_t) ram_held;) {
4583                        const Layer& l = L[(size_t) warm[i].layer];
4584                        if (!read_mx_file(l, warm[i].e, ram_slots[i])) rfail.store(true);
4585                        for (int r = 0; r < 3; ++r)
4586                            os::advise(pk.fds[(size_t) l.mx_file[r]], l.mx_off[r] + (uint64_t) warm[i].e * l.mx_stride[r],
4587                                       mx_part_bytes(l, r), false);
4588                    }
4589                });
4590            for (auto& t : rt) t.join();
4591            if (rfail.load()) {
4592                err = "reading the RAM tier's experts from the model's files failed";
4593                return false;
4594            }
4595            for (int i = 0; i < ram_held; ++i) L[(size_t) warm[(size_t) i].layer].ram[(size_t) warm[(size_t) i].e] = i;
4596            if (ram_held > 0) ram_free.push_back(ram_held);
4597            if (o.expert_cache && ram_held > 0) ram_th = std::thread([this] { ram_loop(); });
4598            if (o.verbose)
4599                std::fprintf(stderr, "ds4: RAM tier: %d experts (%.1f GB of RAM), the hottest after VRAM's; the other %zu "
4600                                     "read from the model's files (%.1f s)\n",
4601                             ram_held, ram_slots.size() * (double) maxb / 1e9, warm.size() - (size_t) ram_held,
4602                             (now_ms() - t0) / 1000.0);
4603            return true;
4604        }
4605        size_t nw = 0;
4606        for (double b = 0; nw < warm.size() && b + (double) L[(size_t) warm[nw].layer].blob <= (double) warm_bytes; ++nw)
4607            b += (double) L[(size_t) warm[nw].layer].blob;
4608        std::atomic<size_t> wi{0};
4609        std::vector<std::thread> wt;
4610        for (int t = 0; t < 12 && nw > 0; ++t)
4611            wt.emplace_back([&] {
4612                std::vector<uint8_t> buf(maxb);
4613                for (size_t i; (i = wi.fetch_add(1)) < nw;) read_mx(L[(size_t) warm[i].layer], warm[i].e, buf.data());
4614            });
4615        for (auto& t : wt) t.join();
4616        if (o.verbose && nw > 0)
4617            std::fprintf(stderr, "ds4: %zu CPU-lane experts read ahead (%.1f GB) in %.1f s\n", nw,
4618                         nw * (double) L[0].blob / 1e9, (now_ms() - t0) / 1000.0);
4619        return true;
4620    }
4621
4622    // a GGUF's CPU-lane experts copied into RAM (copy_mode), decided once VRAM's are in - on a unified-memory APU the GPU
4623    // has taken its share of the RAM by then, so the copies only get what it leaves.  `hot`: the CPU lane's experts, the
4624    // most-routed first.  --mmap-experts off: all that fit beside kRamMargin (a warning if not all do); on and auto:
4625    // none - read in place: the page cache follows a conversation's experts where a static set (the profile's
4626    // hottest) does not (the RAM tier's lesson), and copies that all fit were no faster; DS4_COPY_GB=<n>: the
4627    // hottest n GB (the static hybrid, for tests).  Each copy in NH parts on the NUMA nodes (DS4_COPY_NUMA=1: one), read from the files in file
4628    // order by a few threads, anonymous memory on huge pages (Windows: plain), not pinned (only the CPU reads it; what
4629    // goes to a GPU passes the pinned staging) - a layer that cannot get its memory keeps its experts in place
4630    bool copy_experts(const std::vector<std::pair<int, int>>& hot, std::string& err) {
4631        if (o.mmap_experts > 0 || hot.empty()) return true;
4632        const double t0 = now_ms();
4633        auto spare_of = [&](const Layer& l) { return o.expert_cache && l.spare_vram >= 0 ? 1 : 0; };
4634        double all = 0;
4635        {
4636            std::vector<char> seen(L.size(), 0);
4637            for (const auto& h : hot) {
4638                const Layer& l = L[(size_t) h.first];
4639                all += (double) l.blob * (1 + (seen[(size_t) l.il]++ == 0 ? spare_of(l) : 0));
4640            }
4641        }
4642        const uint64_t avail = ram_avail();
4643        // (Windows: the copies are committed memory, within what its commit still has beside the other programs' margin)
4644        const double can = std::min(avail == ~uint64_t{0} ? 1e300 : std::max(0.0, (double) avail - (double) kRamMargin),
4645                                    commit_room());
4646        // (auto: none - copies that all fit were measured no faster than the page cache: the CPU lane's rows are
4647        // compute-bound, ~46 GB/s from either on 2 Xeon sockets, NUMA parts included; a part copied cost decode speed
4648        // on 64 GB and on 32 GB of RAM)
4649        double budget = o.mmap_experts == 0 ? std::min(all, can) : auto_copy_all && all <= can ? all : 0.0;   // (auto: all or none)
4650        if (const char* v = std::getenv("DS4_COPY_GB")) budget = std::atof(v) * 1e9;
4651        if (o.mmap_experts < 0 && auto_copy_all && all > can)
4652            std::fprintf(stderr, "ds4: the CPU lane's experts (%.1f GB) do not all fit the RAM this process can get now (%.1f GB beside %.0f GB for "
4653                                 "the rest): read in place from the model's files (--mmap-experts off copies what fits)\n", all / 1e9, can / 1e9, kRamMargin / 1e9);
4654        if (o.mmap_experts == 0 && all > can)
4655            std::fprintf(stderr, "ds4: --mmap-experts off: the CPU lane's experts (%.1f GB) do not all fit the RAM this "
4656                                 "process can get (%.1f GB beside %.0f GB for the rest) - the most-routed copied, the "
4657                                 "others read in place\n", all / 1e9, can / 1e9, kRamMargin / 1e9);
4658        if (auto_copy_all && budget > 0)
4659            std::fprintf(stderr, "ds4: --mmap-experts auto: the CPU lane's experts (%.1f GB) fit the RAM this process can get (%.1f GB beside %.0f GB for "
4660                                 "the rest): copied in at load, no demand store (--mmap-experts on keeps them in place)\n", all / 1e9, can / 1e9, kRamMargin / 1e9);
4661        if (budget <= 0) {
4662            if (o.verbose)
4663                std::fprintf(stderr, "ds4: the CPU lane's experts (%.1f GB) stay in place: the RAM this process can get "
4664                                     "(%.1f GB beside %.0f GB for the rest) does not hold them all\n",
4665                             all / 1e9, can / 1e9, kRamMargin / 1e9);
4666            return true;
4667        }
4668        // NUMA parts: whole rows of each matrix, so any row count the nodes divide
4669        int nh = (int) std::min<size_t>(2, std::max<size_t>(1, cores.size()));
4670        if (const char* v = std::getenv("DS4_COPY_NUMA"))   // (0 / 1: one part; 2: two, even on one node - a test)
4671            nh = std::atoi(v) >= 2 ? 2 : 1;
4672        if (g.ff % nh != 0 || g.dim % nh != 0) nh = 1;
4673        NH = nh;
4674        cp_lay.assign(L.size(), {0, 0, 0, 0});
4675        for (const Layer& l : L) {
4676            size_t off = 0;
4677            for (int r = 0; r < 3; ++r) {
4678                cp_lay[(size_t) l.il][(size_t) r] = off;
4679                off += align256((size_t) (mx_n(r) / NH) * mx_row_b(l, r));
4680            }
4681            cp_lay[(size_t) l.il][3] = off;
4682        }
4683        // the hottest that fit the budget (a layer's first one brings its spare)
4684        std::vector<int> n_copy(L.size(), 0);
4685        double used = 0;
4686        size_t take = 0;
4687        for (; take < hot.size(); ++take) {
4688            const Layer& l = L[(size_t) hot[take].first];
4689            const double add = (double) l.blob * (1 + (n_copy[(size_t) l.il] == 0 ? spare_of(l) : 0));
4690            if (used + add > budget) break;
4691            used += add;
4692            ++n_copy[(size_t) l.il];
4693        }
4694        // each layer's slots: one block per node of (copies + spare) parts
4695        std::vector<int> first(L.size(), -1);
4696        copy_spare.assign(L.size(), -1);
4697        for (Layer& l : L) {
4698            l.ram.assign((size_t) l.n_exp, -1);
4699            const int ns = n_copy[(size_t) l.il] + (n_copy[(size_t) l.il] > 0 ? spare_of(l) : 0);
4700            if (ns == 0) continue;
4701            const size_t part = cp_lay[(size_t) l.il][3], bytes = (size_t) ns * part;
4702            std::array<uint8_t*, 2> base = {nullptr, nullptr};
4703            bool ok = true;
4704            for (int X = 0; X < NH && ok; ++X) {
4705                base[(size_t) X] = (uint8_t*) node_map(bytes, X, NH);
4706                ok = base[(size_t) X] != nullptr;
4707                if (ok) {
4708                    ram_chunks.push_back(base[(size_t) X]);
4709                    ram_chunk_bytes.push_back(bytes);
4710                }
4711            }
4712            if (!ok) {
4713                std::fprintf(stderr, "ds4: no RAM for layer %d's %d copied experts (%.1f GB): they stay in place\n", l.il,
4714                             ns, (double) bytes * NH / 1e9);
4715                n_copy[(size_t) l.il] = 0;
4716                continue;
4717            }
4718            first[(size_t) l.il] = (int) ram_part.size();
4719            for (int i = 0; i < ns; ++i)
4720                ram_part.push_back({base[0] + (size_t) i * part, NH > 1 ? base[1] + (size_t) i * part : nullptr});
4721            if (spare_of(l)) copy_spare[(size_t) l.il] = first[(size_t) l.il] + ns - 1;
4722        }
4723        struct Job {
4724            int layer, e, slot;
4725        };
4726        std::vector<Job> jobs;
4727        {
4728            std::vector<int> next = first;
4729            for (size_t i = 0; i < take; ++i) {
4730                const int il = hot[i].first;
4731                if (n_copy[(size_t) il] == 0) continue;
4732                jobs.push_back({il, hot[i].second, next[(size_t) il]++});
4733            }
4734        }
4735        std::sort(jobs.begin(), jobs.end(), [&](const Job& a, const Job& b) {   // (file order: the disk reads ahead)
4736            const Layer &la = L[(size_t) a.layer], &lb = L[(size_t) b.layer];
4737            if (la.mx_file[0] != lb.mx_file[0]) return la.mx_file[0] < lb.mx_file[0];
4738            return la.mx_off[0] + (uint64_t) a.e * la.mx_stride[0] < lb.mx_off[0] + (uint64_t) b.e * lb.mx_stride[0];
4739        });
4740        std::atomic<size_t> ji{0};
4741        std::atomic<bool> bad{false};
4742        std::atomic<int64_t> done_b{0};
4743        std::vector<std::thread> th;
4744        for (int t = 0; t < 12 && !jobs.empty(); ++t)
4745            th.emplace_back([&] {
4746                for (size_t i; (i = ji.fetch_add(1)) < jobs.size() && !bad.load();) {
4747                    const Job& j = jobs[i];
4748                    const Layer& l = L[(size_t) j.layer];
4749                    for (int r = 0; r < 3; ++r) {
4750                        const size_t nb = (size_t) (mx_n(r) / NH) * mx_row_b(l, r);
4751                        for (int X = 0; X < NH; ++X)
4752                            if (!pk.read_at(l.mx_file[r], l.mx_off[r] + (uint64_t) j.e * l.mx_stride[r] + (uint64_t) X * nb, nb,
4753                                            ram_part[(size_t) j.slot][(size_t) X] + cp_lay[(size_t) l.il][(size_t) r]))
4754                                bad.store(true);
4755                    }
4756                    const int64_t db = done_b.fetch_add((int64_t) l.blob) + (int64_t) l.blob;
4757                    if (o.verbose && i % 2048 == 0)
4758                        std::fprintf(stderr, "ds4: copying experts %zu / %zu (%.1f GB, %.2f GB/s)\n", i, jobs.size(), db / 1e9,
4759                                     db / 1e6 / std::max(1.0, now_ms() - t0));
4760                }
4761            });
4762        for (auto& t : th) t.join();
4763        if (bad.load()) {
4764            err = "copying the CPU lane's experts from the model's files failed";
4765            return false;
4766        }
4767        for (const Job& j : jobs) L[(size_t) j.layer].ram[(size_t) j.e] = j.slot;
4768        copy_mode = true;
4769        ram_held = (int) jobs.size();
4770        double cb = 0;
4771        for (const Job& j : jobs) cb += (double) L[(size_t) j.layer].blob;
4772        std::fprintf(stderr, "ds4: %zu of the CPU lane's %zu experts copied into RAM (%.1f GB, %d NUMA part%s) in %.1f s%s\n",
4773                     jobs.size(), hot.size(), cb / 1e9, NH, NH > 1 ? "s" : "", (now_ms() - t0) / 1000.0,
4774                     jobs.size() < hot.size() ? "; the others read in place" : "");
4775        return true;
4776    }
4777
4778    bool load_experts(std::string& err) {
4779        if (!L.empty() && L[0].lay.fmt == gg::kFmtMXFP4) return load_experts_mx(err);
4780        // every expert's region, in file order, by a few threads; VRAM ones through a pinned staging blob.  In place
4781        // (file_experts) the CPU lane's experts are not copied: the most-routed of them (the profile's share of their
4782        // layer) are read once, up to warm_bytes, so the page cache starts with them, and the VRAM ones' pages are
4783        // dropped from it again
4784        struct Job {
4785            int layer, e;
4786        };
4787        std::vector<Job> jobs;
4788        for (const Layer& l : L)
4789            for (int e = 0; e < l.n_exp; ++e)
4790                if (!file_experts || l.slot[(size_t) e] >= 0) jobs.push_back({l.il, e});
4791        uint64_t warm = 0;
4792        if (file_experts) {
4793            std::vector<std::pair<double, Job>> cand;
4794            for (const Layer& l : L) {
4795                const uint32_t* p = prof.data() + (size_t) l.il * g.n_exp;
4796                double sum = 0;
4797                for (int e = 0; e < l.n_exp; ++e) sum += p[e];
4798                for (int e = 0; e < l.n_exp; ++e)
4799                    if (l.slot[(size_t) e] < 0) cand.push_back({sum > 0 ? p[e] / sum : 0.0, Job{l.il, e}});
4800            }
4801            std::stable_sort(cand.begin(), cand.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
4802            for (const auto& c : cand) {
4803                const uint64_t b = L[(size_t) c.second.layer].region_bytes[(size_t) c.second.e];
4804                if (warm + b > warm_bytes) break;
4805                warm += b;
4806                jobs.push_back(c.second);
4807            }
4808        }
4809        std::sort(jobs.begin(), jobs.end(), [&](const Job& a, const Job& b) {
4810            const Layer &la = L[(size_t) a.layer], &lb = L[(size_t) b.layer];
4811            if (la.region_file[(size_t) a.e] != lb.region_file[(size_t) b.e])
4812                return la.region_file[(size_t) a.e] < lb.region_file[(size_t) b.e];
4813            return la.region_off[(size_t) a.e] < lb.region_off[(size_t) b.e];
4814        });
4815        std::atomic<size_t> next{0};
4816        std::atomic<bool> failed{false};
4817        std::mutex emu;
4818        std::string ferr;
4819        const int nth = 12;
4820        size_t maxr = 0, maxb = 0;
4821        for (const Layer& l : L) {
4822            maxb = std::max(maxb, l.blob);
4823            for (uint64_t r : l.region_bytes) maxr = std::max<size_t>(maxr, r);
4824        }
4825        std::atomic<int64_t> done_bytes{0};
4826        const double t0 = now_ms();
4827        std::vector<std::thread> th;
4828        for (int t = 0; t < nth; ++t)
4829            th.emplace_back([&] {
4830                std::vector<uint8_t> region(maxr);
4831                uint8_t *stage = nullptr, *stage2 = nullptr;
4832                cudaHostAlloc((void**) &stage, maxb, cudaHostAllocPortable);
4833                cudaHostAlloc((void**) &stage2, maxb, cudaHostAllocPortable);
4834                int cur_dev = -1;
4835                for (;;) {
4836                    const size_t i = next.fetch_add(1);
4837                    if (i >= jobs.size() || failed.load()) break;
4838                    const Layer& l = L[(size_t) jobs[i].layer];
4839                    const int e = jobs[i].e;
4840                    if (!pk.read_at(l.region_file[(size_t) e], l.region_off[(size_t) e], l.region_bytes[(size_t) e],
4841                                    region.data())) {
4842                        std::lock_guard<std::mutex> lk(emu);
4843                        ferr = "reading layer " + std::to_string(l.il) + " expert " + std::to_string(e) + " failed";
4844                        failed.store(true);
4845                        break;
4846                    }
4847                    if (l.slot[(size_t) e] >= 0) {
4848                        repack(l, region.data(), stage);
4849                        bool up = true;
4850                        for (int m = 0; m < l.nm && up; ++m) {   // (a group: each member its part)
4851                            const Layer& x = member(l, m);
4852                            const Dev& d = devs[(size_t) x.dev];
4853                            if (cur_dev != d.id) {
4854                                cudaSetDevice(d.id);
4855                                cur_dev = d.id;
4856                            }
4857                            if (l.nm > 1) blob_to_half(l, stage, m, stage2);
4858                            up = cudaMemcpy(x.vram_base + (size_t) l.slot[(size_t) e] * unit(x), l.nm > 1 ? stage2 : stage,
4859                                            unit(x), cudaMemcpyHostToDevice) == cudaSuccess;
4860                        }
4861                        if (!up) {
4862                            std::lock_guard<std::mutex> lk(emu);
4863                            ferr = "uploading layer " + std::to_string(l.il) + " expert " + std::to_string(e);
4864                            failed.store(true);
4865                            break;
4866                        }
4867                        if (file_experts)
4868                            os::advise(pk.fds[(size_t) l.region_file[(size_t) e]], l.region_off[(size_t) e], l.region_bytes[(size_t) e], false);
4869                    } else if (!file_experts) {
4870                        for (int X = 0; X < NH; ++X) repack_part(l, region.data(), X, l.hh[(size_t) e][(size_t) X]);
4871                    }
4872                    const int64_t db = done_bytes.fetch_add((int64_t) l.region_bytes[(size_t) e]) +
4873                                       (int64_t) l.region_bytes[(size_t) e];
4874                    if (o.verbose && (i % 1024) == 0)
4875                        std::fprintf(stderr, "ds4: experts %zu / %zu (%.1f GB, %.2f GB/s)\n", i, jobs.size(),
4876                                     db / 1e9, db / 1e6 / std::max(1.0, now_ms() - t0));
4877                }
4878                if (stage) cudaFreeHost(stage);
4879                if (stage2) cudaFreeHost(stage2);
4880            });
4881        for (auto& t : th) t.join();
4882        if (failed.load()) {
4883            err = ferr;
4884            return false;
4885        }
4886        if (file_experts)
4887            std::fprintf(stderr, "ds4: experts loaded in %.1f s (%.1f GB of the CPU lane's read ahead)\n",
4888                         (now_ms() - t0) / 1000.0, warm / 1e9);
4889        return true;
4890    }
4891
4892    std::string describe() const {
4893        std::ostringstream s;
4894        for (size_t di = 0; di < devs.size(); ++di) {
4895            const Dev& d = devs[di];
4896            int a = -1, b = -1, ev = 0, et = 0;
4897            for (const Layer& l : L)
4898                for (int m = 0; m < l.nm; ++m)
4899                    if (member(l, m).dev == (int) di) {
4900                        if (a < 0) a = l.il;
4901                        b = l.il;
4902                        ev += l.n_vram;
4903                        et += l.n_exp;
4904                    }
4905            size_t fr = 0, tot = 0;
4906            cudaSetDevice(d.id);
4907            cudaMemGetInfo(&fr, &tot);
4908            const size_t gsz = groups.empty() ? 1 : groups[(size_t) d.grp].mem.size();
4909            char tp[64] = "";
4910            if (gsz > 1) std::snprintf(tp, sizeof tp, " (tensor parallel %zu, part %d)", gsz, d.mi);
4911            char line[384];
4912            std::snprintf(line, sizeof line,
4913                          "ds4: CUDA%d layers [%d, %d]%s%s: weights %.2f GB, experts %.2f GB (%d of %d in VRAM), caches "
4914                          "%.2f GB, %.0f MiB free\n",
4915                          d.id, a, b, tp, (int) di == head_dev ? " + head" : "", d.weights / 1e9, d.experts / 1e9, ev, et,
4916                          d.caches / 1e9, fr / 1048576.0);
4917            s << line;
4918        }
4919        int nh = 0;
4920        size_t hb_ = 0;
4921        for (const Layer& l : L) {
4922            nh += l.n_exp - l.n_vram;
4923            hb_ += (size_t) (l.n_exp - l.n_vram) * l.blob;
4924        }
4925        char line[200];
4926        if (copy_mode)
4927            std::snprintf(line, sizeof line, "ds4: %d routed experts on the CPU lane (%.1f GB): %d copied into RAM (%d NUMA "
4928                                             "parts), the rest in place in the model's files; %d threads\n",
4929                          nh, hb_ / 1e9, ram_held, NH, cpu_threads());
4930        else if (file_experts)
4931            std::snprintf(line, sizeof line,
4932                          "ds4: %d routed experts on the CPU lane (%.1f GB, in place in the model's files), %d threads\n",
4933                          nh, hb_ / 1e9, cpu_threads());
4934        else
4935            std::snprintf(line, sizeof line, "ds4: %d routed experts on the CPU lane (%.1f GB of RAM, %d NUMA parts), %d threads\n", nh,
4936                          hb_ / 1e9, NH, cpu_threads());
4937        s << line;
4938        return s.str();
4939    }
4940
4941    // The most the automatic store may take: all of the trunk's routed experts (the CPU lane's are a part of them; a store larger
4942    // than they are is never filled), never less than the old 48 GB.  A PC whose free RAM holds them all (the 251 GB R9700 box:
4943    // 115 GB of CPU-lane experts, 1 card, 2.00 set: 12.6 -> 21.4 tokens/s with the whole set resident, misses 15.4 -> 1.5 a token)
4944    // gets every one; the RAM that the room below leaves (free - 12 GB) is what bounds it elsewhere.
4945    // Whether the experts the GPUs will not hold (the CPU lane's: the pack's less the GPUs' share) all fit the RAM this process can get beside
4946    // kRamMargin, so that --mmap-experts auto copies them in (a copied expert is the CPU lane's own memory: no page cache to lose to the
4947    // Engram tables and the files' churn, no store indirection or miss path).  Measured, 1 x R9700 + 251 GB, 2.00 pack, warm: decode +10-15%.
4948    // --mmap-experts on/off and --ssd-cache N stand as given.
4949    bool cpu_lane_fits_ram() const {
4950        if (!pk.gguf || o.mmap_experts >= 0 || o.ssd_cache_gb >= 0.0 || std::getenv("DS4_STORE_GB") || std::getenv("DS4_COPY_GB")) return false;
4951        if (const char* v = std::getenv("DS4_COPY_ALL")) return std::atoi(v) != 0 && ram_avail() != ~uint64_t{0};
4952        const uint64_t avail = ram_avail();
4953        if (avail == ~uint64_t{0}) return false;
4954        double exp_b = 0, room = 0, other_b = 0;
4955        const double share = gpu_expert_share(&exp_b, &room, &other_b);
4956        if (exp_b <= 0) return false;
4957        const double lane = exp_b * (1.0 - std::min(1.0, share));
4958        return copy_all_fits(lane, avail, (double) kRamMargin, commit_room());   // (Windows: the commit room too, not only the free RAM)
4959    }
4960    mutable bool auto_copy_all = false;   // (set by store_gb(): the auto size is the CPU lane's experts copied in, no demand store)
4961    double store_cap_gb() const {
4962        double b = 0;
4963        for (const auto& kt : pk.t)
4964            if (kt.first.find(".ffn.experts.") != std::string::npos && kt.first.rfind("mtp.", 0) != 0) b += (double) kt.second.bytes;
4965        return std::max(48.0, b / 1e9);
4966    }
4967    double store_gb() const {
4968        static double cached = -2.0;   // (decided once: the layout of the blobs depends on it)
4969        if (cached > -1.5) return cached;
4970        double gb = o.ssd_cache_gb;
4971        if (const char* v = std::getenv("DS4_STORE_GB")) gb = std::atof(v);
4972        if (!pk.gguf) gb = 0.0;
4973        else if (gb < 0.0 && cpu_lane_fits_ram()) {   // auto, and the RAM holds every CPU-lane expert beside kRamMargin: they are copied in at load
4974            auto_copy_all = true;                       // (copy_experts), the demand store would only be a second, smaller copy of them
4975            gb = 0.0;
4976        } else if (gb < 0.0) {   // auto: the RAM free now less 12 GB for the system and the owner's programs, all the experts at most
4977            const uint64_t avail = ram_avail();
4978            avail0_ = avail;
4979            const double room = avail == ~uint64_t{0} ? 0.0 : (double) avail / 1e9 - 12.0;
4980            gb = room >= 4.0 ? std::min(store_cap_gb(), room) : 0.0;
4981        }
4982        return cached = gb;
4983    }
4984    // The auto size is decided again here, after the weights are on the GPU: on a unified-memory machine (Strix Halo) the GPU's
4985    // allocations come out of the same RAM the store would use, and the first estimate (made at the layout, before any upload)
4986    // saw all of it free.  The explicit sizes (--ssd-cache, DS4_STORE_GB) stand.
4987    mutable uint64_t avail0_ = ~uint64_t{0};   // (free RAM when the first estimate was made, before the weights went to the GPU)
4988    double store_gb_now() const {
4989        const double gb = store_gb();
4990        if (gb <= 0.0 || o.ssd_cache_gb >= 0.0 || std::getenv("DS4_STORE_GB")) return gb;
4991        const uint64_t avail = ram_avail();
4992        if (avail == ~uint64_t{0}) return gb;
4993        // (the prompt buffers and the context's caches are touched after this point and, on such a machine, take RAM too: measured on
4994        // Strix Halo about 0.11 MB a token of context beyond 16384, a 40960 context ending 2.5 GB lower than a 16384 one)
4995        const bool uma = avail0_ != ~uint64_t{0} && avail0_ > avail && (double) (avail0_ - avail) / 1e9 >= 4.0;
4996        const double ctx_gb = uma ? 1.1e-4 * std::max(0.0, (double) o.max_context - 16384.0) : 0.0;
4997        const double room = (double) avail / 1e9 - 12.0 - ctx_gb;
4998        const double now = room >= 4.0 ? std::min(store_cap_gb(), room) : 0.0;
4999        if (now < gb)
5000            std::fprintf(stderr, "ds4: RAM store: %.1f GB of RAM free after the GPU's weights: store sized %.1f GB, not %.1f\n",
5001                         (double) avail / 1e9, now, gb);
5002        return std::min(gb, now);
5003    }
5004    void init_store() {
5005        const double gb = store_gb_now();
5006        if (gb <= 0.0 || L.empty() || L[0].lay.fmt != gg::kFmtMXFP4 || !file_experts) return;
5007        if (o.ssd_cache_gb < 0.0 && !std::getenv("DS4_STORE_GB")) {   // (the auto size: say when it holds less than the CPU lane's experts)
5008            double exp_b = 0;
5009            const double share = gpu_expert_share(&exp_b), lane_gb = exp_b * (1.0 - std::min(1.0, share)) / 1e9;
5010            if (lane_gb > gb + 1.0 && o.verbose)
5011                std::fprintf(stderr, "ds4: RAM store: the auto size (%.1f GB) holds less than the CPU lane's experts (%.1f GB): the hottest are kept, the "
5012                                     "rest is read from the SSD as the prompt picks it (--ssd-cache N sets the size)\n", gb, lane_gb);
5013        }
5014        std::vector<ExpertStore::LayerGeo> geo((size_t) g.nl);   // (the trunk's layers: the drafter's bigger experts stay in place)
5015        for (const Layer& l : L) {
5016            if (l.il >= g.nl) continue;
5017            ExpertStore::LayerGeo& gl = geo[(size_t) l.il];
5018            gl.n_exp = l.n_exp;
5019            for (int r = 0; r < 3; ++r) {
5020                gl.file[r] = l.mx_file[r];
5021                gl.off[r] = l.mx_off[r];
5022                gl.stride[r] = l.mx_stride[r];
5023                gl.bytes[r] = mx_part_bytes(l, r);
5024                gl.tr[r] = l.lay.trellis[r];
5025            }
5026            gl.blob = l.blob;
5027        }
5028        ExpertStore::Cfg cfg;
5029        cfg.budget_bytes = (size_t) (gb * 1e9);
5030        cfg.threads = std::getenv("DS4_STORE_THREADS") ? std::atoi(std::getenv("DS4_STORE_THREADS")) : 8;
5031        cfg.floor_bytes = (size_t) (std::getenv("DS4_STORE_FLOOR_GB") ? std::atof(std::getenv("DS4_STORE_FLOOR_GB")) : 8.0) << 30;
5032        cfg.policy = (ExpertStore::Policy) (std::getenv("DS4_STORE_POLICY") ? std::atoi(std::getenv("DS4_STORE_POLICY")) : o.ssd_policy);
5033        cfg.ram_avail = [] { return ram_avail(); };
5034        cfg.reserve = (size_t) (std::getenv("DS4_STORE_RESERVE") ? std::atoi(std::getenv("DS4_STORE_RESERVE")) : 192);
5035        cfg.vis_percent = std::getenv("DS4_STORE_ZC_FRAC") ? std::atoi(std::getenv("DS4_STORE_ZC_FRAC")) : 50;
5036        // (the GPU computing the store's experts over PCIe is opt-in, DS4_STORE_ZC=1: measured slower than the CPU lane alone on a
5037        // 5070 / PCIe 5.0 - the staging copy sits in the layer's critical path - and its answers depend on the timing of which lane
5038        // took which expert, the CPU lane's are the mmap path's byte for byte)
5039        const bool want_zc = std::getenv("DS4_STORE_ZC") && std::atoi(std::getenv("DS4_STORE_ZC")) != 0 && devs.size() == 1 &&
5040                             L[0].nm == 1;
5041        if (want_zc) {   // the arena's chunks registered for the GPU to read in place (zero-copy over PCIe)
5042            const int dev0 = devs[0].id;
5043            {   // (a unified-memory GPU whose budget the weights already fill: the registered store is the same RAM, past the budget the GPU faults)
5044                cudaDeviceProp zp{};
5045                size_t zfree = 0, ztotal = 0;
5046                cudaSetDevice(dev0);
5047                if (cudaGetDeviceProperties(&zp, dev0) == cudaSuccess && zp.integrated && cudaMemGetInfo(&zfree, &ztotal) == cudaSuccess &&
5048                    (double) zfree < gb * 1e9)
5049                    std::fprintf(stderr,
5050                                 "ds4: DS4_STORE_ZC=1 on a GPU that shares the PC's RAM: the weights already fill its memory budget (%.1f GB left, the store would "
5051                                 "register up to %.1f GB more), so this will likely fail with a GPU fault. The store is the same RAM either way, zero-copy gains nothing here; "
5052                                 "leave DS4_STORE_ZC off.\n", (double) zfree / 1e9, gb);
5053            }
5054            cfg.map_chunk = [dev0](void* h, size_t n) -> void* {
5055                cudaSetDevice(dev0);
5056                unsigned reg_flags = cudaHostRegisterMapped | cudaHostRegisterPortable;
5057#if defined(STRATA_USE_HIP)
5058                // (test arm: DS4_ZC_COARSE=1, hipExtHostRegisterCoarseGrained, which ROCm Core SDK 10.1 honors on Windows; the store is read-only to the GPU)
5059                if (std::getenv("DS4_ZC_COARSE") && std::atoi(std::getenv("DS4_ZC_COARSE")) != 0) reg_flags |= 0x8u;
5060#endif
5061                if (cudaHostRegister(h, n, reg_flags) != cudaSuccess) {
5062                    (void) cudaGetLastError();
5063                    return nullptr;
5064                }
5065                void* d = nullptr;
5066                if (cudaHostGetDevicePointer(&d, h, 0) != cudaSuccess) {
5067                    (void) cudaGetLastError();
5068                    cudaHostUnregister(h);
5069                    return nullptr;
5070                }
5071                if (d != h) std::fprintf(stderr, "ds4: RAM store: chunk host %p -> device %p (not the identity)\n", h, d);
5072                return d;
5073            };
5074            cfg.unmap_chunk = [dev0](void* h) {
5075                cudaSetDevice(dev0);
5076                cudaHostUnregister(h);
5077            };
5078        }
5079        const char* inplace = std::getenv("DS4_STORE_INPLACE");
5080        cfg.read_in_place = !want_zc && inplace != nullptr && std::atoi(inplace) != 0;
5081        if (cfg.read_in_place) std::fprintf(stderr, "ds4: RAM store: CPU matrices kept at their aligned-read addresses\n");
5082        // DS4_STORE_PIECE_KB=n (in place only): each matrix read in pieces of n KB, so DS4_LANE_STREAM can start on the first rows
5083        cfg.piece_bytes = cfg.read_in_place && std::getenv("DS4_STORE_PIECE_KB") ? (size_t) std::atol(std::getenv("DS4_STORE_PIECE_KB")) << 10 : 0;
5084        if (cfg.piece_bytes > 0) std::fprintf(stderr, "ds4: RAM store: reads in pieces of %zu KB\n", cfg.piece_bytes >> 10);
5085        bool direct = true;
5086        for (os::fd_t f : pk.dfds) direct = direct && f != os::kBadFd;
5087        auto st = std::make_unique<ExpertStore>();
5088        if (!st->init(cfg, geo, pk.dfds, pk.pfds)) {
5089            std::fprintf(stderr, "ds4: --ssd-cache: the store could not start\n");
5090            return;
5091        }
5092        store = std::move(st);
5093        // (the router lookahead's guesses are not read ahead with the store: measured 4.5 against 4.7 tok/s, 62% of the guesses are right and
5094        // the SSD is the narrow part; DS4_AHEAD=1 turns them on)
5095        if (std::getenv("DS4_AHEAD") == nullptr) ahead_mode = 0;
5096        for (Layer& l : L)
5097            if (l.il < g.nl && want_zc) l.zc.assign((size_t) l.n_exp, 0);
5098        std::fprintf(stderr, "ds4: RAM store: up to %zu slots of %.1f MB (%.1f GB), policy %d, %d reader threads, %s reads\n",
5099                     store->slots_max(), store->slot_bytes() / 1e6, store->slots_max() * (double) store->slot_bytes() / 1e9,
5100                     (int) cfg.policy, cfg.threads, direct ? "unbuffered" : "BUFFERED (no direct handle)");
5101        if (want_zc) {
5102            if (!store->gpu_mapped()) {
5103                std::fprintf(stderr, "ds4: RAM store: the arena could not be mapped for the GPU: zero-copy off\n");
5104                for (Layer& l : L) l.zc.clear();
5105            } else {
5106                zc_stride = (store->max_blob() + 4095) & ~(size_t) 4095;
5107                cudaSetDevice(devs[0].id);
5108                if (cudaMalloc((void**) &zc_stage_buf, zc_stride * kPicks) != cudaSuccess) {
5109                    (void) cudaGetLastError();
5110                    zc_stage_buf = nullptr;
5111                    for (Layer& l : L) l.zc.clear();
5112                } else {
5113                    for (Layer& l : L)
5114                        if (!l.zc.empty() && cudaMalloc((void**) &l.zc_tab, (size_t) l.n_exp * 8) == cudaSuccess) cudaMemset(l.zc_tab, 0, (size_t) l.n_exp * 8);
5115                        else if (!l.zc.empty()) {
5116                            (void) cudaGetLastError();
5117                            l.zc.clear();
5118                        }
5119                }
5120            }
5121            std::fprintf(stderr, "ds4: RAM store: the GPU takes its slots over PCIe (%s), %zu slots kept evictable\n",
5122                         zc_stage_buf != nullptr ? "copied into a staging area at the PCIe rate first" : "off", cfg.reserve);
5123        }
5124    }
5125    // the profile's hottest experts (VRAM's left out) read into the store before the first token (DS4_STORE_PRELOAD=0: not)
5126    void preload_store() {
5127        if (!store) return;
5128        if (std::getenv("DS4_STORE_PRELOAD") && std::atoi(std::getenv("DS4_STORE_PRELOAD")) == 0) return;
5129        std::vector<std::pair<double, std::pair<int, int>>> cand;
5130        double tot = 0;
5131        for (const Layer& l : L) {
5132            if (l.il >= g.nl) continue;
5133            const uint32_t* p = prof.data() + (size_t) l.il * g.n_exp;
5134            for (int e = 0; e < l.n_exp; ++e) tot += p[e];
5135        }
5136        if (tot <= 0) return;   // (no profile yet: the first tokens fill it)
5137        for (const Layer& l : L) {
5138            if (l.il >= g.nl) continue;
5139            const uint32_t* p = prof.data() + (size_t) l.il * g.n_exp;
5140            for (int e = 0; e < l.n_exp; ++e)
5141                if (l.slot[(size_t) e] < 0 && p[e] > 0 && (l.aux.empty() || !l.aux[(size_t) e]))
5142                    cand.push_back({(double) p[e] / (double) l.blob, {l.il, e}});
5143        }
5144        std::stable_sort(cand.begin(), cand.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
5145        std::vector<std::pair<int, int>> list;
5146        list.reserve(cand.size());
5147        for (const auto& c : cand) list.push_back(c.second);
5148        const double t0 = now_ms();
5149        const size_t leave = (size_t) (std::getenv("DS4_STORE_RESERVE") ? std::atoi(std::getenv("DS4_STORE_RESERVE")) : 192) + 64;
5150        // The first 48 GB (what a store held before it could take every expert) are read before the first token; the rest of the
5151        // hottest-first list is read after it, in pieces of 128 experts on a thread of its own, behind the model's own reads (a
5152        // guess's priority) - the same bytes.  Opt-in (DS4_STORE_BG=1): "ready" comes 9 s sooner on the 251 GB R9700 box (24 s against 34), but a prompt sent at
5153        // once then waits for the same SSD (200 tokens: 18.7 s against 9.0), so the first answer starts no sooner and decode after
5154        // it measured 3.7% lower; it only pays when the first prompt comes more than ~10 s after ready.
5155        const size_t first = !(std::getenv("DS4_STORE_BG") && std::atoi(std::getenv("DS4_STORE_BG")) == 1)
5156                                 ? list.size()
5157                                 : std::min(list.size(), (size_t) (48e9 / (double) std::max<size_t>(1, L[0].blob)));
5158        const std::vector<std::pair<int, int>> head(list.begin(), list.begin() + (long) first), tail(list.begin() + (long) first, list.end());
5159        const size_t n = store->preload(head, leave);
5160        std::fprintf(stderr, "ds4: RAM store: %zu of the profile's hottest experts read in (%.1f GB) in %.1f s%s\n", n,
5161                     (double) n * (double) L[0].blob / 1e9, (now_ms() - t0) / 1000.0,
5162                     tail.empty() ? "" : "; the rest is read in the background");
5163        if (tail.empty()) return;
5164        store_bg = std::thread([this, tail, leave] {
5165            const double tb = now_ms();
5166            size_t got = 0;
5167            std::vector<std::pair<int, int>> piece;
5168            for (size_t i = 0; i < tail.size() && !quit.load(std::memory_order_relaxed); i += 128) {
5169                piece.assign(tail.begin() + (long) i, tail.begin() + (long) std::min(tail.size(), i + 128));
5170                got += store->preload(piece, leave);
5171            }
5172            std::fprintf(stderr, "ds4: RAM store: %zu more experts (%.1f GB) read in the background in %.1f s\n", got,
5173                         (double) got * (double) L[0].blob / 1e9, (now_ms() - tb) / 1000.0);
5174        });
5175    }
5176    // at a window boundary: the store's ready slots become the device's (zero-copy) experts, taken back when it needs the room;
5177    // each touched layer's whole table is written again (VRAM slots, the store's, 0), in stream order before the next window
5178    void store_sync() {
5179        if (!store || !store->gpu_mapped()) return;
5180        // DS4_STORE_ZC_DET=1: every read in flight lands first, so the GPU's share is the same run after run (the two lanes
5181        // round differently; without it the drives' timing decides which lane computes an expert)
5182        static const bool det = std::getenv("DS4_STORE_ZC_DET") != nullptr && std::atoi(std::getenv("DS4_STORE_ZC_DET")) != 0;
5183        if (det) store->drain();
5184        std::vector<ExpertStore::Vis> ev;
5185        store->sync(ev, [&](int layer, int e) { return L[(size_t) layer].slot[(size_t) e] < 0; });
5186        if (ev.empty()) return;
5187        std::vector<char> dirty(L.size(), 0);
5188        for (const auto& v : ev) {
5189            Layer& l = L[(size_t) v.layer];
5190            if (l.zc.empty()) continue;
5191            l.zc[(size_t) v.e] = v.dev != 0 ? 1 : 0;
5192            dirty[(size_t) v.layer] = 1;
5193        }
5194        for (Layer& l : L) {
5195            if (!dirty[(size_t) l.il]) continue;
5196            if (l.zc_tab == nullptr) continue;
5197            std::vector<unsigned long long> tab((size_t) l.n_exp, 0ull);
5198            for (int e = 0; e < l.n_exp; ++e)
5199                if (l.zc[(size_t) e]) {
5200                    const int s = l.slot[(size_t) e] < 0 ? store->find(l.il, e) : -1;
5201                    tab[(size_t) e] = s >= 0 ? store->dev_blob(s) : 0ull;
5202                    if (s < 0) l.zc[(size_t) e] = 0;
5203                }
5204            cudaSetDevice(devs[0].id);
5205            cudaMemcpyAsync(l.zc_tab, tab.data(), tab.size() * 8, cudaMemcpyHostToDevice, devs[0].st);
5206        }
5207    }
5208
5209    int cpu_threads() const {
5210        int n = 0;
5211        for (const auto& pl : pools) n += pl->size() - 1;
5212        return n + 1;
5213    }
5214    // the CPU lane's workers: a pool per NUMA node (NH of them) on its cores; in place with one part, one pool over
5215    // every node's cores (the pages lie where the cache put them)
5216    void make_pools() {
5217        std::vector<std::vector<int>> cs = cores;
5218        if ((int) cs.size() < NH && !cs.empty()) {   // (DS4_COPY_NUMA=2 on one node, a test: its cores split in NH)
5219            std::vector<int> all = cs[0];
5220            cs.assign((size_t) NH, {});
5221            for (size_t i = 0; i < all.size(); ++i) cs[i * (size_t) NH / all.size()].push_back(all[i]);
5222        }
5223        static const int lane_free = [] {
5224            const char* v = std::getenv("STRATA_DS4_LANE_FREE");
5225            return v != nullptr ? std::max(0, std::atoi(v)) : 2;
5226        }();
5227        size_t lane_cpus = 0;
5228        for (const auto& v : cs) lane_cpus += v.size();
5229        const bool lane_takes_all = lane_cpus >= (size_t) std::max(1u, std::thread::hardware_concurrency());
5230        for (int X = 0; X < (int) cs.size() && X < std::max(NH, 1); ++X) {
5231            std::vector<int> c = cs[(size_t) X];
5232            if (file_experts && NH == 1)
5233                for (size_t Y = 1; Y < cs.size(); ++Y) c.insert(c.end(), cs[Y].begin(), cs[Y].end());
5234            if (X == 0 && !c.empty()) c.erase(c.begin());   // the host thread's core (it helps node 0's pool)
5235            // cores of the first pool left free beside the host thread's, for the thread that launches the decode's kernels
5236            // (and waits on the device) and whatever else the PC runs: with a worker spinning on every other logical CPU
5237            // that thread waits for a core (Project Maya #359, a 20-core Windows 11 PC: decode 28.3 -> 55.5 tok/s).  Only
5238            // when the lane would take every logical CPU and --cpu-threads is not given.
5239            // STRATA_DS4_LANE_FREE: the cores left free (2 by default, 0: as before)
5240            if (X == 0 && o.cpu_threads <= 0 && lane_free > 0 && (int) c.size() > lane_free + 1 && lane_takes_all)
5241                c.resize(c.size() - (size_t) lane_free);
5242            int nw = (int) c.size();
5243            if (o.cpu_threads > 0) nw = std::max(X == 0 ? 0 : 1, std::min(nw, o.cpu_threads / NH - (X == 0 ? 1 : 0)));
5244            pools.push_back(std::make_unique<Pool>(nw, c, 20000));   // spin through a token's layers (20 ms)
5245        }
5246        (void) gg::mx_tier();   // (measured here, not on the first token)
5247        if (o.verbose) {
5248            int nthr = 0;
5249            for (auto& p : pools) nthr += p->size();
5250            std::fprintf(stderr, "ds4: CPU lane: %d threads, MXFP4 rows %s (%s)\n", nthr, gg::mx_tier_name(gg::mx_tier()),
5251                         gg::mx_tier_report());
5252        }
5253    }
5254
5255    int scr_relocate(const std::vector<Model::ScrMove>& moves, std::string& err) {
5256        if (!scr_master || devs.size() != 1 || moves.empty() || g.win != 128 ||
5257            g.rd <= 0 || g.rd % 32 != 0 || spec_win || (int64_t) toks.size() != pos) return 0;
5258        for (const Src& sr : srcs)
5259            if (sr.remote || sr.ratio < 1 || sr.ratio > 2) return 0;
5260        int64_t end = 0;
5261        for (const auto& m : moves) {
5262            if (m.old_start < 0 || m.at < end || m.n <= 0 || (m.old_start | m.at | m.n) % 2 ||
5263                m.old_start > pos - m.n || m.at > o.max_context - m.n) return 0;
5264            end = m.at + m.n;
5265        }
5266        Dev& d = devs[0];
5267        cudaSetDevice(d.id);
5268        struct Stage {
5269            uint8_t *packed = nullptr, *tail = nullptr, *dst = nullptr, *valid = nullptr;
5270            float *master = nullptr, *out_master = nullptr;
5271            int n = 0, len = 0, fmt = 0, at = 0, step = 1;
5272        };
5273        struct Stages {
5274            std::vector<Stage> rows;
5275            ~Stages() { for (auto& s : rows) { cudaFree(s.packed); cudaFree(s.tail); cudaFree(s.master); } }
5276        } staged;
5277        auto checked = [&](cudaError_t e) {
5278            if (e == cudaSuccess) return true;
5279            err = cudaGetErrorString(e);
5280            return false;
5281        };
5282        // All allocations, source reads and master-validity checks precede the first destination write.
5283        for (Src& sr : srcs) for (const auto& m : moves) for (int fmt : {kKvFp4, kKvFp4p}) {
5284            auto& caches = fmt == kKvFp4 ? sr.ckv : sr.ik;
5285            if (caches[0] == nullptr) continue;
5286            auto& masters = fmt == kKvFp4 ? sr.master : sr.master_ik;
5287            auto& validity = fmt == kKvFp4 ? sr.master_valid : sr.master_ik_valid;
5288            if (masters.empty() || masters[0] == nullptr) return 0;
5289            const size_t first = (size_t) (m.old_start / sr.ratio), at = (size_t) (m.at / sr.ratio);
5290            const int n = (int) (m.n / sr.ratio), len = fmt == kKvFp4 ? g.hd : g.ix_hd;
5291            if (len % 32 != 0 || len < g.rd) return 0;
5292            const size_t rb = kv_row_bytes(fmt, len), mb = (size_t) n * g.rd * sizeof(float);
5293            std::vector<uint8_t> valid((size_t) n);
5294            if (!checked(cudaMemcpyAsync(valid.data(), validity[0] + first, valid.size(), cudaMemcpyDeviceToHost, d.st)) ||
5295                !checked(cudaStreamSynchronize(d.st))) return 0;
5296            if (std::find(valid.begin(), valid.end(), 0) != valid.end()) return 0;
5297            staged.rows.emplace_back();
5298            Stage& s = staged.rows.back();
5299            s.n = n; s.len = len; s.fmt = fmt; s.at = (int) m.at; s.step = sr.ratio;
5300            s.dst = caches[0] + at * rb;
5301            s.out_master = masters[0] + at * g.rd;
5302            s.valid = validity[0] + at;
5303            if (!checked(cudaMalloc((void**) &s.packed, (size_t) n * rb)) ||
5304                !checked(cudaMalloc((void**) &s.master, mb)) ||
5305                !checked(cudaMalloc((void**) &s.tail, (size_t) n * kv_row_bytes(fmt, g.rd))) ||
5306                !checked(cudaMemcpyAsync(s.packed, caches[0] + first * rb, (size_t) n * rb, cudaMemcpyDeviceToDevice, d.st)) ||
5307                !checked(cudaMemcpyAsync(s.master, masters[0] + first * g.rd, mb, cudaMemcpyDeviceToDevice, d.st))) return 0;
5308        }
5309        if (!checked(cudaStreamSynchronize(d.st))) return 0;
5310        slot_held = false;
5311        scr_derived = true;
5312        for (Stage& s : staged.rows) {
5313            scr_repack(s.packed, s.master, s.tail, s.dst, s.n, s.len, g.rd, s.fmt,
5314                       s.at, s.step, d.freqs_comp, d.st);
5315            if (!checked(cudaGetLastError()) ||
5316                !checked(cudaMemcpyAsync(s.out_master, s.master, (size_t) s.n * g.rd * sizeof(float), cudaMemcpyDeviceToDevice, d.st)) ||
5317                !checked(cudaMemsetAsync(s.valid, 1, (size_t) s.n, d.st))) return -1;
5318        }
5319        return checked(cudaStreamSynchronize(d.st)) ? 1 : -1;
5320    }
5321
5322    // SCR: the state jumps to position `at` of `ids` (an even position whose compressed rows are all in place - the
5323    // prefix's, or a relocated run's): the tokens up to it adopted, every window ring and compressor partial group
5324    // emptied, and the window rows before `at` left out of the attention until the read is a window past it (the
5325    // junction band: its tokens see the compressed rows, and each other)
5326    bool scr_jump(const std::vector<int>& ids, int64_t at, std::string& err, int64_t keep = 0) {
5327        if (!scr_master || devs.size() != 1 || at < 0 || at > (int64_t) ids.size() || at % 2) {
5328            err = "invalid SCR jump";
5329            return false;
5330        }
5331        pos = at;
5332        toks.assign(ids.begin(), ids.begin() + at);
5333        ctoks.resize((size_t) at);
5334        for (int64_t i = 0; i < at; ++i) ctoks[(size_t) i] = ctok(i, toks[(size_t) i]);
5335        // (a checkpoint up to `keep` - the prompt's shared start: its tokens and rows unchanged - stays, a pinned
5336        //  system prompt's among them)
5337        for (Check& c : ck)
5338            if (c.pos > std::min(keep, at)) c.pos = -1;
5339        slot_held = false;
5340        spec_win = false;
5341        n_logits = 0;
5342        scr_band_start = at > 0 ? at : -1;
5343        for (Layer& l : L) {
5344            Dev& d = devs[(size_t) l.dev];
5345            cudaSetDevice(d.id);
5346            cudaMemsetAsync(l.win, 0, (size_t) g.win * win_rb(), d.st);
5347            if (l.c_kv) cudaMemsetAsync(l.c_kv, 0, (size_t) l.ratio * g.hd * 4, d.st);
5348            if (l.c_score) cudaMemsetAsync(l.c_score, 0, (size_t) l.ratio * g.hd * 4, d.st);
5349        }
5350        cudaStreamSynchronize(devs[0].st);
5351        return true;
5352    }
5353
5354    void clear_scr_masters() {
5355        if (!scr_master) return;
5356        for (Src& sr : srcs) for (size_t di = 0; di < devs.size(); ++di) {
5357            cudaSetDevice(devs[di].id);
5358            if (sr.master_valid[di]) cudaMemsetAsync(sr.master_valid[di], 0, (size_t) sr.cap, devs[di].st);
5359            if (sr.master_ik_valid[di]) cudaMemsetAsync(sr.master_ik_valid[di], 0, (size_t) sr.cap, devs[di].st);
5360        }
5361    }
5362
5363    void reset() {
5364        clear_scr_masters();
5365        scr_derived = false;
5366        scr_band_start = -1;
5367        pos = 0;
5368        toks.clear();
5369        ctoks.clear();
5370        slot_held = false;
5371        for (Check& c0 : ck) c0.pos = -1;
5372        for (Layer& l0 : L)
5373            for (int m = 0; m < l0.nm; ++m) {
5374                Layer& l = member(l0, m);
5375                Dev& d = devs[(size_t) l.dev];
5376                cudaSetDevice(d.id);
5377                cudaMemsetAsync(l.win, 0, (size_t) g.win * win_rb(), d.st);
5378                if (l.c_kv) cudaMemsetAsync(l.c_kv, 0, (size_t) l.ratio * g.hd * 4, d.st);
5379                if (l.c_score) cudaMemsetAsync(l.c_score, 0, (size_t) l.ratio * g.hd * 4, d.st);
5380            }
5381        for (Dev& d : devs) {
5382            cudaSetDevice(d.id);
5383            cudaStreamSynchronize(d.st);
5384        }
5385    }
5386
5387    // the state at pos into checkpoint `slot` (the window rings and the compressors' partial groups: the rest of the
5388    // state is indexed by position, and what lies past a restored position is written again)
5389    void checkpoint(int slot) {
5390        Check& c = ck[slot & (kChecks - 1)];
5391        c.pos = pos;
5392        c.win.resize(L.size());
5393        c.comp.resize(L.size() * 2);
5394        for (size_t i = 0; i < L.size(); ++i) {
5395            Layer& l = L[i];
5396            Dev& d = devs[(size_t) l.dev];
5397            cudaSetDevice(d.id);
5398            c.win[i].resize((size_t) g.win * win_rb());
5399            cudaMemcpyAsync(c.win[i].data(), l.win, c.win[i].size(), cudaMemcpyDeviceToHost, d.st);
5400            if (l.c_kv) {
5401                c.comp[2 * i].resize((size_t) l.ratio * g.hd);
5402                c.comp[2 * i + 1].resize((size_t) l.ratio * g.hd);
5403                cudaMemcpyAsync(c.comp[2 * i].data(), l.c_kv, c.comp[2 * i].size() * 4, cudaMemcpyDeviceToHost, d.st);
5404                cudaMemcpyAsync(c.comp[2 * i + 1].data(), l.c_score, c.comp[2 * i + 1].size() * 4,
5405                                cudaMemcpyDeviceToHost, d.st);
5406            }
5407        }
5408        for (Dev& d : devs) {
5409            cudaSetDevice(d.id);
5410            cudaStreamSynchronize(d.st);
5411        }
5412    }
5413
5414    // the checkpoint at or before position limit (the state's tokens agree with a new prompt up to there), or -1
5415    int best_check(int64_t limit) const {
5416        int b = -1;
5417        for (int i = 0; i < kChecks; ++i)
5418            if (ck[i].pos >= 0 && ck[i].pos <= limit && ck[i].pos <= pos && (b < 0 || ck[i].pos > ck[b].pos)) b = i;
5419        return b;
5420    }
5421    int64_t restorable(int64_t limit) const {
5422        const int b = best_check(limit);
5423        return b < 0 ? -1 : ck[b].pos;
5424    }
5425
5426    // checkpoint 1 (the position before the last prompt's end) becomes the anchor too
5427    void pin() {
5428        if (ck[1].pos > 0) ck[2] = ck[1];
5429    }
5430    // the checkpoints the state can go back to (what a slot of it keeps), latest first
5431    std::vector<int64_t> check_positions() const {
5432        std::vector<int64_t> v;
5433        for (const Check& c : ck)
5434            if (c.pos > 0 && c.pos <= pos && c.win.size() == L.size() &&
5435                std::find(v.begin(), v.end(), c.pos) == v.end())
5436                v.push_back(c.pos);
5437        std::sort(v.rbegin(), v.rend());
5438        return v;
5439    }
5440    // the checkpoints a slot keeps (each with its role: 0, 1 or the anchor)
5441    std::vector<int> slot_checks() const {
5442        std::vector<int> v;
5443        for (int i = 0; i < kChecks; ++i)
5444            if (ck[i].pos > 0 && ck[i].pos <= pos && ck[i].win.size() == L.size()) v.push_back(i);
5445        return v;
5446    }
5447    size_t check_bytes() const {
5448        size_t n = 16;
5449        for (const Layer& l : L) n += (size_t) g.win * win_rb() + (l.c_kv ? 2 * (size_t) l.ratio * g.hd * 4 : 0);
5450        return n;
5451    }
5452
5453    bool restore(int64_t limit) {
5454        const int b = best_check(limit);
5455        if (b < 0) return false;
5456        const Check& c = ck[b];
5457        for (size_t i = 0; i < L.size(); ++i)
5458            for (int m = 0; m < L[i].nm; ++m) {   // (a group's members hold the same state: the lead's copy)
5459                Layer& l = member(L[i], m);
5460                Dev& d = devs[(size_t) l.dev];
5461                cudaSetDevice(d.id);
5462                cudaMemcpyAsync(l.win, c.win[i].data(), c.win[i].size(), cudaMemcpyHostToDevice, d.st);
5463                if (l.c_kv) {
5464                    cudaMemcpyAsync(l.c_kv, c.comp[2 * i].data(), c.comp[2 * i].size() * 4, cudaMemcpyHostToDevice, d.st);
5465                    cudaMemcpyAsync(l.c_score, c.comp[2 * i + 1].data(), c.comp[2 * i + 1].size() * 4,
5466                                    cudaMemcpyHostToDevice, d.st);
5467                }
5468            }
5469        for (Dev& d : devs) {
5470            cudaSetDevice(d.id);
5471            cudaStreamSynchronize(d.st);
5472        }
5473        pos = c.pos;
5474        toks.resize((size_t) pos);
5475        ctoks.resize((size_t) pos);
5476        slot_held = false;
5477        if (scr_band_start > pos) scr_band_start = -1;   // (an SCR junction the state went back before)
5478        for (Check& o2 : ck)   // a later checkpoint saw tokens the state no longer has
5479            if (o2.pos > pos) o2.pos = -1;
5480        return true;
5481    }
5482
5483    // ---- the kept conversations (a slot): the state out of the model and back, through a file or a host buffer.
5484    // A prompt that continues the state is reused in place (checkpoint / restore, the compressed KV left where it is);
5485    // a conversation that leaves the model for another one is a slot - the whole state: the position, its tokens,
5486    // every window ring (the DSpark blocks' included), the compressors' partial groups and each KV source's compressed
5487    // KV and index keys up to it (rows 0 .. pos / ratio, the groups its position completed; one the prompt has not
5488    // completed yet lives in the compressor's partial group).  A tensor parallel group's members hold the same state,
5489    // so one member's ring is saved and written back into all of them.  Text only: a conversation that holds pictures
5490    // is not a slot (the Engram history's rows are the tokens' again, no -1 among them).
5491    static constexpr uint64_t kSlotMagic = 0x31544f4c53345344ull;   // "DS4SLOT1" (little endian)
5492
5493    int64_t src_rows(const Src& s) const { return pos / std::max(1, s.ratio); }
5494
5495    // the slot's bytes: the header, the tokens, every layer's ring and partial group, every source's rows, the end
5496    size_t slot_bytes() const {
5497        size_t n = 8 + 8 + slot_identity().size() + 8 + (size_t) pos * 4;
5498        for (const Layer& l : L) n += 8 + (size_t) g.win * win_rb() + 8 + (l.c_kv ? 2 * (size_t) l.ratio * g.hd * 4 : 0);
5499        for (const Src& s : srcs) n += 8 + (size_t) src_rows(s) * (ckv_rb() + ik_rb());
5500        n += 8 + slot_checks().size() * check_bytes();   // (the checkpoints: what the slot can be taken back at)
5501        if (scr_master) n += 16 + scr_master_bytes();   // (SCR: its flags, then every source's pre-RoPE masters)
5502        return n + 8;
5503    }
5504
5505    // SCR's part of a slot: per source, its rows' masters and their valid flags (compressed KV, then index keys)
5506    size_t scr_master_bytes() const { return scr_master_bytes_at(pos); }
5507
5508    uint64_t slot_save(std::vector<uint8_t>& out, std::string& err) {
5509        if (slot_held) {
5510            err = "it is already set aside";
5511            return 0;
5512        }
5513        if (pos <= 0) {
5514            err = "there is no conversation";
5515            return 0;
5516        }
5517        if ((int64_t) toks.size() != pos) {
5518            err = "the state's tokens do not match its position";
5519            return 0;
5520        }
5521        if (!imgs.empty()) {
5522            err = "it holds pictures";
5523            return 0;
5524        }
5525        const std::string id = slot_identity();
5526        out.assign(slot_bytes(), 0);
5527        uint8_t* p = out.data();
5528        size_t off = 0;
5529        const auto put = [&](const void* s, size_t b) {
5530            std::memcpy(p + off, s, b);
5531            off += b;
5532        };
5533        const uint64_t il = id.size(), n = (uint64_t) pos;
5534        put(&kSlotMagic, 8);
5535        put(&il, 8);
5536        put(id.data(), (size_t) il);
5537        put(&n, 8);
5538        put(toks.data(), (size_t) n * 4);
5539        for (Dev& d : devs) {   // (the devices' work ends before their state is read)
5540            cudaSetDevice(d.id);
5541            cudaStreamSynchronize(d.st);
5542        }
5543        for (size_t i = 0; i < L.size(); ++i) {
5544            const Layer& l = L[i];
5545            const Dev& d = devs[(size_t) l.dev];
5546            cudaSetDevice(d.id);
5547            const uint64_t wb = (uint64_t) g.win * win_rb();
5548            put(&wb, 8);
5549            if (cudaMemcpy(p + off, l.win, (size_t) wb, cudaMemcpyDeviceToHost) != cudaSuccess) {
5550                err = l.name + "window ring: " + cudaGetErrorString(cudaGetLastError());
5551                return 0;
5552            }
5553            off += (size_t) wb;
5554            const uint64_t cn = l.c_kv ? (uint64_t) l.ratio * (uint64_t) g.hd : 0;
5555            put(&cn, 8);
5556            if (cn > 0) {
5557                const size_t cb = (size_t) cn * 4;
5558                if (cudaMemcpy(p + off, l.c_kv, cb, cudaMemcpyDeviceToHost) != cudaSuccess ||
5559                    cudaMemcpy(p + off + cb, l.c_score, cb, cudaMemcpyDeviceToHost) != cudaSuccess) {
5560                    err = l.name + "compressor's group: " + cudaGetErrorString(cudaGetLastError());
5561                    return 0;
5562                }
5563                off += 2 * cb;
5564            }
5565        }
5566        for (const Src& s : srcs) {
5567            const uint64_t rows = (uint64_t) src_rows(s);
5568            put(&rows, 8);
5569            if (rows == 0) continue;
5570            const int di = L[(size_t) s.layer].dev;
5571            const uint8_t* ckv = s.ckv[(size_t) di];
5572            const uint8_t* ik = s.ik[(size_t) di];   // (a pack whose sources are not index sources: none, zeros)
5573            if (ckv == nullptr) {
5574                err = "source layer " + std::to_string(s.layer) + "'s rows are not on its device";
5575                return 0;
5576            }
5577            const size_t cb = (size_t) rows * ckv_rb(), ib = (size_t) rows * ik_rb();
5578            cudaSetDevice(devs[(size_t) di].id);
5579            if (cudaMemcpy(p + off, ckv, cb, cudaMemcpyDeviceToHost) != cudaSuccess ||
5580                (ik != nullptr && cudaMemcpy(p + off + cb, ik, ib, cudaMemcpyDeviceToHost) != cudaSuccess)) {
5581                err = "source layer " + std::to_string(s.layer) + "'s compressed KV: " + cudaGetErrorString(cudaGetLastError());
5582                return 0;
5583            }
5584            off += cb + ib;
5585        }
5586        {
5587            const std::vector<int> cs = slot_checks();
5588            const uint64_t nc = cs.size();
5589            put(&nc, 8);
5590            for (int k : cs) {
5591                const Check& c = ck[k];
5592                const uint64_t role = (uint64_t) k, cp = (uint64_t) c.pos;
5593                put(&role, 8);
5594                put(&cp, 8);
5595                for (size_t i = 0; i < L.size(); ++i) {
5596                    put(c.win[i].data(), (size_t) g.win * win_rb());
5597                    if (L[i].c_kv) {
5598                        put(c.comp[2 * i].data(), (size_t) L[i].ratio * g.hd * 4);
5599                        put(c.comp[2 * i + 1].data(), (size_t) L[i].ratio * g.hd * 4);
5600                    }
5601                }
5602            }
5603        }
5604        if (scr_master) {   // (host-mapped: a plain copy, after the devices' work ended above)
5605            const uint64_t derived = scr_derived ? 1 : 0;
5606            const int64_t band = scr_band_start;
5607            put(&derived, 8);
5608            put(&band, 8);
5609            for (const Src& s : srcs) {
5610                const int di = L[(size_t) s.layer].dev;
5611                const size_t rows = (size_t) src_rows(s);
5612                const std::pair<const float*, const uint8_t*> ms[2] = {{s.master[(size_t) di], s.master_valid[(size_t) di]},
5613                                                                      {s.master_ik[(size_t) di], s.master_ik_valid[(size_t) di]}};
5614                for (const auto& mv : ms) {
5615                    if (mv.first == nullptr) continue;
5616                    put(mv.first, rows * (size_t) g.rd * sizeof(float));
5617                    put(mv.second, rows);
5618                }
5619            }
5620        }
5621        if (off + 8 != out.size()) {
5622            err = "the state's size does not add up";
5623            return 0;
5624        }
5625        put(&kSlotMagic, 8);
5626        slot_held = true;
5627        return (uint64_t) off;
5628    }
5629
5630    bool slot_load(const uint8_t* data, size_t bytes, int64_t n_pos, std::string& err) {
5631        clear_scr_masters();
5632        size_t off = 0;
5633        bool wrote = false, ok = false;
5634        // a load that stops after some of another conversation's state went into the layers leaves a state no
5635        // checkpoint can repair: it is reset (the prompt is read from token 0), never served from the mix
5636        struct FailClosed {
5637            Impl& p;
5638            const bool& wrote;
5639            const bool& ok;
5640            ~FailClosed() {
5641                if (!ok && wrote) p.reset();
5642            }
5643        } guard{*this, wrote, ok};
5644        const auto room = [&](size_t b) { return b <= bytes && off <= bytes - b; };
5645        uint64_t magic = 0, il = 0, n = 0;
5646        if (!room(16)) {
5647            err = "the slot is cut short";
5648            return false;
5649        }
5650        std::memcpy(&magic, data + off, 8);
5651        std::memcpy(&il, data + off + 8, 8);
5652        off += 16;
5653        if (magic != kSlotMagic || il == 0 || il > (1u << 20)) {
5654            err = "not a saved conversation";
5655            return false;
5656        }
5657        if (!room((size_t) il + 8)) {
5658            err = "the slot is cut short";
5659            return false;
5660        }
5661        {
5662            std::string id((size_t) il, '\0');
5663            std::memcpy(id.data(), data + off, (size_t) il);
5664            off += (size_t) il;
5665            std::memcpy(&n, data + off, 8);
5666            off += 8;
5667            if (id != slot_identity()) {
5668                err = "another model's, or another engine version's, conversation";
5669                return false;
5670            }
5671        }
5672        if (n != (uint64_t) n_pos || n_pos <= 0 || n_pos > o.max_context || !room((size_t) n * 4)) {
5673            err = "the conversation's position is not this prompt's";
5674            return false;
5675        }
5676        std::vector<int32_t> toks_in((size_t) n);
5677        std::memcpy(toks_in.data(), data + off, (size_t) n * 4);
5678        off += (size_t) n * 4;
5679        for (Dev& d : devs) {   // (their work ends before the state is written over)
5680            cudaSetDevice(d.id);
5681            cudaStreamSynchronize(d.st);
5682        }
5683        for (size_t i = 0; i < L.size(); ++i) {
5684            Layer& l = L[i];
5685            const Dev& d = devs[(size_t) l.dev];
5686            cudaSetDevice(d.id);
5687            uint64_t wb = 0, cn = 0;
5688            if (!room(8)) {
5689                err = "the slot is cut short";
5690                return false;
5691            }
5692            std::memcpy(&wb, data + off, 8);
5693            off += 8;
5694            if (wb != (uint64_t) g.win * win_rb() || !room((size_t) wb + 8)) {
5695                err = l.name + "window ring of another size";
5696                return false;
5697            }
5698            wrote = true;
5699            for (int m = 0; m < l.nm; ++m) {
5700                Layer& lm = member(l, m);
5701                if (cudaMemcpy(lm.win, data + off, (size_t) wb, cudaMemcpyHostToDevice) != cudaSuccess) {
5702                    err = l.name + "window ring: " + cudaGetErrorString(cudaGetLastError());
5703                    return false;
5704                }
5705            }
5706            off += (size_t) wb;
5707            std::memcpy(&cn, data + off, 8);
5708            off += 8;
5709            if (cn != (l.c_kv ? (uint64_t) l.ratio * (uint64_t) g.hd : 0)) {
5710                err = l.name + "compressor's group of another size";
5711                return false;
5712            }
5713            if (cn > 0) {
5714                const size_t cb = (size_t) cn * 4;
5715                if (!room(2 * cb)) {
5716                    err = "the slot is cut short";
5717                    return false;
5718                }
5719                for (int m = 0; m < l.nm; ++m) {
5720                    Layer& lm = member(l, m);
5721                    if (cudaMemcpy(lm.c_kv, data + off, cb, cudaMemcpyHostToDevice) != cudaSuccess ||
5722                        cudaMemcpy(lm.c_score, data + off + cb, cb, cudaMemcpyHostToDevice) != cudaSuccess) {
5723                        err = l.name + "compressor's group: " + cudaGetErrorString(cudaGetLastError());
5724                        return false;
5725                    }
5726                }
5727                off += 2 * cb;
5728            }
5729        }
5730        for (const Src& s : srcs) {
5731            uint64_t rows = 0;
5732            if (!room(8)) {
5733                err = "the slot is cut short";
5734                return false;
5735            }
5736            std::memcpy(&rows, data + off, 8);
5737            off += 8;
5738            if (rows != (uint64_t) (n_pos / std::max(1, s.ratio))) {
5739                err = "source layer " + std::to_string(s.layer) + "'s rows are not this conversation's";
5740                return false;
5741            }
5742            if (rows == 0) continue;
5743            const size_t cb = (size_t) rows * ckv_rb(), ib = (size_t) rows * ik_rb();
5744            if (!room(cb + ib)) {
5745                err = "the slot is cut short";
5746                return false;
5747            }
5748            for (size_t di = 0; di < devs.size(); ++di) {
5749                if (s.ckv[di] == nullptr && s.ik[di] == nullptr) continue;
5750                cudaSetDevice(devs[di].id);
5751                if (s.ckv[di] != nullptr && cudaMemcpy(s.ckv[di], data + off, cb, cudaMemcpyHostToDevice) != cudaSuccess) {
5752                    err = "source layer " + std::to_string(s.layer) + "'s compressed KV: " + cudaGetErrorString(cudaGetLastError());
5753                    return false;
5754                }
5755                if (s.ik[di] != nullptr &&
5756                    cudaMemcpy(s.ik[di], data + off + cb, ib, cudaMemcpyHostToDevice) != cudaSuccess) {
5757                    err = "source layer " + std::to_string(s.layer) + "'s index keys: " + cudaGetErrorString(cudaGetLastError());
5758                    return false;
5759                }
5760            }
5761            off += cb + ib;
5762        }
5763        Check got[kChecks];   // the slot's checkpoints: the positions it can be taken back at
5764        {
5765            uint64_t nc = 0;
5766            if (!room(8)) {
5767                err = "the slot is cut short";
5768                return false;
5769            }
5770            std::memcpy(&nc, data + off, 8);
5771            off += 8;
5772            if (nc > (uint64_t) kChecks) {
5773                err = "the slot's checkpoints are damaged";
5774                return false;
5775            }
5776            for (uint64_t k = 0; k < nc; ++k) {
5777                uint64_t role = 0, cp = 0;
5778                if (!room(16)) {
5779                    err = "the slot is cut short";
5780                    return false;
5781                }
5782                std::memcpy(&role, data + off, 8);
5783                std::memcpy(&cp, data + off + 8, 8);
5784                off += 16;
5785                if (role >= (uint64_t) kChecks || got[role].pos >= 0 || cp == 0 || cp > (uint64_t) n_pos) {
5786                    err = "the slot's checkpoints are damaged";
5787                    return false;
5788                }
5789                Check& c = got[role];
5790                c.pos = (int64_t) cp;
5791                c.win.resize(L.size());
5792                c.comp.resize(L.size() * 2);
5793                for (size_t i = 0; i < L.size(); ++i) {
5794                    const size_t wb = (size_t) g.win * win_rb(), cb = L[i].c_kv ? (size_t) L[i].ratio * g.hd * 4 : 0;
5795                    if (!room(wb + 2 * cb)) {
5796                        err = "the slot is cut short";
5797                        return false;
5798                    }
5799                    c.win[i].assign(data + off, data + off + wb);
5800                    off += wb;
5801                    if (cb > 0) {
5802                        c.comp[2 * i].resize(cb / 4);
5803                        c.comp[2 * i + 1].resize(cb / 4);
5804                        std::memcpy(c.comp[2 * i].data(), data + off, cb);
5805                        std::memcpy(c.comp[2 * i + 1].data(), data + off + cb, cb);
5806                        off += 2 * cb;
5807                    }
5808                }
5809            }
5810        }
5811        bool derived = false;
5812        int64_t band = -1;
5813        if (scr_master) {
5814            uint64_t dv = 0;
5815            if (!room(16 + scr_master_bytes_at(n_pos))) {
5816                err = "the slot is cut short";
5817                return false;
5818            }
5819            std::memcpy(&dv, data + off, 8);
5820            std::memcpy(&band, data + off + 8, 8);
5821            off += 16;
5822            derived = dv != 0;
5823            for (const Src& s : srcs) {
5824                const int di = L[(size_t) s.layer].dev;
5825                const size_t rows = (size_t) (n_pos / std::max(1, s.ratio));
5826                const std::pair<float*, uint8_t*> ms[2] = {{s.master[(size_t) di], s.master_valid[(size_t) di]},
5827                                                          {s.master_ik[(size_t) di], s.master_ik_valid[(size_t) di]}};
5828                for (const auto& mv : ms) {
5829                    if (mv.first == nullptr) continue;
5830                    std::memcpy(mv.first, data + off, rows * (size_t) g.rd * sizeof(float));
5831                    off += rows * (size_t) g.rd * sizeof(float);
5832                    std::memcpy(mv.second, data + off, rows);
5833                    off += rows;
5834                }
5835            }
5836        }
5837        uint64_t end = 0;
5838        if (!room(8)) {
5839            err = "the slot is cut short";
5840            return false;
5841        }
5842        std::memcpy(&end, data + off, 8);
5843        off += 8;
5844        if (end != kSlotMagic) {
5845            err = "the slot does not end where it should";
5846            return false;
5847        }
5848        scr_derived = derived;
5849        scr_band_start = band;
5850        pos = n_pos;
5851        toks.swap(toks_in);
5852        ctoks.resize((size_t) pos);
5853        for (size_t i = 0; i < (size_t) pos; ++i)
5854            ctoks[i] = toks[i] < pk.eg_vocab ? pk.eg_map[(size_t) toks[i]] : 0;
5855        for (int k = 0; k < kChecks; ++k) ck[k] = std::move(got[k]);   // (the slot's own; the old ones held the state
5856                                                               // this one replaced)
5857        slot_held = false;
5858        ok = true;
5859        return true;
5860    }
5861
5862    size_t scr_master_bytes_at(int64_t n_pos) const {
5863        size_t n = 0;
5864        for (const Src& s : srcs) {
5865            const int di = L[(size_t) s.layer].dev;
5866            const size_t rows = (size_t) (n_pos / std::max(1, s.ratio)), one = (size_t) g.rd * sizeof(float) + 1;
5867            if (s.master[(size_t) di] != nullptr) n += rows * one;
5868            if (s.master_ik[(size_t) di] != nullptr) n += rows * one;
5869        }
5870        return n;
5871    }
5872
5873    std::string slot_identity() const {
5874        const auto size_of = [](const std::string& p) {
5875            std::error_code ec;
5876            const auto s = std::filesystem::file_size(p, ec);
5877            return ec ? 0ull : (unsigned long long) s;
5878        };
5879        std::ostringstream id;
5880        id << "strata-ds4-session-3" << (scr_master ? "+scr" : "") << " engine=" << STRATA_VERSION << " mtp=" << g.n_mtp << " dim=" << g.dim << " hd=" << g.hd
5881           << " win=" << g.win << " ratios=";
5882        for (int r : g.ratios) id << r << ",";
5883        id << " kv=";
5884        for (int v : g.kv_src) id << v << ",";
5885        id << " ix=";
5886        for (int v : g.ix_src) id << v << ",";
5887        id << " ds4.txt:" << size_of(pk.dir + "/ds4.txt") << " engram.bin:" << size_of(pk.dir + "/engram.bin")
5888           << " tensors.txt:" << size_of(pk.dir + "/tensors.txt");
5889        for (size_t i = 0; i < pk.files.size(); ++i)
5890            id << " " << pk.files[i] << ":" << os::file_size(pk.fds[i]);
5891        return id.str();
5892    }
5893
5894    size_t bounce_bytes() const {
5895        return (size_t) kWin * ((size_t) g.hc * g.dim * 4 + 8 * 4 + topk_stride() * 4 + cand_stride() * 4);
5896    }
5897    size_t topk_stride() const { return (size_t) std::max(g.ix_topk, 32); }
5898    size_t cand_stride() const { return (size_t) std::max(g.cand_topk, 32); }
5899    size_t bm_stride() const { return (size_t) (o.max_context + 64) / std::max(1, g.cand_blk) + 64; }
5900    static constexpr int kSlots = kWin * kPicks;   // the CPU lane's (token, expert) rows a window can need
5901
5902    // ---- the vision tower (the checkpoint's vision.* / aligner.*) on the first GPU, its weights streamed from the
5903    // host; a prompt's pictures as their spans' rows (set_images)
5904    VisionTower vt;
5905    VisionGeo vg;
5906    int img_tok = -1;
5907    std::string vision_err;              // why the tower did not load (pictures off), or empty
5908    std::vector<uint16_t> img_mark[3];   // image_start, image_newline, image_end: BF16 [dim]
5909    std::vector<Image> imgs;             // the pictures of the prompt being fed, by start
5910    // a BF16 (or, rounded to nearest even, F32) tensor of n values into dst
5911    bool read_bf16(const Tensor& t, size_t n, void* dst) {
5912        if (t.dtype == "BF16") return t.bytes == n * 2 && pk.read(t, dst);
5913        if (t.dtype != "F32" || t.bytes != n * 4) return false;
5914        std::vector<float> f(n);
5915        if (!pk.read(t, f.data())) return false;
5916        uint16_t* o = (uint16_t*) dst;
5917        for (size_t i = 0; i < n; ++i) {
5918            uint32_t u;
5919            std::memcpy(&u, &f[i], 4);
5920            o[i] = (uint16_t) ((u + 0x7FFFu + ((u >> 16) & 1u)) >> 16);
5921        }
5922        return true;
5923    }
5924    bool load_vision(std::string& err) {
5925        vg.layers = (int) pk.num("vision.num_hidden_layers", 0);
5926        const int tok = (int) pk.num("image_token_id", -1);
5927        if (vg.layers <= 0 || tok < 0 || pk.get("vision.patch_embed.proj.weight") == nullptr) return true;   // none
5928        vg.dim = (int) pk.num("vision.hidden_size", 1024), vg.heads = (int) pk.num("vision.num_attention_heads", 16);
5929        vg.inter = (int) pk.num("vision.intermediate_size", 2816), vg.patch = (int) pk.num("vision.patch_size", 14);
5930        vg.merge = (int) pk.num("vision.downsample_ratio", 3), vg.theta = (float) pk.num("vision.rope_theta", 1e4);
5931        vg.max_tokens = (int) pk.num("vision.max_image_tokens", 1024), vg.out = g.dim;
5932        const char* mark[3] = {"image_start", "image_newline", "image_end"};
5933        for (int i = 0; i < 3; ++i) {
5934            const Tensor* t = pk.get(mark[i]);
5935            img_mark[i].resize((size_t) g.dim);
5936            if (t == nullptr || !read_bf16(*t, (size_t) g.dim, img_mark[i].data())) {
5937                err = std::string(mark[i]) + ": not a BF16 (or F32) row of the model's width";
5938                return false;
5939            }
5940        }
5941        const double t0 = now_ms();
5942        Dev& d = devs[0];
5943        // DS4_VISION_GPU=<CUDA index>: the tower on another card (the expert GPU: its arena sizes itself from what the
5944        // tower leaves, and a picture's rows come back through the host either way); default the first layer GPU
5945        int dev = d.id;
5946        if (const char* v = std::getenv("DS4_VISION_GPU"); v != nullptr && *v != 0) {
5947            int ndev = 0;
5948            cudaGetDeviceCount(&ndev);
5949            dev = std::atoi(v);
5950            if (dev < 0 || dev >= ndev) {
5951                err = "DS4_VISION_GPU " + std::string(v) + ": no such device";
5952                return false;
5953            }
5954        }
5955        // the tower's tensors as BF16: the checkpoint's own, or a GGUF's mmproj (F32 norms / biases / marker rows, which
5956        // came from BF16, converted back exactly; mlp.w1 as the two files' gate and up, the halves of its rows)
5957        auto read = [this](const std::string& n, std::vector<int64_t>& shape, void* dst) {
5958            const Tensor* t = pk.get(n);
5959            if (t == nullptr && n.size() > 13 && n.compare(n.size() - 13, 13, "mlp.w1.weight") == 0) {
5960                const std::string pre = n.substr(0, n.size() - 13);
5961                const Tensor* tg = pk.get(pre + "mlp.gate.weight");
5962                const Tensor* tu = pk.get(pre + "mlp.up.weight");
5963                if (tg == nullptr || tu == nullptr || tg->shape.size() != 2 || tg->shape != tu->shape) return false;
5964                shape = {tg->shape[0] * 2, tg->shape[1]};
5965                const size_t half = (size_t) tg->shape[0] * (size_t) tg->shape[1];
5966                return dst == nullptr || (read_bf16(*tg, half, dst) && read_bf16(*tu, half, (uint16_t*) dst + half));
5967            }
5968            if (t == nullptr) return false;
5969            shape = t->shape;
5970            size_t n_el = 1;
5971            for (int64_t x : t->shape) n_el *= (size_t) x;
5972            return dst == nullptr || read_bf16(*t, n_el, dst);
5973        };
5974        if (!vt.load(vg, dev, read, err)) return false;
5975        img_tok = tok;
5976        for (Dev& x : devs)
5977            if (x.id == dev) {
5978                CK(cudaSetDevice(x.id));
5979                CK(cudaMemGetInfo(&x.free0, &x.total));   // (the split sees what the tower left)
5980            }
5981        CK(cudaSetDevice(d.id));
5982        if (o.verbose)
5983            std::fprintf(stderr, "ds4: vision tower (%d blocks) on CUDA%d: %.0f MiB, up to %d patches, %.1f s\n",
5984                         vg.layers, dev, (double) vt.device_bytes() / (1 << 20), vt.max_patches(),
5985                         (now_ms() - t0) / 1000.0);
5986        return true;
5987    }
5988    bool encode_image(const uint8_t* rgb, int w, int h, std::vector<uint16_t>& span, std::string& err) {
5989        if (img_tok < 0) {
5990            err = "this model has no vision tower (or it is off)";
5991            return false;
5992        }
5993        std::vector<uint16_t> rows;
5994        int nh = 0, nw = 0, cur = 0;
5995        cudaGetDevice(&cur);
5996        const bool ok = vt.encode(rgb, w, h, rows, nh, nw, err);
5997        cudaSetDevice(cur);   // (the tower may sit on another card than the caller's)
5998        if (!ok) return false;
5999        const size_t D = (size_t) g.dim;
6000        span.resize(((size_t) nh * (nw + 1) + 2) * D);
6001        uint16_t* o = span.data();
6002        auto put = [&](const uint16_t* r) {
6003            std::memcpy(o, r, D * 2);
6004            o += D;
6005        };
6006        put(img_mark[0].data());
6007        for (int i = 0; i < nh; ++i) {
6008            for (int j = 0; j < nw; ++j) put(rows.data() + ((size_t) i * nw + j) * D);
6009            put(img_mark[1].data());
6010        }
6011        put(img_mark[2].data());
6012        return true;
6013    }
6014    // the row of a picture's span at position p (null: p is in none)
6015    const uint16_t* image_row(int64_t p) const {
6016        if (imgs.empty()) return nullptr;
6017        auto it = std::upper_bound(imgs.begin(), imgs.end(), p, [](int64_t v, const Image& im) { return v < im.start; });
6018        if (it == imgs.begin()) return nullptr;
6019        const Image& im = *(it - 1);
6020        const int64_t r = p - im.start;
6021        if (!im.rows || r >= (int64_t) (im.rows->size() / (size_t) g.dim)) return nullptr;
6022        return im.rows->data() + (size_t) r * g.dim;
6023    }
6024    // token tk's embedding row at position p: inside a picture's span, the picture's
6025    const uint16_t* emb_row(int64_t p, int tk) const {
6026        const uint16_t* r = tk == img_tok ? image_row(p) : nullptr;
6027        return r != nullptr ? r : embed_pinned + (size_t) tk * g.dim;
6028    }
6029    bool in_image(int64_t p) const { return img_tok >= 0 && toks[(size_t) p] == img_tok && image_row(p) != nullptr; }
6030    // the Engram's compressed id of token tk at p (-1: a picture's, which no n-gram spans)
6031    int32_t ctok(int64_t p, int tk) const {
6032        if (tk == img_tok && image_row(p) != nullptr) return -1;
6033        return tk < pk.eg_vocab ? pk.eg_map[(size_t) tk] : 0;
6034    }
6035    // a chunk's image rows (route()'s bits); false: none
6036    bool vl_bits(int64_t p0, int T, VlBits& b) const {
6037        if (imgs.empty()) return false;
6038        std::memset(&b, 0, sizeof b);
6039        bool any = false;
6040        for (int t = 0; t < T && t < kVlRows; ++t)
6041            if (in_image(p0 + t)) {
6042                b.w[t >> 5] |= 1u << (t & 31);
6043                any = true;
6044            }
6045        return any;
6046    }
6047
6048    // ---- Engram: a window's rows of one table (Engram layer li), tokens p0 .. p0 + T - 1 into dst ([token] of [cols]
6049    // [hd] codes then the scales; nullptr: h_eg).  eg_issue serves the rows already fetched from the row cache (and a
6050    // row the window needs twice from one read) and hands the rest to the reader's threads; eg_finish waits for them,
6051    // copies the repeats and keeps the new rows in the cache.  The rows are the file's bytes either way.
6052    void eg_issue(int64_t p0, int T, int li, uint8_t* dst, EgBatch& b) {
6053        const int cols = (pk.eg_ngram - 1) * pk.eg_heads, hd = pk.eg_hd;
6054        const size_t per = (size_t) cols * (hd + hd / 32);
6055        b.clear();
6056        b.reads.reserve((size_t) T * cols);
6057        const std::string P = "layers." + std::to_string(g.eg_layers[(size_t) li]) + ".engram.embed.";
6058        const Tensor* tw = pk.get(P + "weight");
6059        const Tensor* ts = pk.get(P + "scale");
6060        const int fmt = eg_fmt[(size_t) li];
6061        const bool mx8 = fmt == 0;   // (a GGUF: the scales between the codes, one per 32)
6062        const bool q6k = fmt == 1;   // (a GGUF: one Q6_K superblock a 256 values, its scales inside)
6063        const bool iq4 = fmt == 2;   // (a GGUF: 18-byte blocks a 32 values, d and 16 nibble bytes, no scales)
6064        std::unordered_map<uint64_t, int> first;   // a row this batch reads already -> its read
6065        int64_t hits = 0;
6066        {
6067            std::lock_guard<std::mutex> lk(eg_cache_mu);
6068            for (int t = 0; t < T; ++t) {
6069                const int64_t p = p0 + t;
6070                uint8_t* rows = dst != nullptr ? dst + (size_t) t * per : h_eg + ((size_t) li * eg_cap + t) * per;
6071                uint8_t* scales = rows + (size_t) cols * hd;
6072                if (ctoks[(size_t) p] < 0) {   // a picture's token: no rows (zeros: its gate adds nothing)
6073                    std::memset(rows, 0, per);
6074                    continue;
6075                }
6076                int64_t prod[8];
6077                bool blocked = false;
6078                for (int s = 0; s < pk.eg_ngram; ++s) {   // (the look-back stops at the start and at a picture)
6079                    blocked = blocked || p < s || ctoks[(size_t) (p - s)] < 0;
6080                    const int64_t tk = blocked ? pk.eg_pad : ctoks[(size_t) (p - s)];
6081                    prod[s] = tk * pk.eg_mult[(size_t) li * pk.eg_ngram + s];
6082                }
6083                int64_t rolling = prod[0];
6084                for (int n = 1; n < pk.eg_ngram; ++n) {
6085                    rolling ^= prod[n];
6086                    for (int h = 0; h < pk.eg_heads; ++h) {
6087                        const int c = (n - 1) * pk.eg_heads + h;
6088                        const int64_t id = rolling % pk.eg_primes[(size_t) li * cols + c] + pk.eg_off[(size_t) li * cols + c];
6089                        uint8_t* rd = rows + (size_t) c * hd;
6090                        uint8_t* sd = scales + (size_t) c * (hd / 32);
6091                        const uint64_t key = (uint64_t) id * 8 + (uint64_t) li;
6092                        if (const uint8_t* hit = eg_cache.find(key)) {
6093                            std::memcpy(rd, hit, (size_t) hd);
6094                            std::memcpy(sd, hit + hd, (size_t) hd / 32);
6095                            ++hits;
6096                            continue;
6097                        }
6098                        const auto fi = first.find(key);
6099                        if (fi != first.end()) {
6100                            b.dups.push_back({fi->second, {rd, sd}});
6101                            continue;
6102                        }
6103                        first.emplace(key, (int) b.reads.size());
6104                        EgRead r;
6105                        r.file = tw->file;
6106                        r.dst = rd;
6107                        r.scales = sd;
6108                        r.key = key;
6109                        if (mx8) {
6110                            r.mx8 = true;
6111                            r.n = (uint32_t) (hd / 32 * 33);
6112                            r.off = tw->off + (uint64_t) id * r.n;
6113                        } else if (q6k || iq4) {   // (into the row's code bytes; its scale bytes unused)
6114                            r.n = (uint32_t) (q6k ? hd / 256 * 210 : hd / 32 * 18);
6115                            r.off = tw->off + (uint64_t) id * r.n;
6116                        } else {
6117                            r.n = (uint32_t) hd;
6118                            r.off = tw->off + (uint64_t) id * hd;
6119                            r.file2 = ts->file;
6120                            r.n2 = (uint32_t) (hd / 32);
6121                            r.off2 = ts->off + (uint64_t) id * (hd / 32);
6122                        }
6123                        b.reads.push_back(r);
6124                    }
6125                }
6126            }
6127        }
6128        eg_rows_n += hits + (int64_t) b.reads.size() + (int64_t) b.dups.size();
6129        eg_hits_n += hits + (int64_t) b.dups.size();
6130        eg_reads_n += (int64_t) b.reads.size();
6131        eg_io.submit(b);
6132    }
6133    // b's rows all in place (any thread; a group's members may ask at once: one finishes, the others wait for it)
6134    void eg_finish(EgBatch& b) {
6135        if (b.post.load(std::memory_order_acquire) == 2) return;
6136        const int64_t t0 = now_ns();
6137        eg_io.wait(b);
6138        int want = 0;
6139        if (b.post.compare_exchange_strong(want, 1, std::memory_order_acq_rel)) {
6140            const int hd = pk.eg_hd;
6141            for (const auto& d : b.dups) {
6142                const EgRead& r = b.reads[(size_t) d.first];
6143                std::memcpy(d.second.first, r.dst, (size_t) hd);
6144                std::memcpy(d.second.second, r.scales, (size_t) hd / 32);
6145            }
6146            {
6147                std::lock_guard<std::mutex> lk(eg_cache_mu);
6148                for (size_t i = 0; i < b.reads.size(); ++i) {
6149                    const EgRead& r = b.reads[i];
6150                    if (!b.ok[i]) {   // (a failed read: zeros, its gate adds nothing; not kept)
6151                        std::memset(r.dst, 0, (size_t) hd);
6152                        std::memset(r.scales, 0, (size_t) hd / 32);
6153                        continue;
6154                    }
6155                    if (uint8_t* c = eg_cache.put(r.key)) {
6156                        std::memcpy(c, r.dst, (size_t) hd);
6157                        std::memcpy(c + hd, r.scales, (size_t) hd / 32);
6158                    }
6159                }
6160            }
6161            eg_io_ns += b.t1.load() - b.t0;
6162            b.live = false;
6163            b.post.store(2, std::memory_order_release);
6164        } else {
6165            while (b.post.load(std::memory_order_acquire) != 2) std::this_thread::yield();
6166        }
6167        eg_wait_ns += now_ns() - t0;
6168    }
6169    void eg_stats() {
6170        st.eg_rows = eg_rows_n.load();
6171        st.eg_hits = eg_hits_n.load();
6172        st.eg_reads = eg_reads_n.load();
6173        st.eg_io_ms = (double) eg_io_ns.load() / 1e6;
6174        std::lock_guard<std::mutex> lk(eg_cache_mu);
6175        st.eg_cached = (int64_t) eg_cache.size();
6176        st.eg_cache_cap = (int64_t) eg_cache.capacity();
6177    }
6178    // the chunked prompt path: rows of Engram layer `only` into dst, now (a helper thread, a chunk ahead)
6179    void engram_rows(int64_t p0, int T, int only, uint8_t* dst) {
6180        EgBatch b;
6181        eg_issue(p0, T, only, dst, b);
6182        eg_finish(b);
6183    }
6184
6185    // ---- the CPU lane: a window's routed experts that live on the host, as entries (an expert and up to 8 of its
6186    // tokens, in rows slot0 ..) computed together: each node its column part of every matrix, from memory on that node,
6187    // in four rounds (the gate / up split-K pieces, each preparing its two input blocks of every token; each band's
6188    // sums / codebook / Hadamard / swiglu and that block of the down input, which both nodes then read whole; the down
6189    // pieces; the down bands).  yd[slot] gets each row's expert output.
6190    static constexpr int kEntMax = kWin > kc::kExl3CpuMaxN ? kWin : kc::kExl3CpuMaxN;
6191    struct Ent {
6192        int e = 0, n = 0, slot0 = 0;
6193        int tok[kEntMax] = {};
6194    };
6195    // tokens an entry holds: the i-quant GGUF experts take a whole window's tokens of an expert in one call (the CPU
6196    // lane's exact multi-token rows, 7+ tokens an expert: decoded once for all), the others (MXFP4, EXL3) up to 8
6197    static int ent_cap(const Layer& l) {
6198        return l.lay.fmt == gg::kFmtMXFP4 && !gg::mx_experts(l.lay) ? kEntMax : kc::kExl3CpuMaxN;
6199    }
6200    void run_nodes(int n, const std::function<void(int)>* f) {
6201        for (int X = 0; X < NH; ++X) pools[(size_t) X]->start(n, f[X]);
6202        pools[0]->help();
6203        for (int X = 0; X < NH; ++X) pools[(size_t) X]->wait();
6204    }
6205
6206    // a GGUF's MXFP4 experts on the CPU lane, read from the file's mapping or their copy in RAM (mx_part_ptr): each
6207    // node its rows of every matrix - the gate / up rows [X n_ff / NH, ..) of each entry (the swiglu into its h row),
6208    // then (h whole) the down rows [X dim / NH, ..) into yd.  A row's sum is the same whatever the split: the same bits
6209    // in a copy as in place.  The device's arithmetic (gg::mx_rows: int8 activations rounded as the device rounds
6210    // them, exact integer sums a block; every CPU tier the same bits): each token's input quantized once, whatever
6211    // number of entries take it, and each job its band of h straight into the down's int8 input.
6212    // (ord: the order the entries are computed in - their slots, so the sums, stay the same; null: as they are)
6213    void cpu_experts_mx(const Layer& l, const float* x, const std::vector<Ent>& ents, size_t ldx, const int* ord) {
6214        if (!gg::mx_experts(l.lay)) return cpu_experts_iq(l, x, ents, ldx, ord);
6215        constexpr int RB = 64;   // rows a job (whole blocks of h: RB % 32 == 0)
6216        const int E = g.dim, FF = g.ff, FFh = FF / NH, Eh = E / NH;
6217        const int GB = (FFh + RB - 1) / RB, DB = (Eh + RB - 1) / RB, ne = (int) ents.size();
6218        const size_t gr = gg::mx_row_bytes(E), dr = gg::mx_row_bytes(FF);
6219        const size_t xa = gg::mx_act_bytes(E), ha = gg::mx_act_bytes(FF);
6220        const bool band_q = FFh % 32 == 0;   // (each job's rows whole blocks of h)
6221        const float lim = g.lim;
6222        static_assert(kc::kExl3CpuMaxN <= gg::kMxCpuMaxN, "a CPU-lane entry's tokens in one call");
6223        {   // the experts read from the files (not in the RAM tier) that are not resident: all their pages asked for at
6224            // once, so the SSD reads them with large requests side by side while the first entries compute
6225            // (os::prefetch_cold: the resident ones are left alone - the hint walks every page of a range, which cost
6226            // more than computing a warm expert, 0.34 ms a 6.3 MB matrix on Windows)
6227            std::vector<std::pair<const void*, size_t>> want;
6228            for (const Ent& en : ents)
6229                if (!store && (l.ram.empty() || l.ram[(size_t) en.e] < 0))
6230                    for (int r = 0; r < 3; ++r) want.push_back({mx_mat(l, en.e, r), mx_part_bytes(l, r)});
6231            os::prefetch_cold(want);
6232        }
6233        // the int8 inputs in c_xh's bytes: token t's (t < kWin) at t xa, then the slots' h at (kWin + slot) ha; a token
6234        // index past the window (none on the decode or chunk paths) gets a row of its own after them
6235        uint8_t* xq = (uint8_t*) c_xh.data();
6236        uint8_t* hq = xq + (size_t) kWin * xa;
6237        uint8_t* xq_extra = hq + (size_t) kSlots * ha;
6238        auto x_act = [&](const Ent& en, int i) -> const void* {
6239            const int t = en.tok[i];
6240            return t < kWin ? xq + (size_t) t * xa : xq_extra + (size_t) (en.slot0 + i) * xa;
6241        };
6242        {
6243            bool done[kWin] = {};
6244            for (const Ent& en : ents)
6245                for (int i = 0; i < en.n; ++i) {
6246                    const int t = en.tok[i];
6247                    if (t < kWin && done[t]) continue;
6248                    if (t < kWin) done[t] = true;
6249                    gg::mx_quant(x + (size_t) t * ldx, E, (void*) x_act(en, i));
6250                }
6251        }
6252        std::function<void(int)> f[4];
6253        for (int X = 0; X < NH; ++X)
6254            f[X] = [&, X](int j) {
6255                const Ent& en = ents[(size_t) (ord != nullptr ? ord[j / GB] : j / GB)];
6256                const int r0 = X * FFh + (j % GB) * RB, r1 = std::min(X * FFh + FFh, r0 + RB);
6257                const void* ap[gg::kMxCpuMaxN];
6258                float yg[gg::kMxCpuMaxN][RB], yu[gg::kMxCpuMaxN][RB];
6259                float *gp[gg::kMxCpuMaxN], *up[gg::kMxCpuMaxN];
6260                for (int i = 0; i < en.n; ++i) {
6261                    ap[i] = x_act(en, i);
6262                    gp[i] = yg[i];
6263                    up[i] = yu[i];
6264                }
6265                // (part X's rows, from where they are: a copy's part on node X, or the file's)
6266                gg::mx_rows(mx_part_ptr(l, en.e, 0, X), gr, E, r0 - X * FFh, r1 - X * FFh, ap, en.n, gp);
6267                gg::mx_rows(mx_part_ptr(l, en.e, 1, X), gr, E, r0 - X * FFh, r1 - X * FFh, ap, en.n, up);
6268                for (int i = 0; i < en.n; ++i) {
6269                    float* h = band_q ? yg[i] : c_xhd.data() + (size_t) (en.slot0 + i) * FF + r0;
6270                    for (int r = r0; r < r1; ++r) {
6271                        float gv = yg[i][r - r0], uv = yu[i][r - r0];
6272                        if (lim > 0.0f) {
6273                            gv = std::min(gv, lim);
6274                            uv = std::min(std::max(uv, -lim), lim);
6275                        }
6276                        h[r - r0] = gv / (1.0f + std::exp(-gv)) * uv;
6277                    }
6278                    if (band_q) gg::mx_quant_blocks(h, r0 / 32, r1 / 32, hq + (size_t) (en.slot0 + i) * ha, FF);
6279                }
6280            };
6281        run_nodes(ne * GB, f);
6282        if (!band_q)
6283            for (const Ent& en : ents)
6284                for (int i = 0; i < en.n; ++i)
6285                    gg::mx_quant(c_xhd.data() + (size_t) (en.slot0 + i) * FF, FF, hq + (size_t) (en.slot0 + i) * ha);
6286        for (int X = 0; X < NH; ++X)
6287            f[X] = [&, X](int j) {
6288                const Ent& en = ents[(size_t) (ord != nullptr ? ord[j / DB] : j / DB)];
6289                const int r0 = X * Eh + (j % DB) * RB, r1 = std::min(X * Eh + Eh, r0 + RB);
6290                const void* ap[gg::kMxCpuMaxN];
6291                float* yp[gg::kMxCpuMaxN];
6292                for (int i = 0; i < en.n; ++i) {
6293                    ap[i] = hq + (size_t) (en.slot0 + i) * ha;
6294                    yp[i] = c_yd.data() + (size_t) (en.slot0 + i) * E + r0;
6295                }
6296                gg::mx_rows(mx_part_ptr(l, en.e, 2, X), dr, FF, r0 - X * Eh, r1 - X * Eh, ap, en.n, yp);
6297            };
6298        run_nodes(ne * DB, f);
6299    }
6300    // ... the low-bit ones (ds4_iq's types): as above, through ggml-cpu's dots (gg::iq_cpu_*) - each token's input
6301    // quantized once to the weight type's activation (Q8_K) in its c_xh row's bytes, then (h whole) its h the same
6302    void cpu_experts_iq(const Layer& l, const float* x, const std::vector<Ent>& ents, size_t ldx, const int* ord) {
6303        constexpr int RB = 64;   // rows a job
6304        const int E = g.dim, FF = g.ff, FFh = FF / NH, Eh = E / NH;
6305        const int GB = (FFh + RB - 1) / RB, DB = (Eh + RB - 1) / RB, ne = (int) ents.size();
6306        gg::IqCpu fm;
6307        std::string ferr;
6308        if (!gg::iq_cpu_fmt(gg::expert_type(l.lay, 0), gg::expert_type(l.lay, 2), E, FF, fm, ferr) ||
6309            fm.act_bytes > (size_t) E * 4 || fm.h_bytes > (size_t) E * 4) {
6310            static std::atomic<bool> said{false};
6311            if (!said.exchange(true)) std::fprintf(stderr, "ds4: layer %d's CPU-lane experts: %s\n", l.il, ferr.c_str());
6312            for (const Ent& en : ents) std::memset(c_yd.data() + (size_t) en.slot0 * E, 0, (size_t) en.n * E * 4);
6313            return;
6314        }
6315        const float lim = g.lim;
6316        const double tp0 = now_ms();
6317        {   // (os::prefetch_cold, as above: the resident ones are left alone - on Windows the hint walks every page of a
6318            // range, ~0.13 ms an IQ2_XXS expert, on the lane's critical path before the first entry computes.
6319            // off by default (the mmap path, owner PC: not faster in every pair); DS4_IQ_PF_COLD=1 turns it on)
6320            std::vector<std::pair<const void*, size_t>> want;
6321            for (const Ent& en : ents)
6322                if (!store && (l.ram.empty() || l.ram[(size_t) en.e] < 0))
6323                    for (int r = 0; r < 3; ++r) want.push_back({mx_mat(l, en.e, r), mx_part_bytes(l, r)});
6324            static const bool pf_all = std::getenv("DS4_IQ_PF_COLD") == nullptr || std::atoi(std::getenv("DS4_IQ_PF_COLD")) == 0;
6325            if (pf_all) os::prefetch(want);
6326            else os::prefetch_cold(want);
6327        }
6328        // the activations in c_xh's bytes, E 4 apart: token t's (t < kWin) at row t - quantized once, whatever number of
6329        // entries take it - then a row a slot (kWin + slot): a token past the window's input (none on the decode or
6330        // chunk paths), then (x no longer needed) the slot's h
6331        uint8_t* aq = (uint8_t*) c_xh.data();
6332        auto x_act = [&](const Ent& en, int i) -> uint8_t* {
6333            const int t = en.tok[i];
6334            return aq + (size_t) (t < kWin ? t : kWin + en.slot0 + i) * E * 4;
6335        };
6336        {
6337            bool done[kWin] = {};
6338            for (const Ent& en : ents)
6339                for (int i = 0; i < en.n; ++i) {
6340                    const int t = en.tok[i];
6341                    if (t < kWin && done[t]) continue;
6342                    if (t < kWin) done[t] = true;
6343                    gg::iq_cpu_quant(fm.gu_act, x + (size_t) t * ldx, E, x_act(en, i));
6344                }
6345        }
6346        const double tp1 = now_ms();
6347        std::function<void(int)> f[4];
6348        for (int X = 0; X < NH; ++X)
6349            f[X] = [&, X](int j) {
6350                const Ent& en = ents[(size_t) (ord != nullptr ? ord[j / GB] : j / GB)];
6351                const int r0 = X * FFh + (j % GB) * RB, r1 = std::min(X * FFh + FFh, r0 + RB);
6352                const void* ap[kEntMax];
6353                float* hp[kEntMax];
6354                for (int i = 0; i < en.n; ++i) {
6355                    ap[i] = x_act(en, i);
6356                    hp[i] = c_xhd.data() + (size_t) (en.slot0 + i) * FF + (size_t) X * FFh;   // (part X's rows of h)
6357                }
6358                // (part X's rows, from where they are: a copy's part on node X, or the file's - whole rows, so any
6359                // block size of the type)
6360                gg::iq_cpu_gate_up(fm, mx_part_ptr(l, en.e, 0, X), mx_part_ptr(l, en.e, 1, X), ap, en.n, hp,
6361                                   r0 - X * FFh, r1 - X * FFh, lim);
6362            };
6363        run_nodes(ne * GB, f);
6364        const double tp2 = now_ms();
6365        for (const Ent& en : ents)
6366            for (int i = 0; i < en.n; ++i)
6367                gg::iq_cpu_quant(fm.d_act, c_xhd.data() + (size_t) (en.slot0 + i) * FF, FF,
6368                                 aq + (size_t) (kWin + en.slot0 + i) * E * 4);
6369        const double tp3 = now_ms();
6370        for (int X = 0; X < NH; ++X)
6371            f[X] = [&, X](int j) {
6372                const Ent& en = ents[(size_t) (ord != nullptr ? ord[j / DB] : j / DB)];
6373                const int r0 = X * Eh + (j % DB) * RB, r1 = std::min(X * Eh + Eh, r0 + RB);
6374                const void* hp[kEntMax];
6375                float* yp[kEntMax];
6376                for (int i = 0; i < en.n; ++i) {
6377                    hp[i] = aq + (size_t) (kWin + en.slot0 + i) * E * 4;
6378                    yp[i] = c_yd.data() + (size_t) (en.slot0 + i) * E + (size_t) X * Eh;   // (part X's rows of it)
6379                }
6380                gg::iq_cpu_down(fm, mx_part_ptr(l, en.e, 2, X), hp, en.n, yp, r0 - X * Eh, r1 - X * Eh);
6381            };
6382        run_nodes(ne * DB, f);
6383        {   // DS4_PROF: where the CPU lane's time goes (act prep + prefetch, gate/up, h quant, down), summed
6384            static const bool on = std::getenv("DS4_PROF") != nullptr;
6385            if (on) {
6386                static double acc[6] = {};
6387                const double te = now_ms();
6388                acc[0] += tp1 - tp0; acc[1] += tp2 - tp1; acc[2] += tp3 - tp2; acc[3] += te - tp3; acc[4] += 1; acc[5] += ne;
6389                if (((long long) acc[4]) % 1000 == 0)
6390                    std::fprintf(stderr, "ds4 prof CPU lane (IQ rows) per call: n %.0f, entries/call %.2f, prep %.3f ms, gate+up %.3f ms, h-quant %.3f ms, down %.3f ms\n", acc[4], acc[5] / acc[4], acc[0] / acc[4], acc[1] / acc[4], acc[2] / acc[4], acc[3] / acc[4]);
6391            }
6392        }
6393    }
6394
6395    // the window's CPU-lane experts made ready (and pinned) in the store for the length of the call
6396    struct StoreHold {
6397        Impl* m = nullptr;
6398        int layer = 0;
6399        std::vector<int> es, sl;
6400        std::vector<char> ok;
6401        // lazy: the reads are started here and waited for by wait_all() / wait_expert(); the destructor releases
6402        StoreHold(Impl* m_, const Layer& l, const std::vector<Ent>& ents) {
6403            if (!m_->store) return;
6404            m = m_;
6405            layer = l.il;
6406            for (const Ent& en : ents)
6407                if ((l.ram.empty() || l.ram[(size_t) en.e] < 0) && std::find(es.begin(), es.end(), en.e) == es.end()) es.push_back(en.e);
6408            m->store->begin(layer, es.data(), (int) es.size(), ok, sl);
6409        }
6410        int idx(int e) const {
6411            for (size_t i = 0; i < es.size(); ++i)
6412                if (es[i] == e) return (int) i;
6413            return -1;
6414        }
6415        // expert e needs no waiting: not a store expert (RAM copy) or its reads are done
6416        bool ready(int e) const {
6417            if (!m) return true;
6418            const int i = idx(e);
6419            return i < 0 || m->store->loaded(sl[(size_t) i]);
6420        }
6421        void wait_expert(int e) {
6422            if (!m) return;
6423            const int i = idx(e);
6424            if (i >= 0) m->store->wait_slots(sl, ok, i, i + 1);
6425        }
6426        void wait_all() {
6427            if (m) m->store->wait_slots(sl, ok, 0, (int) es.size());
6428        }
6429        ~StoreHold() {
6430            if (m) m->store->release(layer, es.data(), (int) es.size(), ok);
6431        }
6432    };
6433    // DS4_LANE_STREAM=1 (one NUMA part, the i-quant experts, the RAM store): the window's entries in one pool batch - each
6434    // entry's gate/up jobs, then its down jobs - the ones whose reads are done first, the others in the order their reads
6435    // were started.  A job on an expert still being read waits only for the pieces holding its rows (DS4_STORE_PIECE_KB:
6436    // it starts before the rest of the expert has landed; a piece whose read failed is read from the file's mapping
6437    // instead); an entry's last gate/up job quantizes its h, which its down jobs wait for.  Every row is computed by the
6438    // same call on the same rows and lands in the same place as in cpu_experts_iq: the same bits, whatever the timing.
6439    void cpu_experts_iq_stream(const Layer& l, const float* x, const std::vector<Ent>& ents, size_t ldx, const int* ord,
6440                               StoreHold& hold) {
6441        constexpr int RB = 64;
6442        const int E = g.dim, FF = g.ff, GB = (FF + RB - 1) / RB, DB = (E + RB - 1) / RB, JB = GB + DB;
6443        const int ne = (int) ents.size();
6444        gg::IqCpu fm;
6445        std::string ferr;
6446        if (!gg::iq_cpu_fmt(gg::expert_type(l.lay, 0), gg::expert_type(l.lay, 2), E, FF, fm, ferr) ||
6447            fm.act_bytes > (size_t) E * 4 || fm.h_bytes > (size_t) E * 4) {
6448            hold.wait_all();
6449            return cpu_experts_iq(l, x, ents, ldx, ord);
6450        }
6451        const float lim = g.lim;
6452        const double tp0 = now_ms();
6453        std::vector<int> order, slot((size_t) ne, -1);   // slot: the store slot an entry reads from (-1: mx_part_ptr's place)
6454        order.reserve((size_t) ne);
6455        for (int k = 0; k < ne; ++k) {
6456            const int i = hold.idx(ents[(size_t) k].e);
6457            if (i >= 0) slot[(size_t) k] = hold.sl[(size_t) i];
6458        }
6459        for (int pass = 0; pass < 2; ++pass)
6460            for (int q = 0; q < ne; ++q) {
6461                const int k = ord != nullptr ? ord[q] : q;
6462                if ((slot[(size_t) k] < 0 || store->loaded(slot[(size_t) k])) == (pass == 0)) order.push_back(k);
6463            }
6464        uint8_t* aq = (uint8_t*) c_xh.data();
6465        auto x_act = [&](const Ent& en, int i) -> uint8_t* {
6466            const int t = en.tok[i];
6467            return aq + (size_t) (t < kWin ? t : kWin + en.slot0 + i) * E * 4;
6468        };
6469        {
6470            bool done[kWin] = {};
6471            for (const Ent& en : ents)
6472                for (int i = 0; i < en.n; ++i) {
6473                    const int t = en.tok[i];
6474                    if (t < kWin && done[t]) continue;
6475                    if (t < kWin) done[t] = true;
6476                    gg::iq_cpu_quant(fm.gu_act, x + (size_t) t * ldx, E, x_act(en, i));
6477                }
6478        }
6479        const double tp1 = now_ms();
6480        // matrix r of entry k with bytes [lo, hi) in: the slot's (waiting for them) or, a read having failed, the file's
6481        static const bool prof = std::getenv("DS4_PROF") != nullptr;
6482        std::atomic<int64_t> waited_ns{0}, hwait_ns{0}, last_ns{0};
6483        const auto tb = std::chrono::steady_clock::now();
6484        auto mat = [&](int k, int r, uint64_t lo, uint64_t hi) -> const uint8_t* {
6485            const int s = slot[(size_t) k], e = ents[(size_t) k].e;
6486            if (s < 0) return mx_part_ptr(l, e, r, 0);
6487            std::chrono::steady_clock::time_point t0;
6488            for (int it = 0;; ++it) {
6489                const int st = store->bytes_ready(s, r, lo, hi);
6490                if (st != 0) {
6491                    if (prof && it > 0) {
6492                        const auto t1 = std::chrono::steady_clock::now();
6493                        waited_ns.fetch_add(std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count(), std::memory_order_relaxed);
6494                        const int64_t at = std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - tb).count();
6495                        int64_t cur = last_ns.load(std::memory_order_relaxed);
6496                        while (at > cur && !last_ns.compare_exchange_weak(cur, at)) {
6497                        }
6498                    }
6499                    return st > 0 ? store->mat(s, r) : pk.at(l.mx_file[r], l.mx_off[r] + (uint64_t) e * l.mx_stride[r]);
6500                }
6501                if (prof && it == 0) t0 = std::chrono::steady_clock::now();
6502                cpu_relax();
6503                if (it > 4000) std::this_thread::yield();
6504            }
6505        };
6506        std::unique_ptr<std::atomic<int>[]> gu_left(new std::atomic<int>[(size_t) ne]), h_ready(new std::atomic<int>[(size_t) ne]);
6507        for (int k = 0; k < ne; ++k) {
6508            gu_left[(size_t) k].store(GB, std::memory_order_relaxed);
6509            h_ready[(size_t) k].store(0, std::memory_order_relaxed);
6510        }
6511        const std::function<void(int)> f = [&](int j) {
6512            const int k = order[(size_t) (j / JB)], w = j % JB;
6513            const Ent& en = ents[(size_t) k];
6514            if (w < GB) {
6515                const int r0 = w * RB, r1 = std::min(FF, r0 + RB);
6516                const void* ap[kEntMax];
6517                float* hp[kEntMax];
6518                for (int i = 0; i < en.n; ++i) {
6519                    ap[i] = x_act(en, i);
6520                    hp[i] = c_xhd.data() + (size_t) (en.slot0 + i) * FF;
6521                }
6522                const uint64_t lo = (uint64_t) r0 * fm.gu_row, hi = (uint64_t) r1 * fm.gu_row;
6523                const uint8_t* gm = mat(k, 0, lo, hi);
6524                const uint8_t* um = mat(k, 1, lo, hi);
6525                gg::iq_cpu_gate_up(fm, gm, um, ap, en.n, hp, r0, r1, lim);
6526                if (gu_left[(size_t) k].fetch_sub(1, std::memory_order_acq_rel) == 1) {   // (the entry's h whole)
6527                    for (int i = 0; i < en.n; ++i)
6528                        gg::iq_cpu_quant(fm.d_act, c_xhd.data() + (size_t) (en.slot0 + i) * FF, FF,
6529                                         aq + (size_t) (kWin + en.slot0 + i) * E * 4);
6530                    h_ready[(size_t) k].store(1, std::memory_order_release);
6531                }
6532                return;
6533            }
6534            const int r0 = (w - GB) * RB, r1 = std::min(E, r0 + RB);
6535            const uint8_t* dm = mat(k, 2, (uint64_t) r0 * fm.d_row, (uint64_t) r1 * fm.d_row);
6536            if (h_ready[(size_t) k].load(std::memory_order_acquire) == 0) {
6537                const auto t0 = std::chrono::steady_clock::now();
6538                while (h_ready[(size_t) k].load(std::memory_order_acquire) == 0) cpu_relax();
6539                if (prof)
6540                    hwait_ns.fetch_add(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - t0).count(),
6541                                       std::memory_order_relaxed);
6542            }
6543            const void* hp[kEntMax];
6544            float* yp[kEntMax];
6545            for (int i = 0; i < en.n; ++i) {
6546                hp[i] = aq + (size_t) (kWin + en.slot0 + i) * E * 4;
6547                yp[i] = c_yd.data() + (size_t) (en.slot0 + i) * E;
6548            }
6549            gg::iq_cpu_down(fm, dm, hp, en.n, yp, r0, r1);
6550        };
6551        pools[0]->run(ne * JB, f);
6552        hold.wait_all();   // (the reads are all in: the store's bookkeeping, and the slots' pins released with the hold)
6553        if (prof) {   // (waits: the jobs' waits for pieces and for h, summed over the threads)
6554            static double acc[7] = {};
6555            acc[0] += tp1 - tp0; acc[1] += now_ms() - tp1; acc[2] += 1; acc[3] += ne; acc[4] += waited_ns.load() / 1e6;
6556            acc[5] += hwait_ns.load() / 1e6; acc[6] += last_ns.load() / 1e6;
6557            if (((long long) acc[2]) % 1000 == 0)
6558                std::fprintf(stderr, "ds4 prof CPU lane (IQ stream) per call: n %.0f, entries/call %.2f, prep %.3f ms, rows %.3f ms, thread waits: pieces %.3f ms, h %.3f ms; last piece in at %.3f ms\n",
6559                             acc[2], acc[3] / acc[2], acc[0] / acc[2], acc[1] / acc[2], acc[4] / acc[2], acc[5] / acc[2], acc[6] / acc[2]);
6560        }
6561    }
6562    // ---- the expert GPU (DS4_AUX_GPU=<CUDA index>): a second card that holds experts and computes them, not a layer split.
6563    // The hottest experts by the profile that neither VRAM nor a RAM copy holds are copied into its arena once (DS4_AUX_GB,
6564    // default: what it has free less 0.8 GB); the CPU lane hands it their rows of each request - the FFN inputs over PCIe,
6565    // the same GEMV kernels as the main GPU's VRAM experts - and adds its outputs into the token's part after the CPU
6566    // lane's own, in expert order.  A layer's VRAM cache moves still go first: an expert in VRAM is the device's.
6567    struct Aux {
6568        int dev = -1;
6569        cudaStream_t st = nullptr;
6570        cudaEvent_t ev = nullptr;
6571        uint8_t* arena = nullptr;
6572        size_t arena_bytes = 0, used = 0;
6573        float *xin = nullptr, *xe = nullptr, *xg = nullptr, *xu = nullptr, *xh = nullptr, *ye = nullptr;
6574        float* hy = nullptr;   // pinned: the rows' outputs, kWin * kPicks rows of dim
6575        int n_experts = 0;
6576    } aux;
6577    bool aux_init(std::string& err) {
6578        const char* v = std::getenv("DS4_AUX_GPU");
6579        if (v == nullptr || *v == 0) return true;
6580        int ndev = 0;
6581        cudaGetDeviceCount(&ndev);
6582        aux.dev = std::atoi(v);
6583        if (aux.dev < 0 || aux.dev >= ndev) {
6584            err = "DS4_AUX_GPU " + std::string(v) + ": no such device";
6585            return false;
6586        }
6587        for (const Dev& d : devs)
6588            if (d.id == aux.dev) {
6589                err = "DS4_AUX_GPU: device " + std::string(v) + " already runs layers (start with --gpus without it)";
6590                return false;
6591            }
6592        int prev = 0;
6593        cudaGetDevice(&prev);
6594        cudaSetDevice(aux.dev);
6595        const size_t D = (size_t) g.dim, FF = (size_t) g.ff, R = (size_t) kWin * kPicks;
6596        if (cudaStreamCreateWithFlags(&aux.st, cudaStreamNonBlocking) != cudaSuccess ||
6597            cudaEventCreateWithFlags(&aux.ev, cudaEventDisableTiming) != cudaSuccess ||
6598            cudaMalloc((void**) &aux.xin, (size_t) kWin * D * 4) != cudaSuccess ||
6599            cudaMalloc((void**) &aux.xe, R * D * 4) != cudaSuccess || cudaMalloc((void**) &aux.ye, R * D * 4) != cudaSuccess ||
6600            cudaMalloc((void**) &aux.xg, R * FF * 4) != cudaSuccess || cudaMalloc((void**) &aux.xu, R * FF * 4) != cudaSuccess ||
6601            cudaMalloc((void**) &aux.xh, R * FF * 4) != cudaSuccess ||
6602            cudaHostAlloc((void**) &aux.hy, R * D * 4, cudaHostAllocPortable) != cudaSuccess) {
6603            err = "DS4_AUX_GPU: its buffers could not be had";
6604            return false;
6605        }
6606        size_t fr = 0, tot = 0;
6607        cudaMemGetInfo(&fr, &tot);
6608        const double want_gb = std::getenv("DS4_AUX_GB") ? std::atof(std::getenv("DS4_AUX_GB")) : 0.0;
6609        const size_t margin = (size_t) (std::getenv("DS4_AUX_MARGIN_MB") ? std::atol(std::getenv("DS4_AUX_MARGIN_MB")) : 700) << 20;
6610        size_t budget = fr > margin ? fr - margin : 0;
6611        if (want_gb > 0) budget = std::min(budget, (size_t) (want_gb * 1e9));
6612        // the candidates: experts neither VRAM nor a RAM copy holds, hottest first by the profile
6613        std::vector<std::pair<uint32_t, std::pair<int, int>>> cand;
6614        for (Layer& l : L) {
6615            if (l.mtp || l.il >= g.nl || l.lay.fmt != gg::kFmtMXFP4 || gg::mx_experts(l.lay) || l.nm != 1) continue;
6616            const uint32_t* p = prof.data() + (size_t) l.il * g.n_exp;
6617            for (int e = 0; e < l.n_exp; ++e)
6618                if (l.slot[(size_t) e] < 0 && (l.ram.empty() || l.ram[(size_t) e] < 0)) cand.push_back({p[e], {l.il, e}});
6619        }
6620        std::stable_sort(cand.begin(), cand.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
6621        size_t bmax = 0;
6622        for (const auto& c : cand) bmax = std::max(bmax, L[(size_t) c.second.first].blob);
6623        ac.rate = std::max(0, (int) env_f("DS4_AUX_CACHE", 0.0f));
6624        ac.slot_bytes = (bmax + 255) & ~(size_t) 255;   // (with the cache every slot takes the largest blob: any expert fits any slot)
6625        const size_t spares = (size_t) ac.rate * 2;   // (the reads in flight land in spare slots)
6626        if (spares * ac.slot_bytes < budget) budget -= spares * ac.slot_bytes;
6627        else ac.rate = 0;
6628        size_t need = 0, take = 0;
6629        for (; take < cand.size(); ++take) {
6630            const size_t b = ac.rate > 0 ? ac.slot_bytes : (L[(size_t) cand[take].second.first].blob + 255) & ~(size_t) 255;
6631            if (need + b > budget) break;
6632            need += b;
6633        }
6634        if (ac.rate > 0) need += spares * ac.slot_bytes;
6635        if (take == 0 || cudaMalloc((void**) &aux.arena, need) != cudaSuccess) {
6636            (void) cudaGetLastError();
6637            err = "DS4_AUX_GPU: no room for experts";
6638            return false;
6639        }
6640        aux.arena_bytes = need;
6641        const double t0 = now_ms();
6642        std::vector<uint8_t> blob;
6643        for (size_t i = 0; i < take; ++i) {
6644            Layer& l = L[(size_t) cand[i].second.first];
6645            const int e = cand[i].second.second;
6646            blob.resize(l.blob);
6647            if (!read_mx_file(l, e, blob.data())) {
6648                err = "DS4_AUX_GPU: reading an expert failed";
6649                return false;
6650            }
6651            uint8_t* dst = aux.arena + aux.used;
6652            if (cudaMemcpy(dst, blob.data(), l.blob, cudaMemcpyHostToDevice) != cudaSuccess) {
6653                err = "DS4_AUX_GPU: copying an expert failed";
6654                return false;
6655            }
6656            aux.used += ac.rate > 0 ? ac.slot_bytes : (l.blob + 255) & ~(size_t) 255;
6657            aux_set(l, e, dst);
6658            ac.owner.push_back(l.il * g.n_exp + e);
6659        }
6660        aux.n_experts = (int) take;
6661        if (ac.rate > 0) aux_cache_init(need);
6662        cudaSetDevice(prev);
6663        std::fprintf(stderr, "ds4: expert GPU %d: %d experts (%.2f GB) of %zu candidates, in %.1f s\n", aux.dev, aux.n_experts,
6664                     need / 1e9, cand.size(), (now_ms() - t0) / 1000.0);
6665        return true;
6666    }
6667    void aux_set(Layer& l, int e, uint8_t* dst) {   // expert e's matrices at dst in the expert GPU's arena
6668        if (l.aux.empty()) {
6669            l.aux.assign((size_t) l.n_exp, 0);
6670            l.avm.assign((size_t) l.n_exp, {});
6671        }
6672        l.aux[(size_t) e] = 1;
6673        for (int r = 0; r < 3; ++r) {
6674            x3::Mat& m = l.avm[(size_t) e][(size_t) r];
6675            m = x3::Mat{};
6676            m.K = gg::expert_type(l.lay, r);
6677            m.fmt = m.K == gg::kTypeMXFP4 ? gg::kFmtMXFP4 : gg::kFmtGG;
6678            m.raw = dst + l.lay.trellis[r];
6679            m.k = r < 2 ? g.dim : g.ff;
6680            m.n = r < 2 ? g.ff : g.dim;
6681        }
6682    }
6683    // ---- DS4_AUX_CACHE=N: the expert GPU's experts follow the decode instead of staying the profile's.  Each window tick
6684    // (decode and verify windows; not a prompt's chunks) up to N of the hottest CPU-lane picks not on it are read from the
6685    // files into spare slots of its arena by a thread of their own, each against its coldest expert by a decayed heat of the
6686    // picks (half-life DS4_AUX_HALF tokens, 64; the prompt's picks count 16/T each).  The next tick waits for them all and
6687    // swaps them in, in queue order: which experts it computes depends on the routing alone, never on the reads' timing
6688    // (DS4_AUX_ASYNC=1: a tick swaps in what has landed and waits for nothing - only the rounding of a few tokens moves).
6689    struct AuxCache {
6690        int rate = 0;
6691        bool async = false;   // DS4_AUX_ASYNC=1: a tick takes the swaps that have landed and waits for none (timing decides when)
6692        size_t slot_bytes = 0;
6693        float half = 64.0f;
6694        std::vector<int> owner;                  // slot -> layer * n_exp + e (-1: spare)
6695        std::vector<int> spare;
6696        std::vector<float> heat;                 // (layer, e) -> the picks' heat at `at`
6697        std::vector<double> at;
6698        std::vector<char> pending;
6699        double clock = 0;
6700        struct Job {
6701            int layer = 0, in = 0, out = 0, slot = 0;
6702            bool ok = false;
6703        };
6704        std::vector<Job> queue, done;
6705        int inflight = 0;
6706        std::mutex mu;
6707        std::condition_variable cv, done_cv;
6708        std::thread th;
6709        uint8_t* pin = nullptr;
6710        cudaStream_t cs = nullptr;
6711        int64_t swaps = 0;
6712    } ac;
6713    void aux_cache_init(size_t arena_bytes) {
6714        const size_t nslots = arena_bytes / ac.slot_bytes;
6715        ac.owner.resize(nslots, -1);
6716        for (size_t s = (size_t) aux.n_experts; s < nslots; ++s) ac.spare.push_back((int) s);
6717        const size_t n = (size_t) g.nl * (size_t) g.n_exp;
6718        ac.heat.assign(n, 0.0f);
6719        ac.at.assign(n, 0.0);
6720        ac.pending.assign(n, 0);
6721        ac.half = env_f("DS4_AUX_HALF", 64.0f);
6722        ac.async = env_f("DS4_AUX_ASYNC", 0.0f) != 0.0f;
6723        if (cudaStreamCreateWithFlags(&ac.cs, cudaStreamNonBlocking) != cudaSuccess ||
6724            cudaHostAlloc((void**) &ac.pin, ac.slot_bytes, cudaHostAllocPortable) != cudaSuccess) {
6725            ac.rate = 0;
6726            return;
6727        }
6728        for (Layer& l : L)   // (every layer it can take experts of: a table to flip)
6729            if (!l.mtp && l.il < g.nl && l.lay.fmt == gg::kFmtMXFP4 && !gg::mx_experts(l.lay) && l.nm == 1 && l.aux.empty()) {
6730                l.aux.assign((size_t) l.n_exp, 0);
6731                l.avm.assign((size_t) l.n_exp, {});
6732            }
6733        ac.th = std::thread([this] { aux_cache_loop(); });
6734        std::fprintf(stderr, "ds4: expert GPU cache: up to %d swaps a window, %zu spare slots, heat half-life %.0f tokens\n", ac.rate,
6735                     ac.spare.size(), ac.half);
6736    }
6737    void aux_cache_loop() {
6738        cudaSetDevice(aux.dev);
6739        for (;;) {
6740            AuxCache::Job j;
6741            {
6742                std::unique_lock<std::mutex> lk(ac.mu);
6743                ac.cv.wait(lk, [&] { return !ac.queue.empty() || quit.load(); });
6744                if (quit.load()) return;
6745                j = ac.queue.front();
6746                ac.queue.erase(ac.queue.begin());
6747            }
6748            const Layer& l = L[(size_t) j.layer];
6749            j.ok = read_mx_file(l, j.in, ac.pin) &&
6750                   cudaMemcpyAsync(aux.arena + (size_t) j.slot * ac.slot_bytes, ac.pin, l.blob, cudaMemcpyHostToDevice, ac.cs) == cudaSuccess &&
6751                   cudaStreamSynchronize(ac.cs) == cudaSuccess;
6752            {
6753                std::lock_guard<std::mutex> lk(ac.mu);
6754                ac.done.push_back(j);
6755                --ac.inflight;
6756            }
6757            ac.done_cv.notify_all();
6758        }
6759    }
6760    float aux_heat(int key) {   // (key's heat decayed to now)
6761        const double dt = ac.clock - ac.at[(size_t) key];
6762        if (dt > 0) {
6763            ac.heat[(size_t) key] *= (float) std::exp2(-dt / ac.half);
6764            ac.at[(size_t) key] = ac.clock;
6765        }
6766        return ac.heat[(size_t) key];
6767    }
6768    // at a window boundary (the lane idle), before the VRAM cache takes this window's hits
6769    void aux_tick(int T) {
6770        if (ac.rate <= 0) return;
6771        std::vector<AuxCache::Job> jobs;
6772        {
6773            std::unique_lock<std::mutex> lk(ac.mu);
6774            if (!ac.async) ac.done_cv.wait(lk, [&] { return ac.inflight == 0 || quit.load(); });
6775            jobs.swap(ac.done);
6776        }
6777        std::sort(jobs.begin(), jobs.end(), [](const AuxCache::Job& a, const AuxCache::Job& b) { return a.slot < b.slot; });
6778        for (const AuxCache::Job& j : jobs) {
6779            Layer& l = L[(size_t) j.layer];
6780            Layer& lo = L[(size_t) (j.out / g.n_exp)];
6781            const int out = j.out % g.n_exp, vs = (int) (std::find(ac.owner.begin(), ac.owner.end(), j.out) - ac.owner.begin());
6782            ac.pending[(size_t) (j.layer * g.n_exp + j.in)] = 0;
6783            ac.pending[(size_t) j.out] = 0;
6784            if (!j.ok || vs >= (int) ac.owner.size()) {
6785                ac.spare.push_back(j.slot);
6786                continue;
6787            }
6788            lo.aux[(size_t) out] = 0;
6789            ac.owner[(size_t) vs] = -1;
6790            ac.spare.push_back(vs);
6791            aux_set(l, j.in, aux.arena + (size_t) j.slot * ac.slot_bytes);
6792            ac.owner[(size_t) j.slot] = j.layer * g.n_exp + j.in;
6793            ++ac.swaps;
6794            ++st.aux_swaps;
6795        }
6796        std::sort(ac.spare.begin(), ac.spare.end());
6797        ac.clock += T;
6798        const float w = T <= 16 ? 1.0f : 16.0f / (float) T;
6799        std::vector<int> cand;
6800        for (const Layer& l : L) {
6801            if (l.mtp || l.il >= g.nl || l.aux.empty()) continue;
6802            for (int e : l.cpu_hits) {
6803                const int key = l.il * g.n_exp + e;
6804                aux_heat(key);
6805                ac.heat[(size_t) key] += w;
6806                if (!l.aux[(size_t) e] && l.slot[(size_t) e] < 0) cand.push_back(key);
6807            }
6808        }
6809        if (T > 16 || cand.empty()) return;
6810        std::sort(cand.begin(), cand.end());
6811        cand.erase(std::unique(cand.begin(), cand.end()), cand.end());
6812        cand.erase(std::remove_if(cand.begin(), cand.end(), [&](int k) {
6813                       const Layer& l = L[(size_t) (k / g.n_exp)];
6814                       return l.aux[(size_t) (k % g.n_exp)] || l.slot[(size_t) (k % g.n_exp)] >= 0 || ac.pending[(size_t) k];
6815                   }), cand.end());
6816        if (cand.empty()) return;
6817        std::stable_sort(cand.begin(), cand.end(), [&](int a, int b) { return ac.heat[(size_t) a] > ac.heat[(size_t) b]; });
6818        // the victims: the coldest of its experts (one VRAM holds now first: its copy here is idle)
6819        std::vector<std::pair<float, int>> vic;
6820        for (int k : ac.owner)
6821            if (k >= 0 && !ac.pending[(size_t) k]) {
6822                const Layer& l = L[(size_t) (k / g.n_exp)];
6823                vic.push_back({l.slot[(size_t) (k % g.n_exp)] >= 0 ? -1.0f : aux_heat(k), k});
6824            }
6825        const size_t n = std::min({(size_t) ac.rate, cand.size(), vic.size(), ac.spare.size()});
6826        std::partial_sort(vic.begin(), vic.begin() + (long) n, vic.end());
6827        std::vector<AuxCache::Job> q;
6828        for (size_t i = 0; i < n; ++i) {
6829            const int k = cand[i];
6830            if (!(ac.heat[(size_t) k] > vic[i].first * c_margin + c_bonus)) break;
6831            AuxCache::Job j;
6832            j.layer = k / g.n_exp;
6833            j.in = k % g.n_exp;
6834            j.out = vic[i].second;
6835            j.slot = ac.spare.front();
6836            ac.spare.erase(ac.spare.begin());
6837            ac.pending[(size_t) k] = 1;
6838            ac.pending[(size_t) j.out] = 1;
6839            q.push_back(j);
6840        }
6841        if (q.empty()) return;
6842        {
6843            std::lock_guard<std::mutex> lk(ac.mu);
6844            ac.queue.insert(ac.queue.end(), q.begin(), q.end());
6845            ac.inflight += (int) q.size();
6846        }
6847        ac.cv.notify_one();
6848    }
6849    // the expert GPU's rows of request r (apicks: (expert, t * kPicks + i) sorted) started; returns their number (0: none)
6850    int aux_launch(const Layer& l, const Req& r, int T, const std::vector<std::pair<int, int>>& apicks) {
6851        const int n = (int) apicks.size();
6852        if (n == 0) return 0;
6853        const int D = g.dim, FF = g.ff;
6854        int prev = 0;
6855        cudaGetDevice(&prev);
6856        cudaSetDevice(aux.dev);
6857        cudaMemcpy2DAsync(aux.xin, (size_t) D * 4, &r.x[0][0], (size_t) kMaxDim * 4, (size_t) D * 4, (size_t) T,
6858                          cudaMemcpyHostToDevice, aux.st);
6859        Gather ga;
6860        for (int k = 0; k < n; ++k) ga.src[k] = apicks[(size_t) k].second / kPicks;
6861        gather_rows(aux.xin, ga, n, D, aux.xe, aux.st);
6862        x3::MvJob j[2 * kWin * kPicks];
6863        int nj = 0;
6864        for (int a = 0; a < n;) {   // (an expert's rows side by side)
6865            int b = a;
6866            while (b < n && apicks[(size_t) b].first == apicks[(size_t) a].first) ++b;
6867            const auto& m = l.avm[(size_t) apicks[(size_t) a].first];
6868            j[nj++] = job(m[0], aux.xe + (size_t) a * D, aux.xg + (size_t) a * FF, b - a, D, FF);
6869            j[nj++] = job(m[1], aux.xe + (size_t) a * D, aux.xu + (size_t) a * FF, b - a, D, FF);
6870            a = b;
6871        }
6872        for (int a = 0; a < nj; a += x3::kMaxMvJobs) mv_any(j + a, std::min(x3::kMaxMvJobs, nj - a), aux.st);
6873        swiglu(aux.xg, aux.xu, n * FF, g.lim, aux.xh, aux.st);
6874        nj = 0;
6875        for (int a = 0; a < n;) {
6876            int b = a;
6877            while (b < n && apicks[(size_t) b].first == apicks[(size_t) a].first) ++b;
6878            j[nj++] = job(l.avm[(size_t) apicks[(size_t) a].first][2], aux.xh + (size_t) a * FF, aux.ye + (size_t) a * D, b - a, FF, D);
6879            a = b;
6880        }
6881        for (int a = 0; a < nj; a += x3::kMaxMvJobs) mv_any(j + a, std::min(x3::kMaxMvJobs, nj - a), aux.st);
6882        cudaMemcpyAsync(aux.hy, aux.ye, (size_t) n * D * 4, cudaMemcpyDeviceToHost, aux.st);
6883        cudaEventRecord(aux.ev, aux.st);
6884        cudaSetDevice(prev);
6885        return n;
6886    }
6887    void aux_wait() {
6888        const double t0 = now_ms();
6889        if (cudaEventSynchronize(aux.ev) != cudaSuccess) {
6890            std::fprintf(stderr, "ds4: expert GPU: %s\n", cudaGetErrorString(cudaGetLastError()));
6891            std::abort();
6892        }
6893        static const bool prof_on = std::getenv("DS4_PROF") != nullptr;
6894        if (prof_on) {   // (DS4_PROF: how long the CPU lane waits for the expert GPU after its own work)
6895            static double acc[2] = {};
6896            acc[0] += now_ms() - t0;
6897            if (++acc[1] == 2000) std::fprintf(stderr, "ds4 prof expert GPU: the CPU lane waited %.3f ms a request for it\n", acc[0] / acc[1]);
6898        }
6899    }
6900    // DS4_MISS_SPLIT=0: the old order (wait for every read, then compute); default: the entries whose reads are done
6901    // computed first, the others each as its read lands (the same bits: every entry's rows are independent)
6902    void cpu_experts(const Layer& l, const float* x, const std::vector<Ent>& ents, size_t ldx = 0,
6903                     const int* ord = nullptr) {
6904        if (ldx == 0) ldx = (size_t) g.dim;
6905        if (l.lay.fmt == gg::kFmtMXFP4) {
6906            StoreHold hold(this, l, ents);
6907            static const bool stream = std::getenv("DS4_LANE_STREAM") != nullptr && std::atoi(std::getenv("DS4_LANE_STREAM")) != 0;
6908            if (stream && hold.m && NH == 1 && !gg::mx_experts(l.lay)) return cpu_experts_iq_stream(l, x, ents, ldx, ord, hold);
6909            static const bool split = std::getenv("DS4_MISS_SPLIT") == nullptr || std::atoi(std::getenv("DS4_MISS_SPLIT")) != 0;
6910            if (!split || ord != nullptr || !hold.m || ents.size() < 2) {
6911                hold.wait_all();
6912                return cpu_experts_mx(l, x, ents, ldx, ord);
6913            }
6914            std::vector<Ent> hot, cold;
6915            for (const Ent& en : ents) (hold.ready(en.e) ? hot : cold).push_back(en);
6916            if (cold.empty()) {
6917                hold.wait_all();
6918                return cpu_experts_mx(l, x, ents, ldx, ord);
6919            }
6920            for (const Ent& en : hot) hold.wait_expert(en.e);   // (done reading: only the bookkeeping)
6921            if (!hot.empty()) cpu_experts_mx(l, x, hot, ldx, nullptr);
6922            // the ones that came in meanwhile first, then the rest in the order they land
6923            std::vector<char> done(cold.size(), 0);
6924            for (size_t left = cold.size(); left > 0;) {
6925                size_t pick = cold.size();
6926                for (size_t i = 0; i < cold.size(); ++i)
6927                    if (!done[i] && hold.ready(cold[i].e)) {
6928                        pick = i;
6929                        break;
6930                    }
6931                if (pick == cold.size())
6932                    for (size_t i = 0; i < cold.size(); ++i)
6933                        if (!done[i]) {
6934                            pick = i;
6935                            break;
6936                        }
6937                hold.wait_expert(cold[pick].e);
6938                std::vector<Ent> one(1, cold[pick]);
6939                cpu_experts_mx(l, x, one, ldx, nullptr);
6940                done[pick] = 1;
6941                --left;
6942            }
6943            return;
6944        }
6945        const int E = g.dim, FF = g.ff, FFh = FF / NH, Eh = E / NH, GQ = E / 256, DQ = FF / 128;
6946        const int GB = FFh / 128, DB = Eh / 128, EB = E / 128, FB = FF / 128;
6947        const int ne = (int) ents.size();
6948        const float lim = g.lim;
6949        auto part = [&](int e, int X, int r) {
6950            const uint8_t* b = l.hh[(size_t) e][(size_t) X];
6951            kc::Exl3Part p;
6952            p.trellis = (const uint32_t*) (b + l.hl.trellis[r]);
6953            p.suh = (const uint16_t*) (b + l.hl.suh[r]);
6954            p.svh = (const uint16_t*) (b + l.hl.svh[r]);
6955            p.k = l.hl.k[r];
6956            p.n = l.hl.n[r];
6957            p.K = l.lay.K[r];
6958            return p;
6959        };
6960        auto xh = [&](int X, int sl, int r) { return c_xh.data() + ((size_t) (X * kSlots + sl) * 2 + r) * E; };
6961        auto xsb = [&](int X, int sl, int r) { return c_xsb.data() + ((size_t) (X * kSlots + sl) * 2 + r) * EB; };
6962        auto acc = [&](int X, int sl, int r, int q) {
6963            return c_acc.data() + (((size_t) (X * kSlots + sl) * 2 + r) * GQ + q) * FFh;
6964        };
6965        auto xhd = [&](int sl) { return c_xhd.data() + (size_t) sl * FF; };
6966        auto xsd = [&](int sl) { return c_xsd.data() + (size_t) sl * FB; };
6967        auto accd = [&](int X, int sl, int q) { return c_accd.data() + ((size_t) (X * kSlots + sl) * DQ + q) * Eh; };
6968        std::function<void(int)> f[4];
6969        for (int X = 0; X < NH; ++X)
6970            f[X] = [&, X](int j) {
6971                const Ent& en = ents[(size_t) (j / (2 * GQ))];
6972                const int r = (j / GQ) % 2, q = j % GQ;
6973                const kc::Exl3Part p = part(en.e, X, r);
6974                const float* xp[kc::kExl3CpuMaxN];
6975                float* ap[kc::kExl3CpuMaxN];
6976                for (int i = 0; i < en.n; ++i) {
6977                    const int sl = en.slot0 + i;
6978                    const float* xt = x + (size_t) en.tok[i] * ldx;
6979                    for (int b = 2 * q; b < 2 * q + 2; ++b)
6980                        xsb(X, sl, r)[b] = kc::exl3_cpu_prepare_block(p.suh + b * 128, xt + b * 128, xh(X, sl, r) + b * 128);
6981                    xp[i] = xh(X, sl, r);
6982                    ap[i] = acc(X, sl, r, q);
6983                }
6984                if (en.n == 1) kc::exl3_cpu_rows_acc(p, xp[0], q * 16, (q + 1) * 16, ap[0]);
6985                else kc::exl3_cpu_rows_acc_n(p, xp, en.n, q * 16, (q + 1) * 16, ap);
6986            };
6987        run_nodes(ne * 2 * GQ, f);
6988        for (int X = 0; X < NH; ++X)
6989            f[X] = [&, X](int j) {
6990                const Ent& en = ents[(size_t) (j / GB)];
6991                const int b = j % GB;
6992                const kc::Exl3Part pg = part(en.e, X, 0), pu = part(en.e, X, 1), pd = part(en.e, X, 2);
6993                for (int i = 0; i < en.n; ++i) {
6994                    const int sl = en.slot0 + i;
6995                    float y[2][128], a[128], hb[128];
6996                    for (int r = 0; r < 2; ++r) {
6997                        for (int c = 0; c < 128; ++c) a[c] = 0.0f;
6998                        for (int q = 0; q < GQ; ++q) {
6999                            const float* aq = acc(X, sl, r, q) + b * 128;
7000                            for (int c = 0; c < 128; ++c) a[c] += aq[c];
7001                        }
7002                        double xs = 0.0;
7003                        for (int k = 0; k < EB; ++k) xs += xsb(X, sl, r)[k];
7004                        kc::exl3_cpu_band_out(r == 0 ? pg : pu, a, (float) xs, b * 128, y[r]);
7005                    }
7006                    for (int c = 0; c < 128; ++c) {
7007                        float gv = y[0][c], uv = y[1][c];
7008                        if (lim > 0.0f) {
7009                            gv = std::min(gv, lim);
7010                            uv = std::min(std::max(uv, -lim), lim);
7011                        }
7012                        hb[c] = gv / (1.0f + std::exp(-gv)) * uv;
7013                    }
7014                    const int gb = X * GB + b;
7015                    xsd(sl)[gb] = kc::exl3_cpu_prepare_block(pd.suh + gb * 128, hb, xhd(sl) + gb * 128);
7016                }
7017            };
7018        run_nodes(ne * GB, f);
7019        for (int X = 0; X < NH; ++X)
7020            f[X] = [&, X](int j) {
7021                const Ent& en = ents[(size_t) (j / DQ)];
7022                const int q = j % DQ;
7023                const kc::Exl3Part p = part(en.e, X, 2);
7024                const float* xp[kc::kExl3CpuMaxN];
7025                float* ap[kc::kExl3CpuMaxN];
7026                for (int i = 0; i < en.n; ++i) {
7027                    xp[i] = xhd(en.slot0 + i);
7028                    ap[i] = accd(X, en.slot0 + i, q);
7029                }
7030                if (en.n == 1) kc::exl3_cpu_rows_acc(p, xp[0], q * 8, (q + 1) * 8, ap[0]);
7031                else kc::exl3_cpu_rows_acc_n(p, xp, en.n, q * 8, (q + 1) * 8, ap);
7032            };
7033        run_nodes(ne * DQ, f);
7034        for (int X = 0; X < NH; ++X)
7035            f[X] = [&, X](int j) {
7036                const Ent& en = ents[(size_t) (j / DB)];
7037                const int b = j % DB;
7038                const kc::Exl3Part pd = part(en.e, X, 2);
7039                for (int i = 0; i < en.n; ++i) {
7040                    const int sl = en.slot0 + i;
7041                    float a[128];
7042                    for (int c = 0; c < 128; ++c) a[c] = 0.0f;
7043                    for (int q = 0; q < DQ; ++q) {
7044                        const float* aq = accd(X, sl, q) + b * 128;
7045                        for (int c = 0; c < 128; ++c) a[c] += aq[c];
7046                    }
7047                    double xs = 0.0;
7048                    for (int k = 0; k < FB; ++k) xs += xsd(sl)[k];
7049                    kc::exl3_cpu_band_out(pd, a, (float) xs, b * 128, c_yd.data() + (size_t) sl * E + (size_t) X * Eh + b * 128);
7050                }
7051            };
7052        run_nodes(ne * DB, f);
7053    }
7054
7055    // ---- the expert cache.  A swap moves a CPU-lane expert (`in`) into the layer's spare VRAM slot and the VRAM expert it
7056    // replaces (`out`) into the spare host parts - both copies of weights that do not change, made while the model runs
7057    // (the copy stream, the host's repacking) - and cache_tick switches the tables between windows, so the device's
7058    // table and the host's view of a layer always agree within a window.  In place (file_experts) `out` needs no copy:
7059    // the CPU lane reads it from the file again.
7060    void ram_loop() {   // the RAM tier's moves in: an expert read from the file into a free slot
7061        for (;;) {
7062            RamSwap rs;
7063            {
7064                std::unique_lock<std::mutex> lk(sw_mu);
7065                ram_cv.wait(lk, [&] { return quit.load() || !ram_queue.empty(); });
7066                if (quit.load()) return;
7067                rs = ram_queue.front();
7068                ram_queue.pop_front();
7069            }
7070            const Layer& l = L[(size_t) rs.layer];
7071            if (read_mx_file(l, rs.in, ram_slots[(size_t) rs.slot])) {
7072                for (int r = 0; r < 3; ++r)   // (one copy of it in RAM)
7073                    os::advise(pk.fds[(size_t) l.mx_file[r]], l.mx_off[r] + (uint64_t) rs.in * l.mx_stride[r],
7074                               mx_part_bytes(l, r), false);
7075            } else {
7076                rs.in = -1;   // (failed: the slot goes back)
7077            }
7078            std::lock_guard<std::mutex> lk(sw_mu);
7079            ram_ready.push_back(rs);
7080        }
7081    }
7082
7083    void cache_loop(SwapBufs& B) {
7084        for (;;) {
7085            Swap sw;
7086            {
7087                std::unique_lock<std::mutex> lk(sw_mu);
7088                sw_cv.wait(lk, [&] { return quit.load() || !sw_queue.empty(); });
7089                if (quit.load()) return;
7090                sw = sw_queue.front();
7091                sw_queue.pop_front();
7092            }
7093            Layer& l = L[(size_t) sw.layer];
7094            if (l.lay.fmt == gg::kFmtMXFP4) {   // in: from the file; out: nothing to keep (the file has it)
7095                swap_in_mx(l, sw, B);
7096                std::lock_guard<std::mutex> lk(sw_mu);
7097                sw_ready.push_back(sw);
7098                sw_done_cv.notify_one();
7099                continue;
7100            }
7101            parts_to_blob(l, l.hh[(size_t) sw.in], B.a);
7102            if (l.nm == 1) {
7103                const Dev& d = devs[(size_t) l.dev];
7104                cudaSetDevice(d.id);
7105                cudaStream_t cs = B.st[(size_t) l.dev];
7106                cudaMemcpyAsync(l.vram_base + (size_t) l.spare_vram * l.blob, B.a, l.blob, cudaMemcpyHostToDevice, cs);
7107                if (!file_experts)
7108                    cudaMemcpyAsync(B.b, l.vram_base + (size_t) l.slot[(size_t) sw.out] * l.blob, l.blob,
7109                                    cudaMemcpyDeviceToHost, cs);
7110                cudaStreamSynchronize(cs);
7111            } else {   // a group: each member's part in, each member's part out
7112                for (int m = 0; m < l.nm; ++m) {
7113                    const Layer& x = member(l, m);
7114                    cudaSetDevice(devs[(size_t) x.dev].id);
7115                    cudaStream_t cs = B.st[(size_t) x.dev];
7116                    blob_to_half(l, B.a, m, B.h);
7117                    cudaMemcpyAsync(x.vram_base + (size_t) l.spare_vram * x.hblob, B.h, x.hblob, cudaMemcpyHostToDevice, cs);
7118                    cudaStreamSynchronize(cs);
7119                    if (file_experts) continue;
7120                    cudaMemcpyAsync(B.h, x.vram_base + (size_t) l.slot[(size_t) sw.out] * x.hblob, x.hblob,
7121                                    cudaMemcpyDeviceToHost, cs);
7122                    cudaStreamSynchronize(cs);
7123                    half_to_blob(l, B.h, m, B.b);
7124                }
7125            }
7126            if (!file_experts)
7127                for (int X = 0; X < NH; ++X) blob_to_part(l, B.b, X, l.spare_host[(size_t) X]);
7128            if (check_swaps) {   // DS4_CHECK_SWAPS: both moves against the model file, byte for byte
7129                std::vector<uint8_t> reg, blob(l.blob), part(l.hl.bytes);
7130                bool ok = true;
7131                for (int pass = 0; pass < (file_experts ? 1 : 2); ++pass) {   // (in place: no host copy of `out`)
7132                    const int e = pass == 0 ? sw.in : sw.out;
7133                    reg.resize(l.region_bytes[(size_t) e]);
7134                    pk.read_at(l.region_file[(size_t) e], l.region_off[(size_t) e], reg.size(), reg.data());
7135                    if (pass == 0) {
7136                        repack(l, reg.data(), blob.data());
7137                        std::vector<uint8_t> dev(l.blob);
7138                        if (l.nm == 1)
7139                            cudaMemcpy(dev.data(), l.vram_base + (size_t) l.spare_vram * l.blob, l.blob, cudaMemcpyDeviceToHost);
7140                        else
7141                            for (int m = 0; m < l.nm; ++m) {   // (the members' parts, put together again)
7142                                std::vector<uint8_t> h(member(l, m).hblob);
7143                                cudaSetDevice(devs[(size_t) member(l, m).dev].id);
7144                                cudaMemcpy(h.data(), member(l, m).vram_base + (size_t) l.spare_vram * member(l, m).hblob, member(l, m).hblob,
7145                                           cudaMemcpyDeviceToHost);
7146                                half_to_blob(l, h.data(), m, dev.data());
7147                            }
7148                        for (int r = 0; r < 3; ++r)
7149                            ok = ok && std::memcmp(dev.data() + l.lay.trellis[r], blob.data() + l.lay.trellis[r], l.piece_bytes[r][0]) == 0 &&
7150                                 std::memcmp(dev.data() + l.lay.suh[r], blob.data() + l.lay.suh[r], l.piece_bytes[r][1]) == 0 &&
7151                                 std::memcmp(dev.data() + l.lay.svh[r], blob.data() + l.lay.svh[r], l.piece_bytes[r][2]) == 0;
7152                    } else {
7153                        for (int X = 0; X < NH; ++X) {
7154                            repack_part(l, reg.data(), X, part.data());
7155                            for (int r = 0; r < 3; ++r) {
7156                                const size_t tb = (size_t) (l.hl.k[r] / 16) * (l.hl.n[r] / 16) * 32 * l.lay.K[r];
7157                                ok = ok && std::memcmp(part.data() + l.hl.trellis[r], l.spare_host[(size_t) X] + l.hl.trellis[r], tb) == 0 &&
7158                                     std::memcmp(part.data() + l.hl.suh[r], l.spare_host[(size_t) X] + l.hl.suh[r], (size_t) l.hl.k[r] * 2) == 0 &&
7159                                     std::memcmp(part.data() + l.hl.svh[r], l.spare_host[(size_t) X] + l.hl.svh[r], (size_t) l.hl.n[r] * 2) == 0;
7160                            }
7161                        }
7162                    }
7163                }
7164                std::fprintf(stderr, "ds4 cache: layer %d expert %d in, %d out: %s\n", l.il, sw.in, sw.out,
7165                             ok ? "both match the model file" : "MISMATCH");
7166            }
7167            std::lock_guard<std::mutex> lk(sw_mu);
7168            sw_ready.push_back(sw);
7169                sw_done_cv.notify_one();
7170        }
7171    }
7172
7173    // a GGUF's swap: expert sw.in from the file (copy_mode: its copy) into the spare VRAM slot (each member its part);
7174    // the expert it replaces goes back to the CPU lane, which reads it from the file's mapping - or (copy_mode, sw.ram)
7175    // from the layer's spare RAM slot, which it is copied into from VRAM here
7176    void swap_in_mx(Layer& l, Swap& sw, SwapBufs& B) {
7177        uint8_t *sw_a = B.a, *sw_b = B.b, *sw_h = B.h;   // (this thread's)
7178        const std::vector<cudaStream_t>& copy_st = B.st;
7179        bool ok = copy_mode ? read_mx(l, sw.in, sw_a) : read_mx_file(l, sw.in, sw_a);   // (a copy holds its slot till
7180                                                                                          // this swap's switch)
7181        for (int m = 0; m < l.nm && ok; ++m) {
7182            const Layer& x = member(l, m);
7183            cudaSetDevice(devs[(size_t) x.dev].id);
7184            cudaStream_t cs = copy_st[(size_t) x.dev];
7185            if (l.nm > 1) blob_to_half(l, sw_a, m, sw_h);
7186            ok = cudaMemcpyAsync(x.vram_base + (size_t) l.spare_vram * unit(l), l.nm > 1 ? sw_h : sw_a, unit(l),
7187                                 cudaMemcpyHostToDevice, cs) == cudaSuccess &&
7188                 cudaStreamSynchronize(cs) == cudaSuccess;
7189        }
7190        if (sw.ram >= 0) {   // `out` from its VRAM slot (each member its part) into the spare RAM slot
7191            bool got = ok;
7192            for (int m = 0; m < l.nm && got; ++m) {
7193                const Layer& x = member(l, m);
7194                cudaSetDevice(devs[(size_t) x.dev].id);
7195                cudaStream_t cs = copy_st[(size_t) x.dev];
7196                got = cudaMemcpyAsync(l.nm > 1 ? sw_h : sw_b, x.vram_base + (size_t) l.slot[(size_t) sw.out] * unit(l),
7197                                      unit(l), cudaMemcpyDeviceToHost, cs) == cudaSuccess &&
7198                      cudaStreamSynchronize(cs) == cudaSuccess;
7199                if (got && l.nm > 1) half_to_blob(l, sw_h, m, sw_b);
7200            }
7201            if (got) blob_to_ram(l, sw_b, sw.ram);
7202            else sw.ram = -1;   // (back to the file's pages then)
7203        }
7204        if (check_swaps) {   // DS4_CHECK_SWAPS: the slot (and `out`'s RAM copy) against the model file, byte for byte
7205            std::vector<uint8_t> dev(l.blob), h(unit(l)), file(l.blob);
7206            for (int m = 0; m < l.nm && ok; ++m) {
7207                const Layer& x = member(l, m);
7208                cudaSetDevice(devs[(size_t) x.dev].id);
7209                cudaMemcpy(l.nm > 1 ? h.data() : dev.data(), x.vram_base + (size_t) l.spare_vram * unit(l), unit(l),
7210                           cudaMemcpyDeviceToHost);
7211                if (l.nm > 1) half_to_blob(l, h.data(), m, dev.data());
7212            }
7213            ok = ok && read_mx_file(l, sw.in, file.data());
7214            for (int r = 0; r < 3 && ok; ++r)
7215                ok = std::memcmp(dev.data() + l.lay.trellis[r], file.data() + l.lay.trellis[r], mx_part_bytes(l, r)) == 0;
7216            bool ok_out = true;
7217            if (sw.ram >= 0) {
7218                ok_out = read_mx_file(l, sw.out, file.data());
7219                ram_to_blob(l, sw.ram, dev.data());
7220                for (int r = 0; r < 3 && ok_out; ++r)
7221                    ok_out = std::memcmp(dev.data() + l.lay.trellis[r], file.data() + l.lay.trellis[r], mx_part_bytes(l, r)) == 0;
7222            }
7223            std::fprintf(stderr, "ds4 cache: layer %d expert %d in, %d out%s: %s\n", l.il, sw.in, sw.out,
7224                         sw.ram >= 0 ? " (into RAM)" : "", ok && ok_out ? "matches the model file" : "MISMATCH");
7225        } else if (!ok) {
7226            std::fprintf(stderr, "ds4 cache: layer %d expert %d: the move into VRAM failed\n", l.il, sw.in);
7227        }
7228    }
7229
7230    // after a chunked prompt: the expert cache catches up with what the prompt picked at once - a window prompt gets
7231    // its swaps one tick at a time over its hundreds of windows, a chunked one has a single tick - so the decode that
7232    // follows finds the hot experts in VRAM.  Rounds of the ordinary swap rule (the hottest CPU-lane pick of each layer
7233    // in, its coldest VRAM expert out) until nothing is worth moving or DS4_SETTLE_MS (6000) is spent
7234    // DS4_SETTLE_DEFER=1: a prompt's settle runs when the next forward (or draft) starts, not before its first token is
7235    // sampled - the same moves in the same order before any later routing, so the same tokens; the first one sooner
7236    const bool settle_defer = std::getenv("DS4_SETTLE_DEFER") != nullptr && std::atoi(std::getenv("DS4_SETTLE_DEFER")) != 0;
7237    bool settle_due = false;
7238    void settle_if_due() {
7239        if (!settle_due) return;
7240        settle_due = false;
7241        cache_settle();
7242    }
7243    void cache_settle() {
7244        if (!o.expert_cache || cache_ths.empty()) return;
7245        static const double budget = env_f("DS4_SETTLE_MS", 6000.0f);
7246        if (budget <= 0.0) return;
7247        const double t0 = now_ms();
7248        const int64_t s0 = st.swaps;
7249        while (now_ms() - t0 < budget) {
7250            for (Layer& l : L) {
7251                if (l.mtp || l.spare_vram < 0 || l.swap_pending) continue;
7252                l.cpu_hits.clear();
7253                for (int e = 0; e < l.n_exp; ++e)
7254                    if (l.slot[(size_t) e] < 0 && l.heat[(size_t) e] >= 2.0f) l.cpu_hits.push_back(e);
7255            }
7256            cache_tick_swaps(0);
7257            if (sw_inflight == 0) break;   // (nothing queued: every layer's best CPU-lane expert is not hotter than its coldest VRAM one)
7258            std::this_thread::sleep_for(std::chrono::milliseconds(1));
7259        }
7260        if (store && env_f("DS4_SETTLE_STORE", 1.0f) != 0.0f) {   // the RAM store too: a window prompt fills it through the CPU
7261            // lane's picks, a chunked one streams past it - the hottest CPU-lane experts of the prompt into its free slots
7262            std::vector<std::pair<float, std::pair<int, int>>> hot;
7263            for (const Layer& l : L) {
7264                if (l.mtp) continue;
7265                for (int e = 0; e < l.n_exp; ++e)
7266                    if (l.slot[(size_t) e] < 0 && l.heat[(size_t) e] >= 4.0f && (l.aux.empty() || !l.aux[(size_t) e]))
7267                        hot.push_back({l.heat[(size_t) e], {l.il, e}});
7268            }
7269            std::sort(hot.begin(), hot.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
7270            std::vector<std::pair<int, int>> list;
7271            for (const auto& h : hot) {
7272                if (list.size() >= store->slots_max()) break;
7273                list.push_back(h.second);
7274            }
7275            const double ts = now_ms();
7276            const size_t n = store->preload(list, 0);
7277            if (o.verbose) std::fprintf(stderr, "ds4: RAM store: %zu hot experts read after the prompt (%.0f ms)\n", n, now_ms() - ts);
7278        }
7279        if (o.verbose && st.swaps > s0)
7280            std::fprintf(stderr, "ds4: expert cache: %lld swaps after the prompt (%.0f ms)\n", (long long) (st.swaps - s0),
7281                         now_ms() - t0);
7282    }
7283    void cache_tick(int T) {
7284        aux_tick(T);
7285        cache_tick_swaps(T);
7286        store_sync();
7287        cp_store_sync();
7288        store_watch();
7289    }
7290    // the store gives RAM back when the PC runs short (the owner opened something): below 4 GB free, a 0.7 GB chunk at a time
7291    // until 5 GB are free again (checked every 16 windows); it grows again by itself once 8 GB beside its chunk are free
7292    void store_watch() {
7293        if (!store) return;
7294        static int tick = 0;
7295        if (++tick % 16 != 0) return;
7296        const uint64_t avail = ram_avail();
7297        if (avail == ~uint64_t{0} || avail >= (4ull << 30)) return;
7298        const size_t chunks = 1 + (size_t) (((5ull << 30) - avail) / (700ull << 20));
7299        const size_t n = store->shrink_chunks(chunks);
7300        if (n > 0) std::fprintf(stderr, "ds4: RAM store: %.1f GB free: gave back %zu chunks (%zu slots left)\n", avail / 1e9, n, store->slots_allocated());
7301    }
7302    void cache_tick_swaps(int T) {
7303        if (!o.expert_cache || cache_ths.empty()) return;
7304        std::vector<Swap> ready;
7305        std::vector<RamSwap> rready;
7306        // Cache-Prior routes from VRAM residency, so applying only the swaps that happen to be ready would make the picks
7307        // depend on copy timing: with it on (DS4_CACHE_DET=0 turns this off), every queued swap lands first, applied in order
7308        static const bool det = [] {
7309            const char* off = std::getenv("DS4_CACHE_DET");
7310            if (off != nullptr && std::atoi(off) == 0) return false;
7311            for (const char* v : {"DS4_CP_LAMBDA", "DS4_CP_PREFILL"})
7312                if (std::getenv(v) != nullptr && std::atof(std::getenv(v)) > 0.0) return true;
7313            return off != nullptr && std::atoi(off) != 0;
7314        }();
7315        {
7316            std::unique_lock<std::mutex> lk(sw_mu);
7317            if (det) sw_done_cv.wait(lk, [&] { return sw_ready.size() >= (size_t) sw_inflight || quit.load(); });
7318            ready.swap(sw_ready);
7319            rready.swap(ram_ready);
7320        }
7321        if (det) std::sort(ready.begin(), ready.end(), [](const Swap& a, const Swap& b) { return a.layer < b.layer; });
7322        for (const RamSwap& rs : rready) {   // (nothing reads the tier between windows)
7323            --ram_inflight;
7324            Layer& l = L[(size_t) rs.layer];
7325            if (rs.in < 0 || l.ram[(size_t) rs.in] >= 0 || l.slot[(size_t) rs.in] >= 0) {
7326                ram_free.push_back(rs.slot);
7327                continue;
7328            }
7329            l.ram[(size_t) rs.in] = rs.slot;
7330            if (rs.out >= 0 && l.ram[(size_t) rs.out] >= 0) {
7331                ram_free.push_back(l.ram[(size_t) rs.out]);
7332                l.ram[(size_t) rs.out] = -1;
7333            }
7334            ++st.ram_moves;
7335        }
7336        for (const Swap& sw : ready) {
7337            Layer& l = L[(size_t) sw.layer];
7338            const int old_slot = l.slot[(size_t) sw.out];
7339            const std::array<uint8_t*, 4> old_parts = l.hh[(size_t) sw.in];
7340            if (copy_mode) {   // (`out` takes the RAM place `in` leaves: through the spare, which `in`'s slot becomes)
7341                const int s_in = l.ram[(size_t) sw.in];
7342                l.ram[(size_t) sw.in] = -1;
7343                if (sw.ram >= 0) {
7344                    l.ram[(size_t) sw.out] = sw.ram;
7345                    copy_spare[(size_t) l.il] = s_in;
7346                } else if (s_in >= 0) {   // (the move into RAM failed: `out` back to the file, one copy fewer)
7347                    --ram_held;
7348                    if (copy_spare[(size_t) l.il] < 0) copy_spare[(size_t) l.il] = s_in;
7349                }
7350            } else if (!l.ram.empty() && l.ram[(size_t) sw.in] >= 0) {   // (in VRAM now: its RAM slot for the next hottest)
7351                ram_free.push_back(l.ram[(size_t) sw.in]);
7352                l.ram[(size_t) sw.in] = -1;
7353            }
7354            l.slot[(size_t) sw.in] = l.spare_vram;
7355            if (!l.zc.empty() && l.zc[(size_t) sw.in]) {   // (VRAM's now: not the store's to compute any more)
7356                l.zc[(size_t) sw.in] = 0;
7357                if (l.zc_tab != nullptr) {   // (the device's table too: its entry pointed into the slot the store now reuses - when `in` left VRAM later,
7358                                             // zc_stage copied whatever lay there, another expert's blob, into the plan)
7359                    cudaSetDevice(devs[0].id);
7360                    cudaMemsetAsync(l.zc_tab + sw.in, 0, 8, devs[0].st);
7361                }
7362                store->unmark(l.il, sw.in);
7363            }
7364            if (l.nm == 1) set_vm(l, sw.in, l.spare_vram);
7365            l.hh[(size_t) sw.in] = {nullptr, nullptr, nullptr, nullptr};
7366            l.host[(size_t) sw.in] = nullptr;
7367            l.slot[(size_t) sw.out] = -1;
7368            if (l.lay.fmt == gg::kFmtMXFP4) {   // (the file has it)
7369                l.host[(size_t) sw.out] = (uint8_t*) mx_mat(l, sw.out, 0);
7370            } else if (file_experts) {   // (back to its pages in the file)
7371                l.hh[(size_t) sw.out] = {file_part(l, sw.out), nullptr, nullptr, nullptr};
7372                l.host[(size_t) sw.out] = l.hh[(size_t) sw.out][0];
7373            } else {
7374                l.hh[(size_t) sw.out] = l.spare_host;
7375                l.host[(size_t) sw.out] = l.spare_host[0];
7376                l.spare_host = old_parts;
7377            }
7378            l.spare_vram = old_slot;
7379            for (int m = 0; m < l.nm; ++m) {
7380                Layer& x = member(l, m);
7381                const Dev& dm = devs[(size_t) x.dev];
7382                l.tab_pin[2 * m] = (unsigned long long) (x.vram_base + (size_t) l.slot[(size_t) sw.in] * unit(x));
7383                l.tab_pin[2 * m + 1] = 0ull;
7384                cudaSetDevice(dm.id);   // (stream order: before the next window)
7385                cudaMemcpyAsync(x.vram_tab + sw.in, &l.tab_pin[2 * m], 8, cudaMemcpyHostToDevice, dm.st);
7386                cudaMemcpyAsync(x.vram_tab + sw.out, &l.tab_pin[2 * m + 1], 8, cudaMemcpyHostToDevice, dm.st);
7387            }
7388            l.swap_pending = false;
7389            --sw_inflight;
7390            ++st.swaps;
7391        }
7392        decay_tokens += T;
7393        if (decay_tokens >= 256) {   // older use counts less: x0.9 every 256 tokens
7394            decay_tokens = 0;
7395            for (Layer& l : L)
7396                for (float& h : l.heat) h *= c_decay;
7397        }
7398        bool queued = false, rqueued = false;
7399        for (Layer& l : L) {
7400            if (l.cpu_hits.empty()) continue;
7401            std::vector<int> hits;
7402            hits.swap(l.cpu_hits);
7403            int best = -1, vin = -1;
7404            for (int e : hits)
7405                if (l.slot[(size_t) e] < 0 && (best < 0 || l.heat[(size_t) e] > l.heat[(size_t) best])) best = e;
7406            if (best >= 0 && l.spare_vram >= 0 && !l.swap_pending && sw_inflight < c_inflight) {   // VRAM: the hottest in
7407                int cold = -1;
7408                for (int e = 0; e < l.n_exp; ++e)
7409                    if (l.slot[(size_t) e] >= 0 && (cold < 0 || l.heat[(size_t) e] < l.heat[(size_t) cold])) cold = e;
7410                if (cold >= 0 && l.heat[(size_t) best] > l.heat[(size_t) cold] * c_margin + c_bonus) {
7411                    l.swap_pending = true;
7412                    ++sw_inflight;
7413                    vin = best;
7414                    Swap sw{l.il, best, cold};
7415                    if (copy_mode && l.ram[(size_t) best] >= 0) sw.ram = copy_spare[(size_t) l.il];   // (-1: none)
7416                    std::lock_guard<std::mutex> lk(sw_mu);
7417                    sw_queue.push_back(sw);
7418                    queued = true;
7419                }
7420            }
7421            if (l.ram.empty() || ram_free.empty() || ram_inflight >= kMaxSwaps) continue;
7422            int rb = -1;   // RAM: the hottest read from the file, in place of the layer's coldest held (or a free slot)
7423            for (int e : hits)
7424                if (e != vin && l.slot[(size_t) e] < 0 && l.ram[(size_t) e] < 0 &&
7425                    (rb < 0 || l.heat[(size_t) e] > l.heat[(size_t) rb]))
7426                    rb = e;
7427            if (rb < 0) continue;
7428            int rc = -1;
7429            for (int e = 0; e < l.n_exp; ++e)
7430                if (l.ram[(size_t) e] >= 0 && (rc < 0 || l.heat[(size_t) e] < l.heat[(size_t) rc])) rc = e;
7431            const bool room = ram_free.size() > 1;   // (slots VRAM freed: filled at once)
7432            if (!room && !(rc >= 0 && l.heat[(size_t) rb] > l.heat[(size_t) rc] * 1.25f + 1.0f)) continue;
7433            RamSwap rs;
7434            rs.layer = l.il;
7435            rs.in = rb;
7436            rs.out = room ? -1 : rc;
7437            rs.slot = ram_free.back();
7438            ram_free.pop_back();
7439            ++ram_inflight;
7440            std::lock_guard<std::mutex> lk(sw_mu);
7441            ram_queue.push_back(rs);
7442            rqueued = true;
7443        }
7444        if (queued) sw_cv.notify_all();
7445        if (rqueued) ram_cv.notify_one();
7446    }
7447
7448    // lookahead's thread: the ranges the CPU lane asked for, read in (os::prefetch) off the lane, which computes
7449    void prefetch_loop() {
7450        std::vector<std::pair<const void*, size_t>> b;
7451        for (;;) {
7452            {
7453                std::unique_lock<std::mutex> lk(pf_mu);
7454                pf_cv.wait(lk, [&] { return quit.load(std::memory_order_relaxed) || !pf_q.empty(); });
7455                if (quit.load(std::memory_order_relaxed)) return;
7456                b.swap(pf_q);
7457            }
7458            os::prefetch_cold(b);   // (the resident ones would only cost the page walk)
7459            b.clear();
7460        }
7461    }
7462    // where a decode pick of (l, e) is computed (Stats::tier): 0 VRAM, 1 the expert GPU, 2 the store's GPU-visible slot, 3 a ready
7463    // store slot, 4 a store read in flight, 5 none
7464    int tier_of(const Layer& l, int e, int T = 1) const {
7465        if (l.slot[(size_t) e] >= 0) return 0;
7466        if (!l.aux.empty() && l.aux[(size_t) e]) return 1;
7467        if (T == 1 && !l.zc.empty() && l.zc[(size_t) e]) return 2;
7468        const int s = store ? store->state_of(l.il, e) : 0;
7469        return s == 2 ? 3 : s == 1 ? 4 : 5;
7470    }
7471    void tier_dump(const std::string& path) const {
7472        std::FILE* f = std::fopen(path.c_str(), "w");
7473        if (f == nullptr) return;
7474        for (const Layer& l : L) {
7475            if (l.mtp || l.il >= g.nl || (int) l.slot.size() < l.n_exp) continue;
7476            std::string s((size_t) l.n_exp, '.');
7477            for (int e = 0; e < l.n_exp; ++e) s[(size_t) e] = "VAZSL."[tier_of(l, e)];
7478            std::fprintf(f, "%d %s\n", l.il, s.c_str());
7479        }
7480        std::fclose(f);
7481    }
7482    // an expert the CPU lane reads from the files (neither in VRAM nor in the RAM tier)
7483    static bool file_read(const Layer& l, int e) {
7484        return l.slot[(size_t) e] < 0 && (l.ram.empty() || l.ram[(size_t) e] < 0) && (l.aux.empty() || !l.aux[(size_t) e]);
7485    }
7486    // the layer whose picks layer l0 guesses a layers ahead (1, 2): the next ones of its stack on its device, MXFP4
7487    // experts read in place, some of them from the files now (none: nothing to read early - null)
7488    const Layer* ahead_layer(const Layer& l0, int a) const {
7489        const int j = l0.il + a, end = l0.mtp ? g.nl + g.n_mtp : g.nl;
7490        if (j >= end || j >= (int) L.size()) return nullptr;
7491        const Layer& n = L[(size_t) j];
7492        if (n.dev != l0.dev || n.mtp != l0.mtp || n.lay.fmt != gg::kFmtMXFP4 || n.gate_w == nullptr || n.n_exp > 1024 ||
7493            (int) n.slot.size() < n.n_exp)
7494            return nullptr;
7495        for (int e = 0; e < n.n_exp; ++e)
7496            if (file_read(n, e)) return &n;
7497        return nullptr;
7498    }
7499    // lookahead on the CPU lane: request r (layer li, seq) carries the device's guesses for the next layers - the
7500    // guessed experts read from the files asked for now (each once a window), the guesses kept for the hit counts
7501    std::vector<std::pair<const void*, size_t>> pf_want;
7502    void ahead_ask(int li, const Req& r, unsigned seq, int T) {
7503        pf_want.clear();
7504        for (int a = 1; a <= 2; ++a) {
7505            const int m = std::min(r.na[a - 1], a == 1 ? kAhead1 : kPicks), j = li + a;
7506            if (m <= 0 || j >= (int) L.size()) continue;
7507            const Layer& n = L[(size_t) j];
7508            uint8_t* fl = ahead_fl.data() + (size_t) j * 1024;
7509            uint8_t* rk = ahead_rank.data() + (size_t) j * 1024;
7510            if (ahead_for[(size_t) j] != seq + (unsigned) a) {
7511                std::memset(fl, 0, 1024);
7512                std::memset(rk, 0, 1024);
7513                ahead_for[(size_t) j] = seq + (unsigned) a;
7514            }
7515            for (int t = 0; t < T; ++t)
7516                for (int i = 0; i < m; ++i) {
7517                    const int e = r.ahead[t][(a - 1) * kAhead1 + i];
7518                    if (e < 0 || e >= n.n_exp || e >= (int) n.slot.size()) continue;
7519                    fl[e] |= a == 2 ? 4 : (i < n.k_exp ? 3 : 2);
7520                    if (a == 1 && (rk[e] == 0 || rk[e] > i + 1)) rk[e] = (uint8_t) (i + 1);
7521                    if ((fl[e] & 8) || !file_read(n, e)) continue;
7522                    fl[e] |= 8;
7523                    if (store) store->prefetch(j, e);
7524                    else
7525                        for (int q = 0; q < 3; ++q) pf_want.push_back({mx_mat(n, e, q), mx_part_bytes(n, q)});
7526                    ++st.ahead_pf;
7527                }
7528        }
7529        if (pf_want.empty()) return;
7530        {
7531            std::lock_guard<std::mutex> lk(pf_mu);
7532            pf_q.insert(pf_q.end(), pf_want.begin(), pf_want.end());
7533        }
7534        pf_cv.notify_one();
7535    }
7536
7537    // the decode path's host side: each published routing in turn - its CPU lane experts (if any) into the answer's
7538    // part, then the answer's seq.  Spins while requests come (a token's 40 layers), naps after 2 ms without one.
7539    void serve_lane() {
7540        unsigned next = 1;
7541        auto last = std::chrono::steady_clock::now();
7542        std::vector<Ent> ents;
7543        while (!quit.load(std::memory_order_relaxed)) {
7544            Req& r = reqs[next % kRing];
7545            if (*(volatile unsigned*) &r.seq != next) {
7546                cpu_relax();
7547                if (std::chrono::steady_clock::now() - last > std::chrono::milliseconds(2))
7548                    std::this_thread::sleep_for(std::chrono::microseconds(20));
7549                continue;
7550            }
7551            std::atomic_thread_fence(std::memory_order_acquire);
7552            const int li = layer_of[next % kRing].load(std::memory_order_acquire);
7553            Resp& rp = resps[next % kRing];
7554            const int T = std::max(1, std::min(kWin, r.T));
7555            for (int t = 0; t < T; ++t) rp.cpu[t] = 0;
7556            if (li >= 0 && li < (int) L.size()) {
7557                Layer& l = L[(size_t) li];
7558                uint32_t* pr = prof.data() + (size_t) li * g.n_exp;
7559                ents.clear();
7560                if (store && li > 0 && li < g.nl) store->cancel_stale(li - 1);   // (guesses for layers the token has passed: dropped unread)
7561                // lookahead: the guesses made for this layer (when they are for this request), counted on decode
7562                const uint8_t* fl = T == 1 && !ahead_for.empty() && ahead_for[(size_t) li] == next
7563                                        ? ahead_fl.data() + (size_t) li * 1024 : nullptr;
7564                // the window's CPU-lane picks by expert (up to 8 tokens an entry), their weights by entry row
7565                float wv[kWin * kPicks];
7566                int tok_of[kWin * kPicks];
7567                int nslots = 0;
7568                std::vector<std::pair<int, int>> picks;   // (expert, t * kPicks + i), CPU-lane only
7569                std::vector<std::pair<int, int>> apicks;  // the same, the expert GPU's
7570                if (trace_f != nullptr && !l.mtp) {   // DS4_TRACE=file: one record a route request: u8 layer, u8 T, T x k int16 expert ids
7571                    // DS4_TRACE_AHEAD=1: T has bit 7 set and the guesses follow: u8 na1, u8 na2, T x (na1 + na2) int16 (the
7572                    // next layer's likely picks by rank, then the one after's), as the lookahead made them for THIS layer's
7573                    // predecessors (the request carries the guesses for the layers after it)
7574                    static const bool with_ahead = std::getenv("DS4_TRACE_AHEAD") != nullptr;
7575                    uint8_t hd[2] = {(uint8_t) li, (uint8_t) (T | (with_ahead ? 0x80 : 0))};
7576                    std::fwrite(hd, 1, 2, trace_f);
7577                    for (int t = 0; t < T; ++t)
7578                        for (int i = 0; i < l.k_exp; ++i) {
7579                            const int16_t v = (int16_t) r.ids[t][i];
7580                            std::fwrite(&v, 2, 1, trace_f);
7581                        }
7582                    if (with_ahead) {
7583                        const uint8_t na[2] = {(uint8_t) std::max(0, std::min(r.na[0], kAhead1)), (uint8_t) std::max(0, std::min(r.na[1], kPicks))};
7584                        std::fwrite(na, 1, 2, trace_f);
7585                        for (int t = 0; t < T; ++t) {
7586                            for (int i = 0; i < na[0]; ++i) {
7587                                const int16_t v = (int16_t) r.ahead[t][i];
7588                                std::fwrite(&v, 2, 1, trace_f);
7589                            }
7590                            for (int i = 0; i < na[1]; ++i) {
7591                                const int16_t v = (int16_t) r.ahead[t][kAhead1 + i];
7592                                std::fwrite(&v, 2, 1, trace_f);
7593                            }
7594                        }
7595                    }
7596                }
7597                const bool dsk = disk_skip_w > 0.0f && !l.mtp && li >= disk_skip_from && li < g.nl;
7598                for (int t = 0; t < T; ++t) {
7599                    float wsum = 0.0f;   // (DISK_SKIP_W: the token's route weights)
7600                    if (dsk)
7601                        for (int i = 0; i < l.k_exp; ++i)
7602                            if (r.ids[t][i] >= 0 && r.ids[t][i] < l.n_exp) wsum += r.w[t][i];
7603                    for (int i = 0; i < l.k_exp; ++i) {
7604                        const int e = r.ids[t][i];
7605                        if (e < 0 || e >= l.n_exp) continue;
7606                        ++pr[e];
7607                        l.heat[(size_t) e] += 1.0f;
7608                        if (fl != nullptr) {
7609                            ++st.ahead_picks;
7610                            st.ahead_hit_k += fl[e] & 1;
7611                            st.ahead_hit += (fl[e] & 6) != 0;
7612                            st.ahead_hit2 += (fl[e] >> 2) & 1;
7613                        }
7614                        if (!l.mtp) ++st.tier[tier_of(l, e, T)];
7615                        if (l.slot[(size_t) e] < 0) {
7616                            l.cpu_hits.push_back(e);
7617                            if (!l.aux.empty() && l.aux[(size_t) e]) {   // (the expert GPU's)
7618                                apicks.push_back({e, t * kPicks + i});
7619                                continue;
7620                            }
7621                            if (T == 1 && !l.zc.empty() && l.zc[(size_t) e]) {   // the device computed it from the store's slot
7622                                store->touch(li, e);
7623                                ++st.store_zc;
7624                                continue;
7625                            }
7626                            if (dsk && r.w[t][i] < disk_skip_w * wsum && !in_ram(l, e)) {
7627                                ++st.skipped;
7628                                continue;
7629                            }
7630                            if (!l.ram.empty() && l.ram[(size_t) e] >= 0) ++st.ram_experts;
7631                            else if (fl != nullptr) {
7632                                ++st.ahead_cold;
7633                                st.ahead_cold_hit += (fl[e] >> 3) & 1;
7634                            }
7635                            picks.push_back({e, t * kPicks + i});
7636                        }
7637                    }
7638                }
7639                if (fl != nullptr) {   // the guesses by rank: how many were picked
7640                    const uint8_t* rk = ahead_rank.data() + (size_t) li * 1024;
7641                    for (int e = 0; e < l.n_exp && e < 1024; ++e) {
7642                        if (rk[e] == 0 || rk[e] > 16) continue;
7643                        bool hit = false;
7644                        for (int i = 0; i < l.k_exp; ++i) hit = hit || r.ids[0][i] == e;
7645                        ++st.ahead_rank_n[rk[e] - 1];
7646                        st.ahead_rank_hit[rk[e] - 1] += hit;
7647                    }
7648                }
7649                if (ahead_mode > 0 && !ahead_for.empty()) ahead_ask(li, r, next, T);
7650                std::sort(picks.begin(), picks.end());
7651                for (size_t a = 0; a < picks.size();) {
7652                    Ent en;
7653                    en.e = picks[a].first;
7654                    en.slot0 = nslots;
7655                    en.n = 0;
7656                    while (a < picks.size() && picks[a].first == en.e && en.n < ent_cap(l)) {
7657                        const int t = picks[a].second / kPicks, i = picks[a].second % kPicks;
7658                        en.tok[en.n++] = t;
7659                        tok_of[nslots] = t;
7660                        wv[nslots] = r.w[t][i];
7661                        ++nslots;
7662                        ++a;
7663                    }
7664                    ents.push_back(en);
7665                }
7666                // lookahead: the entries asked for early (or in the RAM tier) computed first, so the ones asked for
7667                // only now get the others' time to come in from the SSD (their slots, so the sums, stay the same)
7668                int ord[kWin * kPicks];
7669                const int* po = nullptr;
7670                if (ahead_order && !ahead_for.empty() && ahead_for[(size_t) li] == next && ents.size() > 1 &&
7671                    ents.size() <= (size_t) (kWin * kPicks)) {
7672                    const uint8_t* fa = ahead_fl.data() + (size_t) li * 1024;
7673                    int n = 0;
7674                    for (int pass = 0; pass < 2; ++pass)
7675                        for (size_t q = 0; q < ents.size(); ++q) {
7676                            const int e = ents[q].e;
7677                            const bool early = !file_read(l, e) || (fa[e] & 8) != 0;
7678                            if (early == (pass == 0)) ord[n++] = (int) q;
7679                        }
7680                    po = ord;
7681                }
7682                std::sort(apicks.begin(), apicks.end());
7683                const int na = aux_launch(l, r, T, apicks);   // (the expert GPU's rows, while the CPU lane computes)
7684                if (!ents.empty() || na > 0) {
7685                    const double tc = now_ms();
7686                    if (!ents.empty()) cpu_experts(l, &r.x[0][0], ents, (size_t) kMaxDim, po);
7687                    if (na > 0) aux_wait();
7688                    // token t's part: its CPU-lane slots in expert order, then its expert-GPU rows in expert order
7689                    const int D = g.dim;
7690                    for (int t = 0; t < T; ++t) {
7691                        bool any = false;
7692                        for (int sl = 0; sl < nslots; ++sl) any = any || tok_of[sl] == t;
7693                        for (int k = 0; k < na; ++k) any = any || apicks[(size_t) k].second / kPicks == t;
7694                        if (!any) continue;
7695                        float* o = rp.part[t];
7696                        for (int e = 0; e < D; ++e) o[e] = 0.0f;
7697                        for (int sl = 0; sl < nslots; ++sl) {
7698                            if (tok_of[sl] != t) continue;
7699                            const float* y = c_yd.data() + (size_t) sl * D;
7700                            for (int e = 0; e < D; ++e) o[e] += wv[sl] * y[e];
7701                        }
7702                        for (int k = 0; k < na; ++k) {
7703                            const int q = apicks[(size_t) k].second;
7704                            if (q / kPicks != t) continue;
7705                            const float wk = r.w[t][q % kPicks];
7706                            const float* y = aux.hy + (size_t) k * D;
7707                            for (int e = 0; e < D; ++e) o[e] += wk * y[e];
7708                        }
7709                        rp.cpu[t] = 1;
7710                    }
7711                    st.cpu_ms += now_ms() - tc;
7712                    st.cpu_experts += nslots;
7713                    st.aux_experts += na;
7714                }
7715            }
7716            std::atomic_thread_fence(std::memory_order_release);
7717            *(volatile unsigned*) &rp.seq = next;
7718            ++next;
7719            last = std::chrono::steady_clock::now();
7720        }
7721    }
7722
7723    // a GGUF's matrices (BF16 / MXFP4) to its own kernels, EXL3 ones to x3's
7724    static bool mv_any(const x3::MvJob* j, int n, cudaStream_t s) {
7725        bool g = false;
7726        for (int i = 0; i < n; ++i) g = g || j[i].m->fmt != 0;
7727        return g ? gg::mv(j, n, s) : x3::mv(j, n, s);
7728    }
7729    bool mv(Dev& d, std::initializer_list<x3::MvJob> jobs, std::string& err) {
7730        x3::MvJob j[x3::kMaxMvJobs];
7731        int n = 0;
7732        for (const x3::MvJob& x : jobs) j[n++] = x;
7733        if (!mv_any(j, n, d.st)) {
7734            err = "exl3 mv failed";
7735            return false;
7736        }
7737        return true;
7738    }
7739    bool mv_n(Dev& d, x3::MvJob* j, int n, std::string& err) {
7740        for (int a = 0; a < n; a += x3::kMaxMvJobs)
7741            if (!mv_any(j + a, std::min(x3::kMaxMvJobs, n - a), d.st)) {
7742                err = "exl3 mv failed";
7743                return false;
7744            }
7745        return true;
7746    }
7747    // y[c] = x[c] W for the T activations x + c * x_cs (floats), into y + c * y_cs
7748    static x3::MvJob job(const x3::Mat& m, const float* x, float* y, int T = 1, size_t x_cs = 0, size_t y_cs = 0,
7749                         float alpha = 1.0f) {
7750        x3::MvJob j;
7751        j.m = &m;
7752        j.xf = x;
7753        j.y = y;
7754        j.alpha = alpha;
7755        j.ncol = T;
7756        j.xf_cs = x_cs;
7757        j.y_cs = y_cs;
7758        return j;
7759    }
7760
7761    // ---- the DSpark drafter (DeepSeek's DSparkBlock / forward_spec).  Its blocks' rings hold the trunk's main KV:
7762    // seed() turns a window's taps (the streams' mean entering layers 37..39) into it, through main_proj / main_norm
7763    // and each block's wkv / kv_norm / rope / FP8, for the positions the trunk kept.  draft() runs the block [y, noise x
7764    // (block - 1)] at positions pos .. through the blocks (each query attending to the ring and to the whole block),
7765    // the trunk's head, the markov bias token by token (greedy) and the confidence head.
7766    bool seed_drafter(int64_t p0, int n, int row0, std::string& err) {
7767        if (g.n_mtp == 0 || n <= 0) return true;
7768        if (n > kWin * kPicks) {
7769            err = "seeding the drafter with " + std::to_string(n) + " rows";
7770            return false;
7771        }
7772        Dev& d = devs[(size_t) d_dev];
7773        cudaSetDevice(d.id);
7774        const int nt = (int) g.d_targets.size(), D = g.dim, HD = g.hd;
7775        if (dump_d != nullptr) {   // DS4_DSPARK_DUMP: 'S', the first position, the rows, then the taps
7776            for (Dev& e : devs) {
7777                cudaSetDevice(e.id);
7778                CK(cudaStreamSynchronize(e.st));
7779            }
7780            cudaSetDevice(d.id);
7781            const int64_t hdr[4] = {'S', p0, n, (int64_t) nt * D};
7782            std::fwrite(hdr, 8, 4, dump_d);
7783            std::fwrite(h_taps + (size_t) row0 * nt * D, 4, (size_t) n * nt * D, dump_d);
7784            std::fflush(dump_d);
7785        }
7786        for (int a = 0; a < n; a += kWin) {   // (a chunk's last 128 rows: 16 a GEMV)
7787            const int na = std::min(kWin, n - a);
7788            CK(cudaMemcpyAsync(d.xe, h_taps + (size_t) (row0 + a) * nt * D, (size_t) na * nt * D * 4,
7789                               cudaMemcpyHostToDevice, d.st));
7790            if (!mv(d, {job(d_main_proj, d.xe, d.ed + (size_t) a * D, na, (size_t) nt * D, D)}, err)) return false;
7791        }
7792        CK(cudaEventRecord(ev_seed, d.st));
7793        Finish fm;
7794        fm.w = d_main_norm;
7795        fm.eps = g.eps;
7796        finish(d.ed, n, D, D, fm, d.st);
7797        for (int i = 0; i < g.n_mtp; ++i) {
7798            Layer& l = L[(size_t) (g.nl + i)];
7799            if (l.dev != d_dev) {
7800                err = "the DSpark blocks are split across devices";
7801                return false;
7802            }
7803            for (int a = 0; a < n; a += kWin) {
7804                const int na = std::min(kWin, n - a);
7805                if (!mv(d, {job(l.wkv, d.ed + (size_t) a * D, d.kvr, na, D, HD)}, err)) return false;
7806                Finish fk;
7807                fk.w = l.kv_norm;
7808                fk.eps = g.eps;
7809                fk.rd = g.rd;
7810                fk.pos = (int) (p0 + a);
7811                fk.freqs = d.freqs_win;
7812                fk.quant = 1;
7813                fk.dst = d.ext + (size_t) g.win * HD;
7814                fk.dst_stride = HD;
7815                finish(d.kvr, na, HD, HD, fk, d.st);
7816                ext_to_ring(d.ext, l.win, p0 + a, g.win, na, HD, d.st);
7817            }
7818        }
7819        return true;
7820    }
7821
7822    bool draft(int y, std::vector<int>& out, std::vector<float>& conf, std::string& err, float temperature, float top_p,
7823               int top_k, float min_p, uint64_t seed, uint64_t counter) {
7824        if (!lend_restore(err)) return false;
7825        settle_if_due();
7826        const double t0 = now_ms();
7827        drafts_q = temperature > 0.0f && sample_drafts;
7828        dq_temp = temperature;
7829        dq_top_p = top_p;
7830        dq_top_k = top_k;
7831        dq_min_p = min_p;
7832        dq_seed = seed;
7833        dq_counter = counter;
7834        const bool ok = draft_(y, out, conf, err);
7835        if (!ok) drafts_q = false;
7836        if (max_drafts > 0 && (int) out.size() > max_drafts) {
7837            out.resize((size_t) max_drafts);
7838            conf.resize((size_t) max_drafts);
7839        }
7840        st.draft_ms += now_ms() - t0;
7841        ++st.drafts_rounds;
7842        return ok;
7843    }
7844    bool draft_(int y, std::vector<int>& out, std::vector<float>& conf, std::string& err) {
7845        out.clear();
7846        conf.clear();
7847        const int T = g.d_block, D = g.dim, H = g.hc, V = g.vocab, R = g.d_rank;
7848        const int64_t p0 = pos;
7849        if (g.n_mtp == 0 || T < 1 || T > kWin || p0 + T > o.max_context) return true;
7850        int tk[kWin];
7851        tk[0] = y;
7852        for (int t = 1; t < T; ++t) tk[t] = g.d_noise;
7853        Dev& d = devs[(size_t) d_dev];
7854        cudaSetDevice(d.id);
7855        for (int t = 0; t < T; ++t) std::memcpy(h_emb + (size_t) t * D, embed_pinned + (size_t) tk[t] * D, (size_t) D * 2);
7856        CK(cudaMemcpyAsync(d.emb_rows, h_emb, (size_t) T * D * 2, cudaMemcpyHostToDevice, d.st));
7857        embed(d.emb_rows, T, d.h, D, H, d.st);
7858        init_pre(d.pre, T, d.st);
7859        WinPlan dp;   // (window attention alone: the mailbox seqs)
7860        dp.async = !sync_decode && T <= async_max_t;
7861        for (int i = 0; i < g.n_mtp && dp.async; ++i) {
7862            const int il = g.nl + i;
7863            dp.seq[il] = ++seq_issued;
7864            layer_of[dp.seq[il] % kRing].store(il, std::memory_order_release);
7865        }
7866        const size_t hs = (size_t) T * H * D, rs = (size_t) g.win * g.hd;
7867        if (dump_d != nullptr && h_dump == nullptr &&
7868            (!halloc(h_dump, (size_t) g.n_mtp * kWin * H * D, err) || !halloc(h_dump_ring, (size_t) g.n_mtp * rs, err)))
7869            return false;
7870        for (int i = 0; i < g.n_mtp; ++i) {
7871            Layer& l = L[(size_t) (g.nl + i)];
7872            if (dump_d != nullptr) {   // (stream order: the ring the block reads - as BF16 rows - the stream it leaves)
7873                ring_to_ext(l.win, d.ext, g.win, g.win, g.hd, d.st);
7874                CK(cudaMemcpyAsync(h_dump_ring + (size_t) i * rs, d.ext, rs * 2, cudaMemcpyDeviceToHost, d.st));
7875            }
7876            if (!layer(l, 0, p0, T, dp, err)) return false;
7877            if (dump_d != nullptr) {
7878                cudaSetDevice(d.id);
7879                CK(cudaMemcpyAsync(h_dump + (size_t) i * hs, d.h, hs * 4, cudaMemcpyDeviceToHost, d.st));
7880            }
7881        }
7882        cudaSetDevice(d.id);
7883        hc_pre_norm(d.h, d.pre, nullptr, D, H, T, g.eps, d.x, d.st);   // (the confidence head reads it before the norm)
7884        Dev& hd = devs[(size_t) head_dev];
7885        // (through the host to the head's device, and to the head group's other members - the drafter's device can be
7886        // the head group's lead itself, a group of every GPU)
7887        if (d_dev != head_dev || groups[(size_t) hd.grp].mem.size() > 1) {
7888            CK(cudaMemcpyAsync(d.bounce, d.x, (size_t) T * D * 4, cudaMemcpyDeviceToHost, d.st));
7889            CK(cudaEventRecord(d.ev_out, d.st));
7890        }
7891        if (d_dev != head_dev) {
7892            cudaSetDevice(hd.id);
7893            CK(cudaStreamWaitEvent(hd.st, d.ev_out, 0));
7894            CK(cudaMemcpyAsync(hd.x, d.bounce, (size_t) T * D * 4, cudaMemcpyHostToDevice, hd.st));
7895        }
7896        // the drafter's final norm and the trunk's head, on every member of the head group (the others' shares first)
7897        const std::vector<int>& hg = groups[(size_t) hd.grp].mem;
7898        const bool mk = mk_split && !drafts_q;   // (sampled drafts: the lead's whole rows, gathered)
7899        for (int m = (int) hg.size() - 1; m >= 0; --m) {
7900            Dev& e = devs[(size_t) hg[(size_t) m]];
7901            cudaSetDevice(e.id);
7902            if (m > 0) {
7903                CK(cudaStreamWaitEvent(e.st, d.ev_out, 0));
7904                CK(cudaMemcpyAsync(e.ao, d.bounce, (size_t) T * D * 4, cudaMemcpyHostToDevice, e.st));
7905            } else
7906                CK(cudaMemcpyAsync(e.ao, e.x, (size_t) T * D * 4, cudaMemcpyDeviceToDevice, e.st));
7907            Finish fn;
7908            fn.w = e.d_norm;
7909            fn.eps = g.eps;
7910            finish(e.ao, T, D, D, fn, e.st);
7911            if (!head_share(e, m, e.ao, T, err, !mk)) return false;
7912        }
7913        h_idx[0] = y;
7914        if (mk) {
7915            // the markov steps over the group: each member its rows of the bias and its share's argmax, every member
7916            // then the global one (the sampler's tie rule) and its E row - the same drafts as the lead's whole rows,
7917            // each step ~1/nm of their 66 MB and no gather of the shares
7918            const int nm = (int) hg.size();
7919            const unsigned seq = ++mk_seq;
7920            for (int m = 0; m < nm; ++m) {
7921                Dev& e = devs[(size_t) hg[(size_t) m]];
7922                cudaSetDevice(e.id);
7923                CK(cudaMemcpyAsync(e.mk_ints, h_idx, 4, cudaMemcpyHostToDevice, e.st));
7924                CK(cudaMemcpyAsync(e.mk_erow, h_mk_embed + (size_t) y * R, (size_t) R * 2, cudaMemcpyHostToDevice, e.st));
7925            }
7926            for (int i = 0; i < T; ++i)
7927                for (int m = 0; m < nm; ++m) {
7928                    Dev& e = devs[(size_t) hg[(size_t) m]];
7929                    cudaSetDevice(e.id);
7930                    float* row = m == 0 ? hd.logits + (size_t) i * V : e.logits_part + (size_t) i * e.mk_vn;
7931                    markov_share(row, e.mk_share, e.mk_erow, e.mk_vn, R, e.st);
7932                    argmax_share(row, e.mk_vn, e.mk_v0, mk_slots + ((size_t) i * nm + m) * 4, seq, e.st);
7933                    markov_pick(mk_slots + (size_t) i * nm * 4, nm, seq, e.mk_ints + i + 1, h_mk_embed, e.mk_erow, R,
7934                                e.st);
7935                }
7936            cudaSetDevice(hd.id);
7937        } else {
7938            CK(cudaMemcpyAsync(d_ints, h_idx, 4, cudaMemcpyHostToDevice, hd.st));
7939            strata::dsv41k::SamplerParams sp;
7940            sp.greedy = true;
7941            sp.temperature = 0.0f;
7942            if (drafts_q) {   // the request's own chain: draft i drawn as the model's token i would be (verify's counter + i)
7943                sp.greedy = false;
7944                sp.temperature = dq_temp * (q_temp_scale > 0.0f ? q_temp_scale : 1.0f);
7945                sp.top_p = dq_top_p;
7946                sp.top_k = dq_top_k;
7947                sp.min_p = dq_min_p;
7948                sp.seed = dq_seed;
7949            }
7950            for (int i = 0; i < T; ++i) {   // the markov bias of the token before, then that position's draft
7951                markov_add(hd.logits + (size_t) i * V, d_mk_embed, d_mk_head, d_ints + i, V, R, hd.st);
7952                if (drafts_q) {
7953                    sp.counter = dq_counter + (uint64_t) i;
7954                    strata::dsv41k::sample_draft(hd.logits + (size_t) i * V, 1, V, sp, d_specq + i, d_ints + i + 1, hd.st);
7955                } else
7956                    strata::dsv41k::sample_tokens(hd.logits + (size_t) i * V, 1, V, nullptr, 0, sp, d_ints + i + 1, hd.st);
7957            }
7958        }
7959        confidence(hd.x, d_mk_embed, d_ints, d_conf, T, D, R, d_confv, hd.st);
7960        int tok[kWin + 1];
7961        float cf[kWin];
7962        CK(cudaMemcpyAsync(h_idx, d_ints, (size_t) (T + 1) * 4, cudaMemcpyDeviceToHost, hd.st));
7963        CK(cudaMemcpyAsync(h_w, d_confv, (size_t) T * 4, cudaMemcpyDeviceToHost, hd.st));
7964        CK(cudaStreamSynchronize(hd.st));
7965        for (int i = 0; i <= T; ++i) tok[i] = h_idx[i];
7966        for (int i = 0; i < T; ++i) cf[i] = h_w[i];
7967        if (dump_d != nullptr) {   // 'D', the block's position, y, T, then the drafts, their confidences, the hidden
7968            std::vector<float> xs((size_t) T * D);   // rows before the final norm; then each block's ring and stream
7969            CK(cudaMemcpy(xs.data(), hd.x, xs.size() * 4, cudaMemcpyDeviceToHost));
7970            cudaSetDevice(d.id);
7971            CK(cudaStreamSynchronize(d.st));
7972            const int64_t hdr[4] = {'D', p0, y, T};
7973            std::fwrite(hdr, 8, 4, dump_d);
7974            std::fwrite(tok + 1, 4, (size_t) T, dump_d);
7975            std::fwrite(cf, 4, (size_t) T, dump_d);
7976            std::fwrite(xs.data(), 4, xs.size(), dump_d);
7977            for (int i = 0; i < g.n_mtp; ++i) {
7978                std::fwrite(h_dump_ring + (size_t) i * rs, 2, rs, dump_d);
7979                std::fwrite(h_dump + (size_t) i * hs, 4, hs, dump_d);
7980            }
7981            std::fflush(dump_d);
7982            cudaSetDevice(hd.id);
7983        }
7984        for (int i = 0; i < T; ++i) {
7985            out.push_back(tok[i + 1]);
7986            conf.push_back(cf[i]);
7987        }
7988        return true;
7989    }
7990
7991    int sample_row(int row, float temperature, float top_p, int top_k, float min_p, uint64_t seed, uint64_t counter,
7992                   const float* bias) {
7993        Dev& d = devs[(size_t) head_dev];
7994        cudaSetDevice(d.id);
7995        strata::dsv41k::SamplerParams sp;
7996        sp.temperature = temperature;
7997        sp.greedy = temperature <= 0.0f;
7998        sp.top_p = top_p;
7999        sp.top_k = top_k;
8000        sp.min_p = min_p;
8001        sp.seed = seed;
8002        sp.counter = counter;
8003        sp.logit_bias = bias;
8004        strata::dsv41k::sample_tokens(d.logits + (size_t) row * g.vocab, 1, g.vocab, nullptr, 0, sp, d.tok, d.st);
8005        int t = -1;
8006        cudaMemcpyAsync(&t, d.tok, 4, cudaMemcpyDeviceToHost, d.st);
8007        cudaStreamSynchronize(d.st);
8008        return t;
8009    }
8010
8011    // [y, drafts] at positions pos ..: the trunk's verdict, its next token, and the state back to what it kept.
8012    // Greedy: the drafts the trunk's argmax agrees with.  Sampled: the speculative-sampling rule over the request's own
8013    // chain (top_k, top_p, min_p, temperature): draft d stands with probability min(1, p(d) / q(d)), q the distribution
8014    // it was drawn from (the drafter's argmax: a point at d, so p(d)), a rejected one is replaced by a draw from the
8015    // residual max(0, p - q) - so each kept token is distributed as the trunk's own draw.
8016    bool verify(int y, const std::vector<int>& drafts, float temperature, float top_p, int top_k, float min_p,
8017                uint64_t seed, uint64_t counter, int& accepted, int& next, std::string& err) {
8018        const int n = (int) std::min<size_t>(drafts.size(), (size_t) kWin - 1);
8019        const int T = n + 1, V = g.vocab;
8020        const int64_t p0 = pos;
8021        int tk[kWin];
8022        tk[0] = y;
8023        for (int i = 0; i < n; ++i) tk[i + 1] = drafts[(size_t) i];
8024        spec_win = true;
8025        const double tv = now_ms();
8026        const bool ok = forward(tk, T, T, err, 0);
8027        st.verify_ms += now_ms() - tv;
8028        spec_win = false;
8029        if (!ok) return false;
8030        Dev& hd = devs[(size_t) head_dev];
8031        cudaSetDevice(hd.id);
8032        int m = 0;
8033        if (temperature <= 0.0f) {
8034            strata::dsv41k::SamplerParams sp;
8035            sp.greedy = true;
8036            sp.temperature = 0.0f;
8037            strata::dsv41k::sample_tokens(hd.logits, T, V, nullptr, 0, sp, d_ints + 16, hd.st);   // (the T rows at once)
8038            CK(cudaMemcpyAsync(h_idx, d_ints + 16, (size_t) T * 4, cudaMemcpyDeviceToHost, hd.st));
8039            CK(cudaStreamSynchronize(hd.st));
8040            while (m < n && h_idx[m] == drafts[(size_t) m]) ++m;
8041            next = h_idx[m];
8042        } else {
8043            // row i keeps draft i with probability min(1, p(d) / q(d)), else draws from the residual max(0, p - q)
8044            // (never d itself): each row a token distributed as the model's own draw at that position, p through the
8045            // request's chain - the top_k / top_p / min_p cut included (the drafter's argmax can lie outside it: p(d) 0,
8046            // never kept); past the first rejection the rows do not count
8047            const bool own = drafts_q && dq_temp == temperature && dq_top_p == top_p && dq_top_k == top_k &&
8048                             dq_min_p == min_p && dq_seed == seed && dq_counter == counter;
8049            if (!own) {   // the drafter's argmax: q a point at each draft
8050                for (int i = 0; i < n; ++i) {
8051                    h_specq[(size_t) i].n = 1;
8052                    h_specq[(size_t) i].ids[0] = drafts[(size_t) i];
8053                    h_specq[(size_t) i].p[0] = 1.0;
8054                }
8055                CK(cudaMemcpyAsync(d_specq, h_specq.data(), (size_t) n * sizeof(strata::dsv41k::SpecList),
8056                                   cudaMemcpyHostToDevice, hd.st));
8057            }
8058            for (int i = 0; i < n; ++i) h_idx[i] = drafts[(size_t) i];
8059            CK(cudaMemcpyAsync(d_ints + 32, h_idx, (size_t) n * 4, cudaMemcpyHostToDevice, hd.st));
8060            strata::dsv41k::SamplerParams sp;
8061            sp.greedy = false;
8062            sp.temperature = temperature;
8063            sp.top_p = top_p;
8064            sp.top_k = top_k;
8065            sp.min_p = min_p;
8066            sp.seed = seed;
8067            sp.counter = counter;
8068            strata::dsv41k::sample_verify(hd.logits, n, V, sp, d_specq, d_ints + 32, d_ints + 16, hd.st);
8069            CK(cudaMemcpyAsync(h_idx, d_ints + 16, (size_t) n * 4, cudaMemcpyDeviceToHost, hd.st));
8070            CK(cudaStreamSynchronize(hd.st));
8071            while (m < n && h_idx[m] == drafts[(size_t) m]) ++m;
8072            next = m < n ? h_idx[m] : sample_row(n, temperature, top_p, top_k, min_p, seed, counter + (uint64_t) n, nullptr);
8073        }
8074        drafts_q = false;
8075        rollback(p0, T, m + 1);
8076        if (!seed_drafter(p0, m + 1, 0, err)) return false;
8077        accepted = m;
8078        st.drafts_offered += n;
8079        st.drafts_accepted += m;
8080        for (int i = 0; i < n && i <= m && i < 8; ++i) {
8081            ++st.draft_reached[i];
8082            if (i < m) ++st.draft_kept[i];
8083        }
8084        return true;
8085    }
8086
8087    // a verified window keeps its first `keep` positions: the ring rows and the compressors' state of the rest undone
8088    // (the compressed KV and the index keys past them are written again when those positions come)
8089    void rollback(int64_t p0, int T, int keep) {
8090        if (keep >= T) return;
8091        // the ring rows: one launch a device for all its layers (a launch a layer and member was ~300 on 8-way tensor
8092        // parallel, a millisecond of the host's before the next draft)
8093        std::vector<RingBatch> rb(devs.size());
8094        for (int il = 0; il < g.nl; ++il)
8095            for (int m = 0; m < L[(size_t) il].nm; ++m) {
8096                Layer& l = member(L[(size_t) il], m);
8097                RingBatch& b = rb[(size_t) l.dev];
8098                if (b.n == kMaxRingBatch) {   // (more layers on a device than a batch takes: this one alone)
8099                    cudaSetDevice(devs[(size_t) l.dev].id);
8100                    ring_restore(l.win, l.ring_bak, p0, g.win, keep, T, g.hd, devs[(size_t) l.dev].st);
8101                    continue;
8102                }
8103                b.ring[b.n] = l.win;
8104                b.bak[b.n++] = l.ring_bak;
8105            }
8106        for (size_t di = 0; di < devs.size(); ++di)
8107            if (rb[di].n > 0) {
8108                cudaSetDevice(devs[di].id);
8109                ring_restore_batch(rb[di], p0, g.win, keep, T, g.hd, devs[di].st);
8110            }
8111        for (int il = 0; il < g.nl; ++il)
8112            for (int m = 0; m < L[(size_t) il].nm; ++m) {
8113                Layer& l = member(L[(size_t) il], m);
8114                Dev& d = devs[(size_t) l.dev];
8115                if (l.c_snap != nullptr) {
8116                    cudaSetDevice(d.id);
8117                    const size_t ns = (size_t) l.ratio * g.hd * 4;
8118                    cudaMemcpyAsync(l.c_kv, l.c_snap, ns, cudaMemcpyDeviceToDevice, d.st);
8119                    cudaMemcpyAsync(l.c_score, l.c_snap + (size_t) l.ratio * g.hd, ns, cudaMemcpyDeviceToDevice, d.st);
8120                    compress_win(l.c_rows, l.c_rows + (size_t) kWin * g.hd, l.c_kv, l.c_score, l.ratio, (int) p0, keep,
8121                                 g.hd, l.c_norm, g.eps, d.latent, d.st);
8122                }
8123            }
8124        pos = p0 + keep;
8125        toks.resize((size_t) pos);
8126        ctoks.resize((size_t) pos);
8127        slot_held = false;
8128    }
8129
8130    // ---- a window: T tokens at positions pos .. pos + T - 1 through every layer; the logits of its last `logits` rows
8131    bool step(int token, bool want_logits, std::string& err) { return forward(&token, 1, want_logits ? 1 : 0, err); }
8132
8133
8134    // layer L0 for a chunk of T tokens at p0 as group member mi: layer()'s arithmetic over the chunk's rows (the
8135    // projections as GEMMs, the attention and the indexer in slabs, the routed experts as sorted rows: the VRAM ones in
8136    // place, the CPU lane's streamed in batches).  kv_only (a long prompt's first pass, Run::stop): only what the layers
8137    // after it read of these rows - its compressed KV and index keys - and nothing of its own attention or experts
8138    bool layer_chunk(Layer& L0, int mi, int64_t p0, int T, const WinPlan& wp, Streamer& S, std::string& err,
8139                     bool kv_only = false) {
8140        Layer& l = member(L0, mi);
8141        Dev& d = devs[(size_t) l.dev];
8142        Chunk& c = *chunks[(size_t) l.dev];
8143        cudaSetDevice(d.id);
8144        cudaStream_t s = d.st;
8145        prof_mark(d, 0);
8146        const int nm = L0.nm;
8147        const int D = g.dim, H = g.hc, HD = g.hd, NHL = l.ahn, HQ = NHL * HD, OG = l.ogn, FF = l.ffn;
8148        const ArGroup& ab = groups[(size_t) L0.grp].arb;
8149        const float* freqs = l.ratio ? d.freqs_comp : d.freqs_win;
8150        // Engram, in slabs of 256 tokens
8151        if (l.eg >= 0) {
8152            const int cols = (pk.eg_ngram - 1) * pk.eg_heads, ehd = pk.eg_hd;
8153            const size_t per = (size_t) cols * (ehd + ehd / 32);
8154            const int slot = wp.eg_slot >= 0 ? wp.eg_slot : wp.k % 2;   // (read ahead by the run: two in flight)
8155            uint8_t* host = c.eg_host[slot] + (size_t) l.eg * c.C * per;
8156            CK(cudaMemcpyAsync(c.eg_rows, host, (size_t) T * per, cudaMemcpyHostToDevice, s));
8157            CK(cudaEventRecord(c.eg_ev[slot], s));
8158            for (int s0 = 0; s0 < T; s0 += 256) {
8159                const int ns = std::min(256, T - s0);
8160                engram_dequant_tok(c.eg_rows + (size_t) s0 * per, per, cols, ns, ehd, c.eg_x, s, (int) eg_fmt[(size_t) l.eg]);
8161                x3::rows_f16(c.eg_x, cols * ehd, nullptr, ns, cols * ehd, c.eg_x16, s);
8162                if (!gemm(d, c, l.eg_wkv, c.eg_x16, cols * ehd, ns, c.eg_kv, (H + 1) * D, 0.0f, err)) return false;
8163                engram_gate(c.h + (size_t) s0 * H * D, c.eg_kv, l.eg_w, H, D, ns, g.eps, s);
8164            }
8165        }
8166        prof_mark(d, 4);
8167        // attention
8168        if (!hc_mix_chunk(d, c, c.h, l.hca_fn, T, c.mix, err)) return false;
8169        hc_split(c.mix, l.hca_scale, l.hca_base, H, g.sinkhorn, g.hc_eps, T, c.a_pre, c.a_post, c.a_comb, s);
8170        hc_pre_norm(c.h, c.pre, l.attn_norm, D, H, T, g.eps, c.x, s);
8171        x3::rows_f16(c.x, D, nullptr, T, D, c.x16, s);
8172        prof_mark(d, 5);
8173        if (!kv_only && (!gemm(d, c, l.wq_a, c.x16, D, T, c.qr, g.q_lora, 0.0f, err) ||
8174                         !gemm(d, c, l.wkv, c.x16, D, T, c.kvr, HD, 0.0f, err)))
8175            return false;
8176        if (l.kv_src && !gemm(d, c, l.c_wkv, c.x16, D, T, c.ckr, HD, 0.0f, err)) return false;
8177        if (l.kv_src && l.ratio > 1 && !gemm(d, c, l.c_wgate, c.x16, D, T, c.cgr, HD, 0.0f, err)) return false;
8178        prof_mark(d, 6);
8179        const bool snap = !kv_only && wp.snap_t >= 0 && mi == 0 && L0.snap_win != nullptr;
8180        if (!kv_only) {
8181            Finish fq;
8182            fq.w = l.q_norm;
8183            fq.eps = g.eps;
8184            finish(c.qr, T, g.q_lora, g.q_lora, fq, s);
8185            x3::rows_f16(c.qr, g.q_lora, nullptr, T, g.q_lora, c.qr16, s);
8186            // the window rows: the ring's (positions p0 - win ..) then the chunk's
8187            ring_to_ext(l.win, c.ext, p0, g.win, HD, s);
8188            Finish fk;
8189            fk.w = l.kv_norm;
8190            fk.eps = g.eps;
8191            fk.rd = g.rd;
8192            fk.pos = (int) p0;
8193            fk.freqs = freqs;
8194            fk.quant = 1;
8195            fk.dst = c.ext + (size_t) g.win * HD;
8196            fk.dst_stride = HD;
8197            finish(c.kvr, T, HD, HD, fk, s);
8198            // feed_mark's checkpoint: the ring as it was before row snap_t - the old ring, then the chunk's rows before it
8199            if (snap) {
8200                CK(cudaMemcpyAsync(L0.snap_win, l.win, (size_t) g.win * win_rb(), cudaMemcpyDeviceToDevice, s));
8201                if (wp.snap_t > 0) ext_to_ring(c.ext, L0.snap_win, p0, g.win, wp.snap_t, HD, s, nullptr);
8202            }
8203            ext_to_ring(c.ext, l.win, p0, g.win, T, HD, s, nullptr);
8204        }
8205        const uint8_t* ckv = nullptr;
8206        const long long ss = (long long) o.max_context + 64;
8207        if (l.ratio > 0) {
8208            Src& sr = srcs[(size_t) l.src];
8209            const int R = l.ratio;
8210            const int64_t g_first = p0 / R, g_end = (p0 + T) / R;
8211            const int ng = (int) std::max<int64_t>(0, g_end - g_first);
8212            const float* latent = c.latent;
8213            if (l.kv_src) {
8214                if (R == 1) {
8215                    Finish fc;
8216                    fc.w = l.c_norm;
8217                    fc.eps = g.eps;
8218                    finish(c.ckr, T, HD, HD, fc, s);
8219                    latent = c.ckr;
8220                } else {
8221                    if (snap && L0.snap_kv != nullptr) {   // (each slot: the latest row before snap_t that holds it)
8222                        const int64_t ps = p0 + wp.snap_t;
8223                        for (int sl = 0; sl < R; ++sl) {
8224                            const int64_t q = ps - 1 - (((ps - 1 - sl) % R) + R) % R;
8225                            const float* kv = q >= p0 ? c.ckr + (size_t) (q - p0) * HD : l.c_kv + (size_t) sl * HD;
8226                            const float* sc = q >= p0 ? c.cgr + (size_t) (q - p0) * HD : l.c_score + (size_t) sl * HD;
8227                            CK(cudaMemcpyAsync(L0.snap_kv + (size_t) sl * HD, kv, (size_t) HD * 4, cudaMemcpyDeviceToDevice, s));
8228                            CK(cudaMemcpyAsync(L0.snap_sc + (size_t) sl * HD, sc, (size_t) HD * 4, cudaMemcpyDeviceToDevice, s));
8229                        }
8230                    }
8231                    compress_win(c.ckr, c.cgr, l.c_kv, l.c_score, R, (int) p0, T, HD, l.c_norm, g.eps, c.latent, s);
8232                }
8233            }
8234            const int clen_max = (int) ((p0 + T) / R);
8235            if (l.ix_src) {
8236                Src& ks = srcs[(size_t) l.ik_src];
8237                if (l.owns_k && ng > 0) {
8238                    x3::rows_f16(latent, HD, nullptr, ng, HD, c.lat16, s);
8239                    if (!gemm(d, c, l.i_wk, c.lat16, HD, ng, c.ikr, g.ix_hd, 0.0f, err)) return false;
8240                    Finish fi;
8241                    fi.w = l.ik_norm;
8242                    fi.eps = g.eps;
8243                    fi.rd = g.rd;
8244                    fi.pos = (int) (g_first * R);
8245                    fi.pos_step = R;
8246                    fi.freqs = freqs;
8247                    fi.quant = 3;
8248                    fi.pdst = ks.ik[(size_t) l.dev] + (size_t) g_first * ik_rb();
8249                    fi.pdst_stride = (long long) ik_rb();
8250                    if (scr_master) { fi.master = ks.master_ik[(size_t) l.dev] + (size_t) g_first * g.rd; fi.master_stride = g.rd; fi.master_valid = ks.master_ik_valid[(size_t) l.dev] + g_first; }
8251                    finish(c.ikr, ng, g.ix_hd, g.ix_hd, fi, s);
8252                }
8253                if (clen_max > 0 && !kv_only) {
8254                    if (!gemm_f16w(c, l.i_wproj, g.ix_heads, D, c.x16, D, T,
8255                                   1.0f / std::sqrt((float) g.ix_hd) / std::sqrt((float) g.ix_heads), c.iw, 64, err))
8256                        return false;
8257                    for (int a0 = 0; a0 < T; a0 += c.AI) {
8258                        const int na = std::min(c.AI, T - a0);
8259                        const int64_t pa = p0 + a0;
8260                        if (!gemm(d, c, l.i_wq_b, c.qr16 + (size_t) a0 * g.q_lora, g.q_lora, na, c.iq,
8261                                  g.ix_heads * g.ix_hd, 0.0f, err))
8262                            return false;
8263                        Finish fi;
8264                        fi.rd = g.rd;
8265                        fi.pos = (int) pa;
8266                        fi.vpp = g.ix_heads;
8267                        fi.freqs = freqs;
8268                        fi.quant = 3;
8269                        finish(c.iq, na * g.ix_heads, g.ix_hd, g.ix_hd, fi, s);
8270                        Rows lim;
8271                        lim.gen = 1;
8272                        lim.p0 = pa;
8273                        lim.R = R;
8274                        lim.kcap = g.ix_topk;
8275                        lim.ccap = g.cand_topk;
8276                        lim.blk = std::max(1, g.cand_blk);
8277                        const int nlast = (int) ((pa + na) / R);   // the slab's widest query
8278                        int* tk = c.topk + (size_t) a0 * topk_stride();
8279                        int* cd = c.cand + (size_t) a0 * cand_stride();
8280                        const float* iw = c.iw + (size_t) a0 * 64;
8281                        if (nlast <= 0) continue;
8282                        if (l.uses_cand && (nlast + g.cand_blk - 1) / g.cand_blk > g.cand_topk) {
8283                            Rows cl = lim;
8284                            cl.gen = 2;
8285                            index_score(c.iq, iw, ks.ik[(size_t) l.dev], g.ix_heads, g.ix_hd, na, g.cand_topk * g.cand_blk,
8286                                        cd, (int) cand_stride(), g.cand_blk, cl, c.scores, ss, s);
8287                            Rows tr = lim;
8288                            tr.gen = 3;
8289                            topk(c.scores, ss, na, tr, cd, (int) cand_stride(), g.cand_blk, tk, (int) topk_stride(), s);
8290                        } else {
8291                            index_score(c.iq, iw, ks.ik[(size_t) l.dev], g.ix_heads, g.ix_hd, na, nlast, nullptr, 0, 1,
8292                                        lim, c.scores, ss, s);
8293                            if (l.cand_src) {
8294                                Rows cr = lim;
8295                                cr.kcap = g.cand_topk;
8296                                cand_blocks(c.scores, ss, na, cr, g.cand_blk, c.bm, (long long) bm_stride(), cd,
8297                                            (int) cand_stride(), s);
8298                            }
8299                            topk(c.scores, ss, na, lim, nullptr, 0, 1, tk, (int) topk_stride(), s);
8300                        }
8301                    }
8302                }
8303            }
8304            if (l.kv_src && ng > 0) {
8305                Finish fc;
8306                fc.rd = g.rd;
8307                fc.pos = (int) (g_first * R);
8308                fc.pos_step = R;
8309                fc.freqs = freqs;
8310                fc.quant = 2;
8311                fc.pdst = sr.ckv[(size_t) l.dev] + (size_t) g_first * ckv_rb();
8312                fc.pdst_stride = (long long) ckv_rb();
8313                if (scr_master) { fc.master = sr.master[(size_t) l.dev] + (size_t) g_first * g.rd; fc.master_stride = g.rd; fc.master_valid = sr.master_valid[(size_t) l.dev] + g_first; }
8314                finish(const_cast<float*>(latent), ng, HD, HD, fc, s);
8315                if (mi == 0 && sr.remote) {   // the new rows for the other groups' readers (slot k % 2, once
8316                    const int slot = wp.k % 2;  // they took the chunk before last's)
8317                    if (wp.k >= 2)
8318                        for (int r : sr.readers) wait_flags(sr.x_ack + ((size_t) slot * devs.size() + r) * 32, 1, 32, wp.win - 2, s);
8319                    Xfer x;
8320                    x.src[0] = fc.pdst;
8321                    x.dst[0] = sr.stage(slot);
8322                    x.bytes[0] = (size_t) ng * ckv_rb();
8323                    x.n = 1;
8324                    if (l.owns_k && srcs[(size_t) l.ik_src].ik[(size_t) l.dev] != nullptr) {
8325                        x.src[1] = srcs[(size_t) l.ik_src].ik[(size_t) l.dev] + (size_t) g_first * ik_rb();
8326                        x.dst[1] = sr.stage(slot) + x_cap() * ckv_rb();
8327                        x.bytes[1] = (size_t) ng * ik_rb();
8328                        x.n = 2;
8329                    }
8330                    xfer_put(x, sr.flag(slot), wp.win, d.xcnt, s);
8331                }
8332            }
8333            ckv = sr.ckv[(size_t) l.dev];
8334        }
8335        if (kv_only) return true;
8336        prof_mark(d, 7);
8337        // the attention in slabs: q, the sparse attention, wo_a, wo_b (this member's share) into acc
8338        if (NHL == 0) CK(cudaMemsetAsync(c.acc, 0, (size_t) T * D * sizeof(*c.acc), s));   // (no heads)
8339        for (int a0 = 0; a0 < T && NHL > 0; a0 += c.A) {
8340            const int na = std::min(c.A, T - a0);
8341            const size_t wq_n = (size_t) HQ * g.q_lora, woa_n = (size_t) (HQ / OG) * g.o_lora;
8342            uint16_t* wc = c.wc;
8343            if (!gemm_kept(d, c, l.wq_b, wc, c.wc_tag[0], c.qr16 + (size_t) a0 * g.q_lora, g.q_lora, na, c.q, HQ, 0.0f,
8344                           err))
8345                return false;
8346            Finish fr;
8347            fr.rd = g.rd;
8348            fr.pos = (int) (p0 + a0);
8349            fr.vpp = NHL;
8350            fr.freqs = freqs;
8351            finish(c.q, na * NHL, HD, HD, fr, s);
8352            prof_mark(d, 8);
8353            AttnRows ar;
8354            ar.gen = 1;
8355            ar.p0 = p0;
8356            ar.t0 = a0;
8357            ar.win = g.win;
8358            ar.floor = scr_band_start;
8359            ar.R = l.ratio;
8360            ar.kcap = g.ix_topk;
8361            sparse_attn(c.q, c.ext, ckv, c.topk + (size_t) a0 * topk_stride(), (int) topk_stride(), ar, l.sink, NHL, HD,
8362                        na, 1.0f / std::sqrt((float) HD), c.o, s, kKvFp4, 0, &d.attn_scr);   // (a short last slab)
8363            prof_mark(d, 9);
8364            Finish fo;
8365            fo.rd = g.rd;
8366            fo.pos = (int) (p0 + a0);
8367            fo.vpp = NHL;
8368            fo.freqs = freqs;
8369            fo.inverse = 1;
8370            fo.quant = 1;
8371            finish(c.o, na * NHL, HD, HD, fo, s);
8372            x3::rows_f16(c.o, HQ, nullptr, na, HQ, c.o16, s);
8373            const int per = HQ / OG;
8374            for (int gi = 0; gi < OG; ++gi)
8375                if (!gemm_kept(d, c, l.wo_a[gi], wc ? wc + wq_n + (size_t) gi * woa_n : nullptr, c.wc_tag[1 + gi],
8376                               c.o16 + (size_t) gi * per, HQ, na, c.oa + (size_t) gi * g.o_lora, OG * g.o_lora, 0.0f,
8377                               err))
8378                    return false;
8379            x3::rows_f16(c.oa, OG * g.o_lora, nullptr, na, OG * g.o_lora, c.oa16, s);
8380            if (!gemm_kept(d, c, l.wo_b, wc ? wc + wq_n + (size_t) OG * woa_n : nullptr, c.wc_tag[17], c.oa16,
8381                           OG * g.o_lora, na, c.acc + (size_t) a0 * D, D, 0.0f, err))
8382                return false;
8383        }
8384        if (nm > 1) allreduce(c.acc, T * D, ab, mi, ++c.arb_seq, d.xcnt, s);
8385        hc_post_inplace(c.acc, c.h, c.a_post, c.a_comb, D, H, T, s);
8386        prof_mark(d, 1);
8387        // the MoE
8388        if (!hc_mix_chunk(d, c, c.h, l.hcf_fn, T, c.mix, err)) return false;
8389        hc_split(c.mix, l.hcf_scale, l.hcf_base, H, g.sinkhorn, g.hc_eps, T, c.f_pre, c.f_post, c.f_comb, s);
8390        hc_pre_norm(c.h, c.a_pre, l.ffn_norm, D, H, T, g.eps, c.x, s);
8391        x3::rows_f16(c.x, D, nullptr, T, D, c.x16, s);
8392        gemv_f32(l.gate_w, c.x, l.n_exp, D, T, c.glog, 1024, s);   // (F32 x: the token path's bits)
8393        for (int r0 = 0; r0 < T; r0 += kVlRows) {   // (route()'s image bits cover kVlRows rows a call)
8394            const int nr = std::min(kVlRows, T - r0);
8395            VlBits vb;
8396            const bool vl = l.gate_bias_vl != nullptr && vl_bits(p0 + r0, nr, vb);
8397            static const bool cp_prefill = std::getenv("DS4_CP_PREFILL") != nullptr && std::atof(std::getenv("DS4_CP_PREFILL")) > 0.0;
8398            route(c.glog + (size_t) r0 * 1024, l.gate_bias, l.n_exp, l.k_exp, nr, g.route_scale,
8399                  c.ridx + (size_t) r0 * kPicks, c.rw + (size_t) r0 * kPicks, s, l.gate_bias_vl, vl ? &vb : nullptr,
8400                  cp_prefill && l.nm == 1 ? l.vram_tab : nullptr, cp_prefill && l.nm == 1 ? l.res_tab : nullptr);
8401        }
8402        const int n_vs = L0.n_slots + (int) L0.host_list.size();
8403        CK(cudaMemcpyAsync(l.vs_dev, l.vs_pin, (size_t) l.n_exp * 4, cudaMemcpyHostToDevice, s));   // (this member's)
8404        moe_sort(c.ridx, T, l.k_exp, l.vs_dev, n_vs, c.bounds, c.row_tok, c.pos, s);
8405        CK(cudaMemcpyAsync(c.bounds_pin, c.bounds, (size_t) (n_vs + 1) * 4, cudaMemcpyDeviceToHost, s));
8406        prof_mark(d, 10);
8407        // the shared expert into acc while the host waits for the bounds
8408        if (!gemm(d, c, l.s1, c.x16, D, T, c.sg, FF, 0.0f, err) || !gemm(d, c, l.s3, c.x16, D, T, c.su, FF, 0.0f, err))
8409            return false;
8410        swiglu(c.sg, c.su, T * FF, g.lim, c.sg, s);
8411        x3::rows_f16(c.sg, FF, nullptr, T, FF, c.sh16, s);
8412        if (!gemm(d, c, l.s2, c.sh16, FF, T, c.acc, D, 0.0f, err)) return false;
8413        prof_mark(d, 2);
8414        // the expert stream's copies keep going while the device runs this layer's attention, routing and shared expert:
8415        // the next items (this layer's likely experts, queued when the layer before routed) go out as they are ready and
8416        // ring slots free, not only once the bounds are back (Project Maya #360; DS4_FLOW_PUMP_WAIT=0: wait as before)
8417        static const bool pump_wait = std::getenv("DS4_FLOW_PUMP_WAIT") == nullptr ||
8418                                      std::atoi(std::getenv("DS4_FLOW_PUMP_WAIT")) != 0;
8419        if (c.flow && pump_wait)
8420            while (cudaStreamQuery(s) == cudaErrorNotReady) {
8421                if (!flow_pump(c, err)) return false;
8422                std::this_thread::yield();
8423            }
8424        CK(cudaStreamSynchronize(s));
8425        std::vector<int> b(c.bounds_pin, c.bounds_pin + n_vs + 1);
8426        if (dump_r != nullptr && mi == 0) {
8427            const size_t nk = (size_t) T * l.k_exp, np = (size_t) T * kPicks;
8428            std::vector<int> ri(np), rt(nk);
8429            std::vector<float> gl((size_t) T * l.n_exp), gb((size_t) l.n_exp);
8430            CK(cudaMemcpy(ri.data(), c.ridx, np * 4, cudaMemcpyDeviceToHost));
8431            CK(cudaMemcpy(rt.data(), c.row_tok, nk * 4, cudaMemcpyDeviceToHost));
8432            CK(cudaMemcpy2D(gl.data(), (size_t) l.n_exp * 4, c.glog, 1024 * 4, (size_t) l.n_exp * 4, (size_t) T,
8433                            cudaMemcpyDeviceToHost));
8434            CK(cudaMemcpy(gb.data(), l.gate_bias, gb.size() * 4, cudaMemcpyDeviceToHost));
8435            std::lock_guard<std::mutex> lk(dump_mu);
8436            const int64_t hdr[8] = {l.il, p0, T, l.k_exp, l.n_exp, n_vs, L0.n_slots, kPicks};
8437            std::fwrite(hdr, 8, 8, dump_r);
8438            std::fwrite(ri.data(), 4, np, dump_r);
8439            std::fwrite(L0.vs_pin, 4, (size_t) l.n_exp, dump_r);
8440            std::fwrite(b.data(), 4, b.size(), dump_r);
8441            std::fwrite(rt.data(), 4, nk, dump_r);
8442            std::fwrite(gl.data(), 4, gl.size(), dump_r);
8443            std::fwrite(gb.data(), 4, gb.size(), dump_r);
8444            std::fflush(dump_r);
8445        }
8446        if (mi == 0 && !l.mtp && (pred_f != nullptr || xin_f != nullptr)) {
8447            std::lock_guard<std::mutex> lk(dump_mu);
8448            if (pred_f != nullptr) {
8449                float* dp = nullptr;
8450                CK(cudaMalloc(&dp, (size_t) T * 256 * 4));
8451                pred_proj_k<<<T, 256, 0, s>>>(c.x, (int) D, dp);
8452                std::vector<float> hp((size_t) T * 256), hl((size_t) T * l.n_exp);
8453                CK(cudaMemcpyAsync(hp.data(), dp, hp.size() * 4, cudaMemcpyDeviceToHost, s));
8454                CK(cudaMemcpy2DAsync(hl.data(), (size_t) l.n_exp * 4, c.glog, 1024 * 4, (size_t) l.n_exp * 4, (size_t) T,
8455                                     cudaMemcpyDeviceToHost, s));
8456                CK(cudaStreamSynchronize(s));
8457                CK(cudaFree(dp));
8458                std::vector<uint16_t> o(hp.size() + hl.size());
8459                for (size_t i = 0; i < hl.size(); ++i) o[i] = strata::kernels::f16_from_f32(hl[i]);
8460                for (size_t i = 0; i < hp.size(); ++i) o[hl.size() + i] = strata::kernels::f16_from_f32(hp[i]);
8461                const uint8_t hd[3] = {(uint8_t) l.il, (uint8_t) (T & 255), (uint8_t) (T >> 8)};
8462                std::fwrite(hd, 1, 3, pred_f);
8463                std::fwrite(o.data(), 2, o.size(), pred_f);
8464            }
8465            if (xin_f != nullptr && xin_got[(size_t) l.il] < xin_n) {   // up to 32 (DS4_XIN_PER) evenly spaced tokens of the chunk
8466                static const int xin_per = std::getenv("DS4_XIN_PER") ? std::max(1, std::atoi(std::getenv("DS4_XIN_PER"))) : 32;
8467                 const int tk = std::min(std::min(T, xin_per), xin_n - xin_got[(size_t) l.il]);
8468                const int stride = std::max(1, T / tk);
8469                std::vector<float> hx((size_t) T * D);
8470                CK(cudaMemcpyAsync(hx.data(), c.x, hx.size() * 4, cudaMemcpyDeviceToHost, s));
8471                CK(cudaStreamSynchronize(s));
8472                const uint8_t hd[3] = {(uint8_t) l.il, (uint8_t) (tk & 255), (uint8_t) (tk >> 8)};
8473                std::fwrite(hd, 1, 3, xin_f);
8474                for (int i = 0; i < tk; ++i) std::fwrite(hx.data() + (size_t) std::min(T - 1, i * stride) * D, 4, (size_t) D, xin_f);
8475                xin_got[(size_t) l.il] += tk;
8476            }
8477        }
8478        if (mi == 0 && trace_f != nullptr && !l.mtp) {   // DS4_TRACE: a chunk's picks, u8 (layer | 0x80), u16 T, T x k int16 ids
8479            std::vector<int> ri((size_t) T * kPicks);
8480            CK(cudaMemcpy(ri.data(), c.ridx, ri.size() * 4, cudaMemcpyDeviceToHost));
8481            std::lock_guard<std::mutex> lk(dump_mu);
8482            const uint8_t hd[3] = {(uint8_t) (l.il | 0x80), (uint8_t) (T & 255), (uint8_t) (T >> 8)};
8483            std::fwrite(hd, 1, 3, trace_f);
8484            for (int t = 0; t < T; ++t)
8485                for (int i = 0; i < l.k_exp; ++i) {
8486                    const int16_t v = (int16_t) ri[(size_t) t * kPicks + i];
8487                    std::fwrite(&v, 2, 1, trace_f);
8488                }
8489        }
8490        if (mi == 0) {   // the profile (the CPU lane's experts: by the plan's order)
8491            uint32_t* pr = prof.data() + (size_t) l.il * g.n_exp;
8492            for (int e = 0; e < l.n_exp; ++e) {
8493                const int v = L0.vs_pin[e];
8494                const int cnt = b[(size_t) v + 1] - b[(size_t) v];
8495                pr[e] += (uint32_t) cnt;
8496                if (cnt > 0) {   // (the expert cache learns from a chunked prompt as from windows: heat, and the CPU lane's hits)
8497                    l.heat[(size_t) e] += (float) cnt;
8498                    if (l.slot[(size_t) e] < 0) l.cpu_hits.push_back(e);
8499                }
8500            }
8501            st.experts += (int64_t) T * l.k_exp;
8502        }
8503        if (c.flow) {
8504            if (!flow_layer(d, c, L0, mi, wp.k, T, b, err)) return false;
8505            if (nm > 1) allreduce(c.acc, T * D, ab, mi, ++c.arb_seq, d.xcnt, s);
8506            hc_post_inplace(c.acc, c.h, c.f_post, c.f_comb, D, H, T, s);
8507            CK(cudaMemcpyAsync(c.pre, c.f_pre, (size_t) T * 8 * 4, cudaMemcpyDeviceToDevice, s));
8508            prof_mark(d, 3);
8509            return true;
8510        }
8511        // the streamed experts as their batches arrive (each batch's slots freed for the copies at once), the VRAM ones
8512        // in shares between them (the device works while the copies run)
8513        const int di = l.dev, P = Chunk::kParts;
8514        int nb = 0;
8515        for (size_t q = S.kp; q < S.b.size() && S.b[q].il == L0.il && S.b[q].k == wp.k; ++q) ++nb;
8516        int v_done = 0;
8517        for (int bi = 0; bi < nb; ++bi) {
8518            const Batch& bt = S.b[S.kp];
8519            const int half = (int) (S.kp % P);
8520            CK(cudaStreamWaitEvent(s, c.filled[half], 0));
8521            const int v0 = L0.n_slots + bt.j0;
8522            if (!run_set(d, c, l, c.ring + (size_t) half * (c.ring_n / P) * c.ring_stride, v0, c.ring_stride, c.bounds,
8523                         b.data(), v0, v0 + bt.n, T, err))
8524                return false;
8525            CK(cudaEventRecord(c.freed[half], s));
8526            ++S.kp;
8527            if (!copy_ahead(d, c, S, di, err)) return false;
8528            const int v_to = (int) ((int64_t) L0.n_slots * (bi + 1) / nb);
8529            if (!run_set(d, c, l, l.vram_base, 0, unit(l), c.bounds, b.data(), v_done, v_to, T, err)) return false;
8530            v_done = v_to;
8531        }
8532        if (!run_set(d, c, l, l.vram_base, 0, unit(l), c.bounds, b.data(), v_done, L0.n_slots, T, err)) return false;
8533        if (nm > 1) allreduce(c.acc, T * D, ab, mi, ++c.arb_seq, d.xcnt, s);
8534        hc_post_inplace(c.acc, c.h, c.f_post, c.f_comb, D, H, T, s);
8535        CK(cudaMemcpyAsync(c.pre, c.f_pre, (size_t) T * 8 * 4, cudaMemcpyDeviceToDevice, s));
8536        prof_mark(d, 3);
8537        return true;
8538    }
8539
8540    // the CPU lane's experts of every layer, in index order, and each expert's virtual slot (before a chunk)
8541    void plan_streams() {
8542        for (Layer& l : L) {
8543            if (l.mtp || l.vs_pin == nullptr) continue;
8544            const bool all = lent_ && lend_of_[(size_t) l.il];   // (a lent prompt: the VRAM experts stream too)
8545            l.host_list.clear();
8546            for (int e = 0; e < l.n_exp; ++e)
8547                if (all || l.slot[(size_t) e] < 0) l.host_list.push_back(e);
8548            for (int m = 0; m < l.nm; ++m) {   // (a group's members: each its own copy)
8549                Layer& x = member(l, m);
8550                int j = 0;
8551                for (int e = 0; e < l.n_exp; ++e)
8552                    x.vs_pin[e] = !all && l.slot[(size_t) e] >= 0 ? l.slot[(size_t) e] : l.n_slots + j++;
8553            }
8554        }
8555    }
8556
8557    // a chunk's hand-off between groups: h | pre | topk | cand of a chunk of T rows
8558    Xfer chunk_xfer(uint8_t* host, Chunk& c, int T, bool put) const {
8559        const size_t nh = (size_t) T * g.hc * g.dim * 4, np = (size_t) T * 8 * 4, nk = (size_t) T * topk_stride() * 4,
8560                     nc = (size_t) T * cand_stride() * 4;
8561        void* dv[4] = {c.h, c.pre, c.topk, c.cand};
8562        uint8_t* hv[4] = {host, host + nh, host + nh + np, host + nh + np + nk};
8563        const size_t nb[4] = {nh, np, nk, nc};
8564        Xfer x;
8565        x.n = 4;
8566        for (int i = 0; i < 4; ++i) {
8567            x.src[i] = put ? (const void*) dv[i] : (const void*) hv[i];
8568            x.dst[i] = put ? (void*) hv[i] : dv[i];
8569            x.bytes[i] = nb[i];
8570        }
8571        return x;
8572    }
8573
8574    // a run of chunks (start positions p0[k], sizes T[k], seqs seq[k]) on device di: its layers chunk after chunk, the
8575    // groups pipelined (a group takes chunk k + 1 while the next takes chunk k: the hand-offs and the sources' rows
8576    // two deep, each slot reused once its readers acknowledged it), the streamed experts' copies running ahead across
8577    // layers and chunks
8578    struct Run {
8579        std::vector<int64_t> p0;
8580        std::vector<int> T;
8581        std::vector<unsigned> seq;
8582        int64_t snap_pos = -1;   // feed_mark: the position whose state before it the layers keep (-1: none)
8583        // a long prompt's skip (forward_chunks): the cut at row cut_r of chunk cut_k - the chunks before it go through
8584        // the layers before `yoco`, that layer as layer_chunk's kv_only and none after it; chunk cut_k's rows before
8585        // cut_r the same, its rows from cut_r on and the chunks after it through every layer (yoco -1: no skip)
8586        int yoco = -1, cut_k = 0, cut_r = 0;
8587        bool runs(int k, int il) const { return yoco < 0 || k >= cut_k || il <= yoco; }
8588        bool kv_only(int k, int il) const { return yoco >= 0 && k < cut_k && il == yoco; }
8589        int r0(int k, int il) const { return yoco >= 0 && k == cut_k && il >= yoco ? cut_r : 0; }   // the first row
8590    };
8591    // layer L0 over chunk k per a long prompt's skip (Run): its kv_only, or its rows from Run::r0 on - the chunk's
8592    // buffers seen from that row (the yoco layer: its kv_only over the rows before it first)
8593    bool run_layer(Layer& L0, int mi, int64_t p0, int T, const WinPlan& wp, Streamer& S, std::string& err,
8594                   const Run& run, int k, int il) {
8595        if (run.kv_only(k, il)) return layer_chunk(L0, mi, p0, T, wp, S, err, true);
8596        const int r0 = run.r0(k, il);
8597        if (r0 <= 0) return layer_chunk(L0, mi, p0, T, wp, S, err);
8598        if (il == run.yoco) {
8599            WinPlan w0 = wp;
8600            w0.snap_t = -1;
8601            if (!layer_chunk(L0, mi, p0, r0, w0, S, err, true)) return false;
8602        }
8603        Chunk& c = *chunks[(size_t) member(L0, mi).dev];
8604        float* const h0 = c.h;
8605        float* const pre0 = c.pre;
8606        c.h += (size_t) r0 * g.hc * g.dim;
8607        c.pre += (size_t) r0 * 8;
8608        WinPlan w1 = wp;
8609        w1.snap_t = wp.snap_t >= r0 ? wp.snap_t - r0 : -1;
8610        const bool ok = layer_chunk(L0, mi, p0 + r0, T - r0, w1, S, err);
8611        c.h = h0;
8612        c.pre = pre0;
8613        return ok;
8614    }
8615
8616    // layer-major (c.lm: a run of several chunks, device di every trunk layer, the flow set up by run_dev_chunks):
8617    // layer after layer, each through all the chunks in order - a chunk's state to host memory after each of its
8618    // layers and back before the next - so a layer's experts are read from the files once for the whole run (the
8619    // layer cache keeps what a chunk read for the chunks after it), where chunk after chunk reads them once a chunk
8620    bool run_dev_layers(int di, const Run& run, std::string& err) {
8621        Dev& d = devs[(size_t) di];
8622        Chunk& c = *chunks[(size_t) di];
8623        cudaSetDevice(d.id);
8624        cudaStream_t s = d.st;
8625        const int D = g.dim, H = g.hc, nk = (int) run.T.size();
8626        Streamer S;   // (none: the flow streams)
8627        const size_t hb = chunk_hand_bytes();
8628        // the Engram rows: (layer, chunk) after (layer, chunk) in the run's order, each read on a helper thread while
8629        // the one before runs (slot u % 2, once unit u - 2's copy of it is done)
8630        std::vector<std::pair<int, int>> egu;   // (Engram layer, chunk)
8631        for (int il : c.fl_layers)
8632            if (L[(size_t) il].eg >= 0)
8633                for (int k = 0; k < nk; ++k)
8634                    if (run.runs(k, il)) egu.push_back({L[(size_t) il].eg, k});
8635        const size_t eg_per = (size_t) (pk.eg_ngram - 1) * pk.eg_heads * (pk.eg_hd + pk.eg_hd / 32);
8636        auto read_eg = [this, &c, &run, &egu, eg_per](size_t u) {
8637            if (u >= 2) cudaEventSynchronize(c.eg_ev[u % 2]);
8638            const int li = egu[u].first, k = egu[u].second;
8639            engram_rows(run.p0[(size_t) k], run.T[(size_t) k], li, c.eg_host[u % 2] + (size_t) li * c.C * eg_per);
8640        };
8641        size_t eg_u = 0;
8642        std::future<void> eg_next;
8643        if (!egu.empty()) eg_next = std::async(std::launch::async, read_eg, (size_t) 0);
8644        for (size_t li = 0; li < c.fl_layers.size(); ++li) {
8645            const int il = c.fl_layers[li];
8646            Layer& L0 = L[(size_t) il];
8647            const bool last_l = li + 1 == c.fl_layers.size();
8648            for (int k = 0; k < nk; ++k) {
8649                if (!run.runs(k, il)) continue;   // (a skipped early chunk: nothing after the yoco layer)
8650                if (halt_now()) return halt_end(di, err);   // (a Stop: one GPU, this one)
8651                const int64_t p0 = run.p0[(size_t) k];
8652                const int T = run.T[(size_t) k], slot = k % 2;
8653                const bool last_k = k + 1 == nk;
8654                WinPlan wp;
8655                wp.par = true;
8656                wp.async = true;
8657                wp.win = run.seq[(size_t) k];
8658                wp.k = k;
8659                wp.snap_t = run.snap_pos >= p0 && run.snap_pos < p0 + T ? (int) (run.snap_pos - p0) : -1;
8660                if (L0.eg >= 0) {   // this unit's rows ready, the next one's on their way
8661                    const double te = now_ms();
8662                    eg_next.get();
8663                    st.engram_ms += now_ms() - te;
8664                    wp.eg_slot = (int) (eg_u % 2);
8665                    if (++eg_u < egu.size()) eg_next = std::async(std::launch::async, read_eg, eg_u);
8666                }
8667                if (li == 0) {   // the chunk's input: its embedding rows
8668                    if (k >= 2) CK(cudaEventSynchronize(c.emb_ev[slot]));
8669                    for (int t = 0; t < T; ++t)
8670                        std::memcpy(c.emb_host[slot] + (size_t) t * D, emb_row(p0 + t, toks[(size_t) (p0 + t)]),
8671                                    (size_t) D * 2);
8672                    CK(cudaMemcpyAsync(c.emb, c.emb_host[slot], (size_t) T * D * 2, cudaMemcpyHostToDevice, s));
8673                    CK(cudaEventRecord(c.emb_ev[slot], s));
8674                    embed(c.emb, T, c.h, D, H, s);
8675                    init_pre(c.pre, T, s);
8676                } else {   // or its state after the layer before
8677                    const Xfer x = chunk_xfer(c.lm_state + (size_t) k * hb, c, T, false);
8678                    for (int i = 0; i < x.n; ++i)
8679                        CK(cudaMemcpyAsync(x.dst[i], x.src[i], x.bytes[i], cudaMemcpyHostToDevice, s));
8680                }
8681                if (last_k && g.n_mtp > 0) {   // the drafter's taps: the last chunk's last rows
8682                    const auto it = std::find(g.d_targets.begin(), g.d_targets.end(), il);
8683                    if (it != g.d_targets.end()) {
8684                        const size_t j = (size_t) (it - g.d_targets.begin()), nt = g.d_targets.size();
8685                        const int nr = std::min(T, tap_cap);
8686                        hc_mean(c.h + (size_t) (T - nr) * H * D, nr, H, D, d.tap, D, s);
8687                        CK(cudaStreamWaitEvent(s, ev_seed, 0));
8688                        CK(cudaMemcpy2DAsync(h_taps + j * D, nt * D * 4, d.tap, (size_t) D * 4, (size_t) D * 4,
8689                                             (size_t) nr, cudaMemcpyDeviceToHost, s));
8690                    }
8691                }
8692                const bool kvo = run.kv_only(k, il);
8693                if (!run_layer(L0, 0, p0, T, wp, S, err, run, k, il)) return false;
8694                if (dump_l != nullptr) dump_layer(d, c.h, il, p0, T);
8695                if (kvo) continue;   // (no layer after it reads this chunk's state)
8696                if (!last_l) {   // the chunk's state kept for the next layer
8697                    const Xfer x = chunk_xfer(c.lm_state + (size_t) k * hb, c, T, true);
8698                    for (int i = 0; i < x.n; ++i)
8699                        CK(cudaMemcpyAsync(x.dst[i], x.src[i], x.bytes[i], cudaMemcpyDeviceToHost, s));
8700                    continue;
8701                }
8702                // through every layer: the chunk's end, and the logits
8703                if ((size_t) k < chunk_done.size()) {
8704                    CK(cudaEventRecord(chunk_done[(size_t) k], s));
8705                    chunk_rec[(size_t) k].store(1, std::memory_order_release);
8706                }
8707                if (logits_all) {   // every row's logits (tests): the head over the chunk's rows, 16 at a time
8708                    const size_t base = (size_t) (p0 - run.p0[0]) * g.vocab;
8709                    for (int r0 = 0; r0 < T; r0 += kWin) {
8710                        const int nr = std::min(kWin, T - r0);
8711                        hc_pre_norm(c.h + (size_t) r0 * H * D, c.pre + (size_t) r0 * 8, d.norm_w, D, H, nr, g.eps, d.x, s);
8712                        if (!head_share(d, d.mi, d.x, nr, err)) return false;
8713                        CK(cudaMemcpyAsync(chunk_logits.data() + base + (size_t) r0 * g.vocab, d.logits,
8714                                           (size_t) nr * g.vocab * 4, cudaMemcpyDeviceToHost, s));
8715                        CK(cudaStreamSynchronize(s));
8716                    }
8717                } else if (last_k && n_logits > 0) {   // (the last rows' logits, into the window path's buffers)
8718                    const int t0 = T - n_logits;
8719                    hc_pre_norm(c.h + (size_t) t0 * H * D, c.pre + (size_t) t0 * 8, d.norm_w, D, H, n_logits, g.eps, d.x, s);
8720                    if (!head_share(d, d.mi, d.x, n_logits, err)) return false;
8721                }
8722            }
8723            lm_layers.store((int) li + 1, std::memory_order_release);
8724        }
8725        return true;
8726    }
8727    bool run_dev_chunks(int di, const Run& run, std::string& err) {
8728        Dev& d = devs[(size_t) di];
8729        Chunk& c = *chunks[(size_t) di];
8730        cudaSetDevice(d.id);
8731        cudaStream_t s = d.st;
8732        const int D = g.dim, H = g.hc, nk = (int) run.T.size();
8733        Streamer S;
8734        const int B = std::max(1, c.ring_n / Chunk::kParts);
8735        if (c.flow) {   // (the flow decides its streams as the layers route; nothing planned here)
8736            CK(cudaStreamSynchronize(s));
8737            CK(cudaStreamSynchronize(c.cs));
8738            c.items.clear();
8739            c.base = c.n_read = c.n_dma = c.n_comp = 0;
8740            c.n_file = 0;
8741            std::fill(c.stage_item.begin(), c.stage_item.end(), -1);
8742            c.fl_layers.clear();
8743            for (int il = 0; il < g.nl; ++il)   // (a group's layers: on each member)
8744                for (int m = 0; m < L[(size_t) il].nm; ++m)
8745                    if (member(L[(size_t) il], m).dev == di) c.fl_layers.push_back(il);
8746            c.fl_T = run.T;
8747            c.fl_yoco = run.yoco;
8748            c.fl_cut_k = run.cut_k;
8749            c.fl_cut_r = run.cut_r;
8750            c.spec_k = c.spec_il = -1;
8751            c.wait_ms = 0;
8752            c.it_file = c.it_ram = c.it_spec = c.it_spec_unused = c.it_lc = c.it_vram = 0;
8753            c.lc_il = -1;
8754            c.lc_used = 0;
8755            c.lc_first = c.lc_chk = 0;
8756            c.io_d0 = c.io->direct_bytes();
8757            c.io_b0 = c.io->buffered_bytes();
8758            c.io_busy0 = c.io->busy_ms();
8759            c.io_any0 = c.io->any_ms();
8760            c.io_runs0 = c.io->runs();
8761            c.io_rj0 = c.io->run_jobs();
8762            if (!c.fl_layers.empty()) {
8763                flow_spec(c, 0, c.fl_layers[0], run.T[0]);
8764                if (!flow_pump(c, err)) return false;
8765            }
8766            if (c.lm) return run_dev_layers(di, run, err);
8767        }
8768        for (int k = 0; k < nk && !c.flow; ++k)
8769            for (int il = 0; il < g.nl; ++il) {
8770                if (!run.runs(k, il) || run.kv_only(k, il)) continue;   // (a long prompt's skip: no experts there)
8771                const Layer& L0 = L[(size_t) il];
8772                bool here = false;
8773                for (int m = 0; m < L0.nm; ++m) here = here || member(L0, m).dev == di;
8774                if (!here) continue;
8775                for (int j0 = 0; j0 < (int) L0.host_list.size(); j0 += B)
8776                    S.b.push_back({k, il, j0, std::min(B, (int) L0.host_list.size() - j0)});
8777            }
8778        if (!S.b.empty() && c.ring == nullptr) {
8779            err = "no slots to stream experts into on CUDA" + std::to_string(d.id);
8780            return false;
8781        }
8782        std::atomic<bool> ra_stop{false};
8783        std::thread ra;
8784        if (file_experts && !S.b.empty()) ra = std::thread([this, &S, di, &ra_stop] { read_ahead(S, di, ra_stop); });
8785        struct Join {   // (every way out of the run: the read-ahead ends before S does)
8786            std::atomic<bool>& stop;
8787            std::thread& th;
8788            ~Join() {
8789                stop.store(true);
8790                if (th.joinable()) th.join();
8791            }
8792        } ra_join{ra_stop, ra};
8793        if (!copy_ahead(d, c, S, di, err)) return false;
8794        // this device's Engram layers: chunk k's rows read on a helper thread while chunk k - 1 runs (slot k % 2, once
8795        // chunk k - 2's copy of it is done)
8796        std::vector<int> egs;
8797        for (const Layer& l0 : L)
8798            for (int m = 0; m < l0.nm; ++m)
8799                if (member(l0, m).dev == di && !l0.mtp && l0.eg >= 0) egs.push_back(l0.eg);
8800        const size_t eg_per = (size_t) (pk.eg_ngram - 1) * pk.eg_heads * (pk.eg_hd + pk.eg_hd / 32);
8801        auto read_eg = [this, &c, &run, &egs, eg_per](int k) {
8802            if (k >= 2) cudaEventSynchronize(c.eg_ev[k % 2]);
8803            for (int li : egs)
8804                engram_rows(run.p0[(size_t) k], run.T[(size_t) k], li, c.eg_host[k % 2] + (size_t) li * c.C * eg_per);
8805        };
8806        std::future<void> eg_next;
8807        if (!egs.empty()) eg_next = std::async(std::launch::async, read_eg, 0);
8808        for (int k = 0; k < nk; ++k) {
8809            if (!chunk_go(k)) return halt_end(di, err);   // (a Stop: the chunks every device reaches are done)
8810            const int64_t p0 = run.p0[(size_t) k];
8811            const int T = run.T[(size_t) k], slot = k % 2;
8812            const bool last_k = k + 1 == nk;
8813            if (!egs.empty()) {   // chunk k's rows ready, chunk k + 1's on their way
8814                const double te = now_ms();
8815                eg_next.get();
8816                if (d.mi == 0) st.engram_ms += now_ms() - te;
8817                if (k + 1 < nk) eg_next = std::async(std::launch::async, read_eg, k + 1);
8818            }
8819            WinPlan wp;
8820            wp.par = true;
8821            wp.async = true;
8822            wp.win = run.seq[(size_t) k];
8823            wp.k = k;
8824            wp.snap_t = run.snap_pos >= p0 && run.snap_pos < p0 + T ? (int) (run.snap_pos - p0) : -1;
8825            bool started = false;
8826            std::vector<char> got(srcs.size(), 0);
8827            for (int il = 0; il < g.nl && run.runs(k, il); ++il) {
8828                if (halt_now()) return halt_end(di, err);   // (one GPU: after the layer it is on)
8829                Layer& L0 = L[(size_t) il];
8830                int mi = -1;
8831                for (int m = 0; m < L0.nm; ++m)
8832                    if (member(L0, m).dev == di) mi = m;
8833                if (mi < 0) continue;
8834                if (!started) {   // the chunk's input: its embedding rows, or the previous group's hand-off
8835                    started = true;
8836                    if (il == 0) {
8837                        if (k >= 2) CK(cudaEventSynchronize(c.emb_ev[slot]));
8838                        for (int t = 0; t < T; ++t)
8839                            std::memcpy(c.emb_host[slot] + (size_t) t * D, emb_row(p0 + t, toks[(size_t) (p0 + t)]),
8840                                        (size_t) D * 2);
8841                        CK(cudaMemcpyAsync(c.emb, c.emb_host[slot], (size_t) T * D * 2, cudaMemcpyHostToDevice, s));
8842                        CK(cudaEventRecord(c.emb_ev[slot], s));
8843                        embed(c.emb, T, c.h, D, H, s);
8844                        init_pre(c.pre, T, s);
8845                    } else {
8846                        Chunk& a = *chunks[(size_t) L[(size_t) il - 1].dev];
8847                        xfer_get(chunk_xfer(a.hand[slot], c, T, false), a.hand_flag[slot], wp.win, s);
8848                        set_flag(a.hand_ack + ((size_t) slot * 8 + mi) * 32, wp.win, s);
8849                    }
8850                }
8851                for (int sidx : {L0.src, L0.ix_src ? L0.ik_src : -1}) {
8852                    if (sidx < 0 || got[(size_t) sidx]) continue;
8853                    got[(size_t) sidx] = 1;
8854                    Src& sr = srcs[(size_t) sidx];
8855                    if (L[(size_t) sr.layer].grp == L0.grp) continue;
8856                    const int64_t g_first = p0 / sr.ratio;
8857                    const int ng = (int) std::max<int64_t>(0, (p0 + T) / sr.ratio - g_first);
8858                    Xfer x;
8859                    if (ng > 0 && sr.ckv[(size_t) di] != nullptr) {
8860                        x.src[x.n] = sr.stage(slot);
8861                        x.dst[x.n] = sr.ckv[(size_t) di] + (size_t) g_first * ckv_rb();
8862                        x.bytes[x.n++] = (size_t) ng * ckv_rb();
8863                    }
8864                    if (ng > 0 && sr.ik[(size_t) di] != nullptr) {
8865                        x.src[x.n] = sr.stage(slot) + x_cap() * ckv_rb();
8866                        x.dst[x.n] = sr.ik[(size_t) di] + (size_t) g_first * ik_rb();
8867                        x.bytes[x.n++] = (size_t) ng * ik_rb();
8868                    }
8869                    if (x.n > 0) xfer_get(x, sr.flag(slot), wp.win, s);
8870                    set_flag(sr.x_ack + ((size_t) slot * devs.size() + di) * 32, wp.win, s);   // (taken, or none)
8871                }
8872                if (last_k && mi == 0 && g.n_mtp > 0) {   // the drafter's taps: the last chunk's last rows
8873                    const auto it = std::find(g.d_targets.begin(), g.d_targets.end(), il);
8874                    if (it != g.d_targets.end()) {
8875                        const size_t j = (size_t) (it - g.d_targets.begin()), nt = g.d_targets.size();
8876                        const int nr = std::min(T, tap_cap);
8877                        hc_mean(c.h + (size_t) (T - nr) * H * D, nr, H, D, d.tap, D, s);
8878                        CK(cudaStreamWaitEvent(s, ev_seed, 0));
8879                        CK(cudaMemcpy2DAsync(h_taps + j * D, nt * D * 4, d.tap, (size_t) D * 4, (size_t) D * 4,
8880                                             (size_t) nr, cudaMemcpyDeviceToHost, s));
8881                    }
8882                }
8883                if (!run_layer(L0, mi, p0, T, wp, S, err, run, k, il)) return false;
8884                if (dump_l != nullptr && mi == 0) dump_layer(d, c.h, il, p0, T);
8885                const bool last = il + 1 == g.nl || L[(size_t) il + 1].grp != L0.grp;
8886                if (last && mi == 0 && il + 1 < g.nl) {   // the hand-off, once the next group took the chunk before last
8887                    const int nnext = L[(size_t) il + 1].nm;
8888                    if (k >= 2) wait_flags(c.hand_ack + (size_t) slot * 8 * 32, nnext, 32, wp.win - 2, s);
8889                    xfer_put(chunk_xfer(c.hand[slot], c, T, true), c.hand_flag[slot], wp.win, d.xcnt, s);
8890                }
8891            }
8892            if (di == head_dev && (size_t) k < chunk_done.size()) {
8893                CK(cudaEventRecord(chunk_done[(size_t) k], s));
8894                chunk_rec[(size_t) k].store(1, std::memory_order_release);
8895            }
8896            if (d.grp == devs[(size_t) head_dev].grp) {   // the head group: each member its share of the logits
8897                if (logits_all) {   // every row's logits (tests): the head over the chunk's rows, 16 at a time
8898                    const size_t base = (size_t) (p0 - run.p0[0]) * g.vocab;
8899                    for (int r0 = 0; r0 < T; r0 += kWin) {
8900                        const int nr = std::min(kWin, T - r0);
8901                        hc_pre_norm(c.h + (size_t) r0 * H * D, c.pre + (size_t) r0 * 8, d.norm_w, D, H, nr, g.eps, d.x, s);
8902                        if (!head_share(d, d.mi, d.x, nr, err)) return false;
8903                        if (di != head_dev) continue;
8904                        CK(cudaMemcpyAsync(chunk_logits.data() + base + (size_t) r0 * g.vocab, d.logits,
8905                                           (size_t) nr * g.vocab * 4, cudaMemcpyDeviceToHost, s));
8906                        CK(cudaStreamSynchronize(s));
8907                    }
8908                } else if (last_k && n_logits > 0) {   // (the last rows' logits, into the window path's buffers)
8909                    const int t0 = T - n_logits;
8910                    hc_pre_norm(c.h + (size_t) t0 * H * D, c.pre + (size_t) t0 * 8, d.norm_w, D, H, n_logits, g.eps, d.x, s);
8911                    if (!head_share(d, d.mi, d.x, n_logits, err)) return false;
8912                }
8913            }
8914        }
8915        return true;
8916    }
8917
8918    // ---- a prompt's path: the flow or windows of 16
8919    // this PC's speeds for pick_path (every device on the flow, the experts in place): the DMA from pinned staging to a
8920    // GPU; the readers copying RAM into staging; the disk read by them (experts not in RAM); the CPU lane on experts in
8921    // RAM and on ones it reads from the disk first - each timed once, a few experts' worth (DS4_PATH_PICK=0: always the
8922    // flow, as before)
8923    void calibrate_paths() {
8924        if (chunk <= 0 || chunk_min != kFlowChunkMin || std::getenv("DS4_CHUNK_MIN") != nullptr) return;
8925        if (const char* v = std::getenv("DS4_PATH_PICK"))
8926            if (std::atoi(v) == 0) return;
8927        int di = -1;
8928        for (size_t i = 0; i < chunks.size() && di < 0; ++i)
8929            if (chunks[i] != nullptr && chunks[i]->flow && chunks[i]->S >= 2) di = (int) i;
8930        if (di < 0) return;
8931        Chunk& c = *chunks[(size_t) di];
8932        Dev& d = devs[(size_t) di];
8933        cudaSetDevice(d.id);
8934        const double t0 = now_ms();
8935        // the DMA: staging -> the ring (once to warm up, once timed)
8936        const size_t nb = std::min({(size_t) 256 << 20, (size_t) c.S * c.stage_stride, (size_t) c.ring_n * c.ring_stride});
8937        double ms = 0;
8938        for (int rep = 0; rep < 2; ++rep) {
8939            const double a = now_ms();
8940            if (cudaMemcpyAsync(c.ring, c.stage, nb, cudaMemcpyHostToDevice, c.cs) != cudaSuccess ||
8941                cudaStreamSynchronize(c.cs) != cudaSuccess) {
8942                cudaGetLastError();
8943                return;
8944            }
8945            ms = now_ms() - a;
8946        }
8947        pm.dma = (double) nb / std::max(1e-3, ms / 1000.0);
8948        // the readers: RAM -> staging (a buffer of its own, touched first), in as many jobs as they are
8949        auto run_jobs = [&](std::vector<IoQueue::Job>& jobs, std::atomic<int>& left) {
8950            const double a = now_ms();
8951            left.store((int) jobs.size());
8952            c.io->push(jobs.data(), (int) jobs.size());
8953            while (left.load(std::memory_order_acquire) != 0) c.io->wait_any(500);
8954            return now_ms() - a;
8955        };
8956        {
8957            const size_t part = std::min(nb, (size_t) 64 << 20) / 8 / 4096 * 4096;
8958            std::vector<uint8_t> src(part * 8, 1);
8959            std::vector<IoQueue::Job> jobs(8);
8960            std::atomic<int> left{0};
8961            std::atomic<bool> bad{false};
8962            for (int i = 0; i < 8; ++i) {
8963                jobs[(size_t) i].mem = src.data() + (size_t) i * part;
8964                jobs[(size_t) i].dst = c.stage + (size_t) i * part;
8965                jobs[(size_t) i].len = part;
8966                jobs[(size_t) i].left = &left;
8967                jobs[(size_t) i].bad = &bad;
8968            }
8969            run_jobs(jobs, left);
8970            const double t1 = run_jobs(jobs, left), t2 = run_jobs(jobs, left);
8971            pm.copy = (double) (part * 8) / std::max(1e-3, std::min(t1, t2) / 1000.0);
8972        }
8973        // experts not in RAM (none of their sampled pages resident), of the trunk layer with the most CPU-lane ones:
8974        // up to min(8, staging slots) read by the readers as the flow reads them, then 8 others through the CPU lane
8975        // three times (from the disk, then in RAM: the faster of two)
8976        int best = -1, most = 0;
8977        for (int il = 0; il < g.nl; ++il) {
8978            int n = 0;
8979            for (int e = 0; e < L[(size_t) il].n_exp; ++e) n += L[(size_t) il].slot[(size_t) e] < 0;
8980            if (n > most) most = n, best = il;
8981        }
8982        if (best < 0) return;
8983        const Layer& l = L[(size_t) best];
8984        std::vector<int> cold;
8985        const int n_read = std::min(8, c.S), n_cpu = 8;
8986        for (int e = 0; e < l.n_exp && (int) cold.size() < n_read + n_cpu; ++e) {
8987            if (l.slot[(size_t) e] >= 0 || (!l.ram.empty() && l.ram[(size_t) e] >= 0)) continue;
8988            bool res = false;
8989            for (int r = 0; r < 3; ++r) res = res || os::resident_sampled(mx_mat(l, e, r), mx_part_bytes(l, r), 4);
8990            if (!res) cold.push_back(e);
8991        }
8992        if ((int) cold.size() >= n_read + n_cpu) {
8993            std::vector<IoQueue::Job> jobs;
8994            std::atomic<int> left{0};
8995            std::atomic<bool> bad{false};
8996            for (int i = 0; i < n_read; ++i) {
8997                uint8_t* sb = c.stage + (size_t) i * c.stage_stride;
8998                for (int r = 0; r < 3; ++r) {
8999                    IoQueue::Job j;
9000                    const os::fd_t pf = pk.pfds.empty() ? os::kBadFd : pk.pfds[(size_t) l.mx_file[r]];
9001                    j.fd = pf != os::kBadFd ? pf : pk.fds[(size_t) l.mx_file[r]];
9002                    j.dfd = pk.dfds.empty() ? os::kBadFd : pk.dfds[(size_t) l.mx_file[r]];
9003                    j.off = l.mx_off[r] + (uint64_t) cold[(size_t) i] * l.mx_stride[r];
9004                    j.len = mx_part_bytes(l, r);
9005                    j.dst = sb;
9006                    j.left = &left;
9007                    j.bad = &bad;
9008                    j.map = pk.at(l.mx_file[r], j.off);
9009                    jobs.push_back(j);
9010                    sb += flow_region(r);
9011                }
9012            }
9013            const double rd = run_jobs(jobs, left);
9014            if (!bad.load()) pm.disk = (double) n_read * (double) l.blob / std::max(1e-3, rd / 1000.0);
9015        }
9016        {   // the CPU lane: entries of one token (as most of a window's are), from the disk (if any were cold), then RAM
9017            const size_t first = (int) cold.size() >= n_read + n_cpu ? (size_t) n_read : 0;
9018            std::vector<Ent> ents;
9019            for (int i = 0; i < n_cpu; ++i) {
9020                Ent en;
9021                en.e = first + (size_t) i < cold.size() ? cold[first + (size_t) i] : -1;
9022                if (en.e < 0)   // (no cold ones: the first CPU-lane experts, wherever they are)
9023                    for (int e = 0, k = 0; e < l.n_exp && en.e < 0; ++e)
9024                        if (l.slot[(size_t) e] < 0 && k++ == i) en.e = e;
9025                if (en.e < 0) break;
9026                en.n = 1;
9027                en.slot0 = i;
9028                en.tok[0] = 0;
9029                ents.push_back(en);
9030            }
9031            if (ents.empty()) return;
9032            std::vector<float> x((size_t) g.dim);
9033            for (size_t i = 0; i < x.size(); ++i) x[i] = 0.02f * std::sin(0.37f * (float) i);
9034            const double bytes = (double) ents.size() * (double) l.blob;
9035            double a = now_ms();
9036            cpu_experts(l, x.data(), ents, (size_t) g.dim);
9037            const double t_first = now_ms() - a;
9038            double t_warm = 1e30;
9039            for (int rep = 0; rep < 2; ++rep) {
9040                a = now_ms();
9041                cpu_experts(l, x.data(), ents, (size_t) g.dim);
9042                t_warm = std::min(t_warm, now_ms() - a);
9043            }
9044            pm.cpu = bytes / std::max(1e-3, t_warm / 1000.0);
9045            if (first > 0 || (int) cold.size() >= n_cpu) pm.cpu_cold = bytes / std::max(1e-3, t_first / 1000.0);
9046        }
9047        pm.on = pm.dma > 0 && pm.copy > 0 && pm.cpu > 0;
9048        if (o.verbose) {
9049            char dk[32] = "not measured", cc[32] = "not measured";
9050            if (pm.disk > 0) std::snprintf(dk, sizeof dk, "%.2f GB/s", pm.disk / 1e9);
9051            if (pm.cpu_cold > 0) std::snprintf(cc, sizeof cc, "%.2f GB/s", pm.cpu_cold / 1e9);
9052            std::fprintf(stderr,
9053                         "ds4: prompts through the flow or windows by this PC's speeds: DMA %.1f GB/s, RAM to staging "
9054                         "%.1f GB/s, the disk %s; the CPU lane %.1f GB/s in RAM, %s from the disk (%.0f ms)\n",
9055                         pm.dma / 1e9, pm.copy / 1e9, dk, pm.cpu / 1e9, cc, now_ms() - t0);
9056        }
9057    }
9058    // layer l's CPU-lane experts (VRAM holds the rest) and the chance a token picks a given one of them: the profile's
9059    // share of the layer's picks they took, spread evenly over them, times pm.m (what the flow's runs found)
9060    double pm_rate(const Layer& l, int& n_cold) const {
9061        const uint32_t* pr = prof.data() + (size_t) l.il * g.n_exp;
9062        double sum = 0, cold = 0;
9063        n_cold = 0;
9064        for (int e = 0; e < l.n_exp; ++e) {
9065            sum += pr[e];
9066            if (l.slot[(size_t) e] < 0) cold += pr[e], ++n_cold;
9067        }
9068        if (n_cold == 0) return 0.0;
9069        const double share = sum > 0 && cold > 0 ? cold / sum : (double) n_cold / l.n_exp;
9070        return pm.m * (double) l.k_exp * share / n_cold;
9071    }
9072    // the CPU-lane experts n tokens pick in the trunk's layers, expected (each layer's n_cold (1 - e^(-rate n)))
9073    double pm_picks(int n) const {
9074        double d = 0;
9075        for (int il = 0; il < g.nl; ++il) {
9076            int nc = 0;
9077            const double a = pm_rate(L[(size_t) il], nc);
9078            d += nc * (1.0 - std::exp(-a * n));
9079        }
9080        return d;
9081    }
9082    // a run of one chunk of n tokens on the flow picked `picked` CPU-lane experts: pm.m to what makes the expectation
9083    // that (bisection over its log; a running mean of the log)
9084    void pm_learn(int n, double picked) {
9085        if (!pm.on || n < 2 || picked < 1) return;
9086        const double m0 = pm.m;
9087        double lo = std::log(1e-3), hi = std::log(1e3);
9088        for (int it = 0; it < 40; ++it) {
9089            pm.m = std::exp(0.5 * (lo + hi));
9090            (pm_picks(n) < picked ? lo : hi) = 0.5 * (lo + hi);
9091        }
9092        const double obs = 0.5 * (lo + hi);
9093        pm.m = std::exp(pm.n_m == 0 ? obs : 0.7 * std::log(m0) + 0.3 * obs);
9094        ++pm.n_m;
9095    }
9096    // a prompt of n tokens that the flow could take (n >= chunk_min): true the flow, false windows of 16 - each path's
9097    // time predicted from the bytes of CPU-lane experts it would move (the flow: each picked one once, n_cold (1 -
9098    // e^(-rate n)) a layer, pm_rate) or compute (windows: each window's own picks), those in RAM (each layer's share:
9099    // sampled pages of up to 32 of its CPU-lane experts, mincore / QueryWorkingSetEx; the RAM tier's) and those not at
9100    // this PC's speeds - the flow's times what it really took against its predictions so far for prompts of that size
9101    // (pm_k), windows' once some ran what a window took times the windows; the flow unless windows are predicted
9102    // faster (by half, with less than kPickRes in RAM); said with --verbose
9103    // The choice is made from the prompt's length alone (pick_flow_min): the same prompt takes the same path - and so
9104    // gives the same bits, the two paths round differently - in every session and on every restart.  The timing prediction below
9105    // (DS4_PICK=adaptive) used measured speeds and sampled page residency, so it flipped between runs: r9700, one 16-token feed
9106    // through the flow in one run, another feed in the next, three different logits checksums in six runs.  Measured on 4 and 1 R9700
9107    // (first prompt of a run, windows against the flow, ms): 28 tokens 594 / 4966 (4 cards), 1094 / 5588 (1 card); 100: 1164 / 5375,
9108    // 3279 / 7299; 300: 2831 / 5874, 9018 / 9803; 600: 5304 / 6808, 16969 / 11327; 1500: 13325 / 8012, 41547 / 18187 - the flow pays a
9109    // fixed ~5 s the first time (its buffers and GEMM libraries), then wins from about 400 tokens up.
9110    // The length from which the flow is taken: one number for every box (ds4_pick_rule.hpp says why 96), DS4_PICK_MIN=N overrides.
9111    int pick_flow_min() {
9112        if (pick_min_ > 0) return pick_min_;
9113        pick_min_ = prompt_flow_min(std::getenv("DS4_PICK_MIN"));
9114        std::fprintf(stderr, "ds4: prompt path: the chunked pass from %d tokens, windows of 16 below\n", pick_min_);
9115        return pick_min_;
9116    }
9117    int pick_min_ = 0;
9118    bool pick_path(int n) {
9119        static const bool adaptive = [] {
9120            const char* e = std::getenv("DS4_PICK");
9121            return e != nullptr && std::strcmp(e, "adaptive") == 0;
9122        }();
9123        pm.last = -1;
9124        if (!adaptive) return n >= pick_flow_min();
9125        if (!pm.on || n >= kPickMax) return true;
9126        double f_res = 0, f_cold = 0, w = 0;
9127        const int nw = n / kWin, rem = n % kWin;
9128        for (int il = 0; il < g.nl; ++il) {
9129            const Layer& l = L[(size_t) il];
9130            int nc = 0;
9131            const double a = pm_rate(l, nc);
9132            if (nc == 0) continue;
9133            int sampled = 0, res = 0, seen = 0;
9134            const int step = std::max(1, nc / 32);
9135            for (int e = 0; e < l.n_exp; ++e) {
9136                if (l.slot[(size_t) e] >= 0 || seen++ % step != 0) continue;
9137                bool r = !l.ram.empty() && l.ram[(size_t) e] >= 0;
9138                if (!r) {
9139                    r = true;
9140                    for (int p = 0; p < 3 && r; ++p) r = os::resident_sampled(mx_mat(l, e, p), mx_part_bytes(l, p), 2);
9141                }
9142                ++sampled;
9143                res += r;
9144            }
9145            const double share = sampled > 0 ? (double) res / sampled : 0.0, b = (double) l.blob;
9146            auto u = [&](int t) { return nc * (1.0 - std::exp(-a * t)); };
9147            f_res += share * u(n) * b;
9148            f_cold += (1.0 - share) * u(n) * b;
9149            w += ((double) nw * u(kWin) + (rem > 0 ? u(rem) : 0.0)) * b;
9150        }
9151        const double r_fr = std::min(pm.copy, pm.dma), r_fc = pm.disk > 0 ? std::min(pm.disk, pm.dma) : r_fr;
9152        const double r_wc = pm.cpu_cold > 0 ? pm.cpu_cold : 1.0 / (1.0 / r_fc + 1.0 / pm.cpu);
9153        const double t_flow = f_res / r_fr + f_cold / r_fc;
9154        const double t_win = std::max(0.0, w - f_cold) / pm.cpu + f_cold / r_wc;
9155        const int cls = pm_cls(n), n_win = (n + kWin - 1) / kWin;
9156        // (windows: once some ran, what a window took on average times the windows the prompt needs - each pays the
9157        // fixed costs of every layer on every GPU again, which a pass of the flow pays once)
9158        const double pf = pm_k(cls) * t_flow, pw = pm.win_n > 0 ? pm.win_s * n_win : t_win;
9159        // (the flow unless windows are predicted faster - in half its time at least, unless kPickRes of the CPU-lane
9160        // experts' bytes are in RAM: the flow wins on every PC whose experts come from an SSD, where a wrong pick would
9161        // cost the most; windows win where they are all in RAM)
9162        const double res_share = f_res / std::max(1.0, f_res + f_cold);
9163        const bool flow = !(pw < pf && (res_share >= kPickRes || 2.0 * pw <= pf));
9164        pm.last = flow ? 1 : 0;
9165        pm.last_cls = cls;
9166        pm.last_nw = n_win;
9167        pm.last_pred = flow ? t_flow : t_win;
9168        if (o.verbose)
9169            std::fprintf(stderr,
9170                         "ds4: a prompt of %d tokens through %s: predicted %.2f s, %s %.2f s (%.0f%% of its CPU-lane "
9171                         "experts' %.1f GB in RAM)\n",
9172                         n, flow ? "the flow" : "windows", flow ? pf : pw, flow ? "windows" : "the flow", flow ? pw : pf,
9173                         100.0 * res_share, (f_res + f_cold) / 1e9);
9174        return flow;
9175    }
9176    // a prompt's size class for pm.k: 2-31, 32-127, 128-511, 512 tokens and more
9177    static int pm_cls(int n) { return n < 32 ? 0 : n < 128 ? 1 : n < 512 ? 2 : 3; }
9178    // the flow's time factor for size class c: its own, else its nearest class's, else 1 (never the windows': theirs
9179    // is mostly the fixed costs a window pays again and again)
9180    double pm_k(int c) const {
9181        for (int dc = 0; dc < 4; ++dc)
9182            for (int cc : {c - dc, c + dc})
9183                if (cc >= 0 && cc < 4 && pm.kn[0][cc] > 0) return pm.k[0][cc];
9184        return 1.0;
9185    }
9186    // n tokens through windows of 16, the last one's logits_rows rows of logits
9187    bool feed_windows(const int* tokens, int n, int logits_rows, std::string& err) {
9188        logits_all = false;
9189        for (int a = 0; a < n; a += kWin) {
9190            const int T = std::min(kWin, n - a);
9191            if (!forward(tokens + a, T, a + T == n ? logits_rows : 0, err)) return false;
9192        }
9193        return true;
9194    }
9195    // the picked path took ms: the flow's predictions for the prompt's size class scaled by what it really takes (taken
9196    // / predicted), windows' time a window - running means
9197    void path_done(double ms) {
9198        if (pm.last < 0 || pm.last_pred <= 0) return;
9199        if (pm.last == 0) {
9200            const double w = ms / 1000.0 / std::max(1, pm.last_nw);
9201            pm.win_s = pm.win_n == 0 ? w : 0.7 * pm.win_s + 0.3 * w;
9202            ++pm.win_n;
9203        } else {
9204            const double ratio = std::min(8.0, std::max(0.25, ms / 1000.0 / pm.last_pred));
9205            double& k = pm.k[0][pm.last_cls];
9206            int64_t& n = pm.kn[0][pm.last_cls];
9207            k = n == 0 ? ratio : 0.7 * k + 0.3 * ratio;
9208            ++n;
9209        }
9210        pm.last = -1;
9211    }
9212    // a run layer-major? - one device holding every layer on the flow, several chunks, and what the chunks after the
9213    // first would read from the files again more than the chunks' states moved to host memory and back at every layer
9214    // (DS4_LAYER_MAJOR=0: never); then its host memory: the chunks' states (pinned, else pageable) and the layer cache,
9215    // the largest layer's experts read from the files if RAM allows (ram_avail() less kRamMargin; DS4_LAYER_CACHE_MB
9216    // sets it) - at least one expert, or not layer-major
9217    bool lm_begin(const Run& run) {
9218        static const char* env = std::getenv("DS4_LAYER_MAJOR");
9219        if (devs.size() != 1 || run.T.size() < 2 || (env != nullptr && std::atoi(env) == 0)) return false;
9220        Chunk& c = *chunks[0];
9221        if (!c.flow) return false;
9222        size_t need = 0, n_exp = 0, blob_max = 0;
9223        double file_b = 0;
9224        for (int il = 0; il < g.nl; ++il) {
9225            const Layer& l = L[(size_t) il];
9226            size_t ne = 0;
9227            for (int e : l.host_list)
9228                if (l.ram.empty() || l.ram[(size_t) e] < 0) ++ne;
9229            const size_t stride = (l.blob + 63) & ~(size_t) 63;
9230            need = std::max(need, ne * stride);
9231            n_exp = std::max(n_exp, (size_t) l.n_exp);
9232            blob_max = std::max(blob_max, stride);
9233            file_b += (double) ne * (double) l.blob;
9234        }
9235        int64_t rows = 0;
9236        for (int T : run.T) rows += T;
9237        const size_t hb = chunk_hand_bytes(), state_b = run.T.size() * hb;
9238        const double moved = 2.0 * (double) rows * ((double) hb / (double) chunk) * (double) g.nl;
9239        if (need == 0 || (double) (run.T.size() - 1) * file_b <= moved) return false;
9240        size_t lc_bytes = need;
9241        if (const char* mb = std::getenv("DS4_LAYER_CACHE_MB")) lc_bytes = std::min(need, (size_t) std::atoll(mb) << 20);
9242        else {
9243            const uint64_t avail = ram_avail();
9244            if (avail != ~uint64_t{0})
9245                lc_bytes = std::min<uint64_t>(need, avail > kRamMargin + state_b ? avail - kRamMargin - state_b : 0);
9246        }
9247        if (lc_bytes < blob_max) return false;
9248        void* st_p = nullptr;
9249        c.lm_pinned = cudaHostAlloc(&st_p, state_b, cudaHostAllocPortable) == cudaSuccess;
9250        if (!c.lm_pinned) {
9251            cudaGetLastError();
9252            st_p = os::anon_alloc(state_b, -1, 1);
9253            if (st_p == nullptr) return false;
9254        }
9255        c.lc = (uint8_t*) os::anon_alloc(lc_bytes, -1, 1);
9256        if (c.lc == nullptr) {
9257            if (c.lm_pinned) cudaFreeHost(st_p);
9258            else os::anon_free(st_p, state_b);
9259            return false;
9260        }
9261        c.lm_state = (uint8_t*) st_p;
9262        c.lm_state_bytes = state_b;
9263        c.lc_bytes = lc_bytes;
9264        c.lc_of.assign(n_exp, -1);
9265        c.lc_writer.assign(n_exp, -1);
9266        c.lm = true;
9267        lm_layers.store(0);
9268        return true;
9269    }
9270    void lm_end() {
9271        for (size_t di = 0; di < chunks.size(); ++di) {
9272            Chunk& c = *chunks[di];
9273            if (!c.lm) continue;
9274            cudaSetDevice(devs[di].id);
9275            cudaStreamSynchronize(devs[di].st);   // (nothing of the run's still reads or writes them: the device's
9276            cudaStreamSynchronize(c.cs);          // copies done, every read the run issued done - a failed run's too)
9277            for (size_t i = c.base; i < c.n_read; ++i)
9278                while (fit(c, i).left.load(std::memory_order_acquire) != 0) c.io->wait_any(500);
9279            if (c.lm_pinned) cudaFreeHost(c.lm_state);
9280            else os::anon_free(c.lm_state, c.lm_state_bytes);
9281            os::anon_free(c.lc, c.lc_bytes);
9282            c.lm_state = c.lc = nullptr;
9283            c.lm_state_bytes = c.lc_bytes = 0;
9284            c.lm = c.lm_pinned = false;
9285        }
9286    }
9287
9288    // the first layer of a long prompt's second half (forward_chunks' two passes), or -1: the first with compress ratio 1
9289    // (V4.1: 20), every one after it ratio 1 too and owning no compressed KV or index keys of its own (they read its),
9290    // every trunk layer on one GPU.  The settings' MAYA_DS4_PROMPT_SKIP (STRATA_DS4_PROMPT_SKIP; DS4_YOCO for tests):
9291    // 1 (the default) the skip, 2 DeepSeek's own serving's (the last 128 rows only: faster, the answers shift a
9292    // little), 0 off
9293    static int yoco_mode() {
9294        static const int m = [] {
9295            const char* v = std::getenv("DS4_YOCO");
9296            if (v == nullptr) v = std::getenv("STRATA_DS4_PROMPT_SKIP");
9297            return v != nullptr ? std::atoi(v) : 1;
9298        }();
9299        return m;
9300    }
9301    int yoco_layer() const {
9302        if (yoco_mode() == 0 || chunk <= 0 || g.nl < 2 || (int) g.ratios.size() < g.nl) return -1;
9303        int yl = -1;
9304        for (int il = 0; il < g.nl && yl < 0; ++il)
9305            if (g.ratios[(size_t) il] == 1) yl = il;
9306        if (yl <= 0 || !L[(size_t) yl].kv_src) return -1;
9307        for (int il = 0; il < g.nl; ++il) {
9308            const Layer& l = L[(size_t) il];
9309            if (l.nm != 1 || l.dev != L[0].dev) return -1;
9310            if (il > yl && (g.ratios[(size_t) il] != 1 || l.kv_src)) return -1;
9311        }
9312        return yl;
9313    }
9314
9315    // n tokens at positions pos .. in chunks of equal size (at most `chunk`), pipelined over the groups; the logits of
9316    // the last min(logits_rows, 16) rows (logits_rows > 16: a run of one chunk, every row's into chunk_logits)
9317    bool forward_chunks(const int* tk, int n, int logits_rows, std::string& err, int snap_slot = -1) {
9318        if (n < 1) return true;
9319        if (!lend_restore(err)) return false;
9320        settle_if_due();
9321        flow_used.store(true);
9322        std::lock_guard<std::mutex> warm_lk(warm_mu);   // (the warm-up, if it is running, finishes first)
9323        if (pos + n > o.max_context) {
9324            err = "the context is full";
9325            return false;
9326        }
9327        for (int t = 0; t < n; ++t)
9328            if (tk[t] < 0 || tk[t] >= g.vocab) {
9329                err = "token " + std::to_string(tk[t]) + " out of range";
9330                return false;
9331            }
9332        // a long prompt's skip: the layers from yoco_layer() on (V4.1: 20-39) read the earlier positions only through
9333        // that layer's compressed KV and index keys, and each looks back one window (win - 1 positions) more than the
9334        // layer before - so they need their own work only on the last keep = (nl - yoco) (win - 1) + win rows for the
9335        // run's last rows and the rings the decode reads to be what the full work gives (up to the experts' summing
9336        // order).  The chunks stay as they are: the ones before the cut go through the layers before yoco and its
9337        // kv_only, the cut's chunk through those over all its rows and through the rest from the cut on (Run::r0, a
9338        // view of its buffers), the chunks after it through every layer - each layer's experts read as without the
9339        // skip.  One GPU (DS4_YOCO=1; 0: off); not with every row's logits (tests)
9340        const int yl = logits_rows > kWin ? -1 : yoco_layer();
9341        // (DS4_YOCO_KEEP=<rows>: fewer - DeepSeek's own serving replays the last 128 tokens through those layers
9342        //  (DeepInfer's "SWA bounded replay"), which shifts the answers a little; at least one window)
9343        static const int keep_env = std::getenv("DS4_YOCO_KEEP") ? std::atoi(std::getenv("DS4_YOCO_KEEP")) : 0;
9344        const int keep = yl <= 0 ? 0
9345                         : keep_env > 0 ? std::max(keep_env, g.win)
9346                         : yoco_mode() == 2 ? g.win : (g.nl - yl) * (g.win - 1) + g.win;
9347        const int a = yl > 0 && n - keep >= kYocoMin ? n - keep : 0;
9348        const bool lend = lend_min_ > 0 && n >= lend_min_ && logits_rows <= kWin;
9349        const int run_chunk = lend || lend_min_ == 0 ? chunk : chunk_small_;
9350        const int nc = (n + run_chunk - 1) / run_chunk, per = (n + nc - 1) / nc;
9351        Run run;
9352        for (int x = 0; x < n; x += per) {
9353            run.p0.push_back(pos + x);
9354            run.T.push_back(std::min(per, n - x));
9355            run.seq.push_back(++win_seq);
9356        }
9357        if (a > 0) {
9358            run.yoco = yl;
9359            run.cut_k = a / per;
9360            run.cut_r = a - run.cut_k * per;
9361        }
9362        logits_all = logits_rows > kWin;
9363        if (logits_all) chunk_logits.resize((size_t) n * g.vocab);
9364        for (int t = 0; t < n; ++t) {
9365            toks.push_back(tk[t]);
9366            ctoks.push_back(ctok(pos + t, tk[t]));
9367        }
9368        if (lend) lend_begin();
9369        struct LendEnd {   // (every way out: the chunk's own buffers back)
9370            Impl* p;
9371            bool on;
9372            ~LendEnd() {
9373                if (on) p->lend_end_bufs();
9374            }
9375        } lend_end_{this, lend};
9376        plan_streams();
9377        if (snap_slot >= 0) {   // feed_mark: the state before the run's last row, kept by its layers on the way
9378            run.snap_pos = pos + n - 1;
9379            for (int il = 0; il < g.nl; ++il) {
9380                Layer& l = L[(size_t) il];
9381                Dev& d = devs[(size_t) l.dev];
9382                if (l.snap_win == nullptr && !dalloc(d, l.snap_win, (size_t) g.win * win_rb(), err)) return false;
9383                if (l.c_kv != nullptr && l.snap_kv == nullptr &&
9384                    (!dalloc(d, l.snap_kv, (size_t) l.ratio * g.hd, err) || !dalloc(d, l.snap_sc, (size_t) l.ratio * g.hd, err)))
9385                    return false;
9386            }
9387        }
9388        const int T_last = run.T.back();
9389        n_logits = logits_all ? 0 : std::min(logits_rows, T_last);
9390        const double tl = now_ms();
9391        {   // each chunk's end on the head device, for the progress reports
9392            cudaSetDevice(devs[(size_t) head_dev].id);
9393            while (chunk_done.size() < run.T.size()) {
9394                cudaEvent_t e = nullptr;
9395                CK(cudaEventCreateWithFlags(&e, cudaEventDisableTiming));
9396                chunk_done.push_back(e);
9397            }
9398            chunk_rec.reset(new std::atomic<int>[chunk_done.size()]);
9399            for (size_t i = 0; i < chunk_done.size(); ++i) chunk_rec[i].store(0);
9400        }
9401        prof_chunk = prof_on;
9402        const bool lm = lm_begin(run);
9403        struct LmEnd {   // (every way out: its host memory freed once the device is done with it)
9404            Impl* p;
9405            bool on;
9406            ~LmEnd() {
9407                if (on) p->lm_end();
9408            }
9409        } lm_end_{this, lm};
9410        std::vector<std::string> errs(devs.size());
9411        halted = false;
9412        halt.store(false);
9413        {
9414            std::lock_guard<std::mutex> lk(halt_mu);
9415            halt_k = INT_MAX;
9416            halt_seen = -1;
9417        }
9418        bool halting = false;
9419        for (size_t di = 0; di < devs.size(); ++di)
9420            workers[di]->submit([this, di, &run, &errs] {
9421                std::string e;
9422                if (!run_dev_chunks((int) di, run, e)) errs[di] = e.empty() ? "a device's thread failed" : e;
9423            });
9424        size_t reported = 0;
9425        for (;;) {
9426            bool all = true;
9427            for (auto& w : workers) all = all && w->idle();
9428            if (!all && !halting && cancel && cancel()) {   // a Stop: the devices end the run early
9429                halting = true;
9430                std::lock_guard<std::mutex> lk(halt_mu);
9431                halt_k = halt_seen + 1;
9432                halt.store(true, std::memory_order_release);
9433            }
9434            if (progress && lm) {   // (layer-major: the share of the layers every chunk went through)
9435                const int nd = lm_layers.load(std::memory_order_acquire);
9436                if (nd > 0 && nd < g.nl) progress((int64_t) n * nd / g.nl);
9437            } else if (progress) {   // chunks through every layer (the last layer's device past their event)
9438                while (reported < run.T.size() && chunk_rec[reported].load(std::memory_order_acquire) &&
9439                       cudaEventQuery(chunk_done[reported]) == cudaSuccess)
9440                    ++reported;
9441                if (reported > 0 && reported < run.T.size())
9442                    progress(run.p0[reported - 1] + run.T[reported - 1] - run.p0[0]);
9443            }
9444            if (all) break;
9445            std::this_thread::sleep_for(std::chrono::milliseconds(50));
9446        }
9447        for (const std::string& e : errs)   // (a device's failure first: a Stop's early end is not one)
9448            if (!e.empty() && e != kHalted) {
9449                err = e;
9450                return false;
9451            }
9452        for (const std::string& e : errs)
9453            if (e == kHalted) {
9454                halted = true;
9455                err = "stopped while reading the prompt";
9456                return false;
9457            }
9458        st.layer_ms += now_ms() - tl;
9459        eg_stats();
9460        Dev& d = devs[(size_t) head_dev];
9461        cudaSetDevice(d.id);
9462        const double th = now_ms();
9463        CK(cudaStreamSynchronize(d.st));
9464        st.head_ms += now_ms() - th;
9465        if (prof_chunk) {   // DS4_PROF: the run's GPU time by stage, every device's summed
9466            for (Dev& dv : devs) {
9467                cudaSetDevice(dv.id);
9468                CK(cudaStreamSynchronize(dv.st));
9469            }
9470            cudaSetDevice(d.id);
9471            prof_collect();
9472            std::fprintf(stderr,
9473                         "ds4 prompt GPU time, %d tokens: attention %.0f ms, routing + shared expert %.0f ms, experts %.0f ms "
9474                         "(with the waits for streamed ones), between layers %.0f ms\n",
9475                         n, cprof_ms[1], cprof_ms[2], cprof_ms[3], cprof_ms[0]);
9476            {   // the finer table (ms, % of the sum)
9477                static const char* nm_[16] = {"between layers", "attn rest (q_b, wo_a/b, hc_post)", "shared expert", "experts (incl waits)",
9478                                              "engram", "attn mHC (mix/split/norm)", "attn projections", "compressor + indexer",
9479                                              "q_b + rope", "sparse attention", "ffn mHC + router + sort", "", "", "", "", ""};
9480                double sum = 0;
9481                for (double v : cprof_ms) sum += v;
9482                for (int i = 0; i < 11; ++i)
9483                    std::fprintf(stderr, "ds4 prof  %-34s %9.1f ms %5.1f%%\n", nm_[i], cprof_ms[i], sum > 0 ? 100.0 * cprof_ms[i] / sum : 0.0);
9484                struct Agg {
9485                    double ms = 0, flops = 0;
9486                    long calls = 0, rows = 0, experts = 0;
9487                };
9488                std::map<std::pair<int, int>, Agg> agg;   // (type, role 0 gate+up, 1 down)
9489                {
9490                    std::lock_guard<std::mutex> lk(prof_mu);
9491                    for (const EkMark& m : ek_marks) {
9492                        float a = 0, b = 0;
9493                        cudaSetDevice(m.dev);
9494                        cudaEventElapsedTime(&a, m.e0, m.e1);
9495                        cudaEventElapsedTime(&b, m.e1, m.e2);
9496                        Agg& x = agg[{m.tg, 0}];
9497                        x.ms += a;
9498                        x.flops += 2.0 * 2.0 * m.nrows * (double) g.dim * (double) m.ff;
9499                        x.calls++, x.rows += m.nrows, x.experts += m.nexp;
9500                        Agg& y = agg[{m.td, 1}];
9501                        y.ms += b;
9502                        y.flops += 2.0 * m.nrows * (double) g.dim * (double) m.ff;
9503                        y.calls++, y.rows += m.nrows, y.experts += m.nexp;
9504                        ek_pool[m.dev].push_back(m.e0);
9505                        ek_pool[m.dev].push_back(m.e1);
9506                        ek_pool[m.dev].push_back(m.e2);
9507                    }
9508                    ek_marks.clear();
9509                }
9510                double tot = 0;
9511                for (auto& kv : agg) tot += kv.second.ms;
9512                for (auto& kv : agg)
9513                    std::fprintf(stderr,
9514                                 "ds4 prof  expert kernels type %-8s %-7s %9.1f ms  calls %5ld  experts %6ld (%.1f us each, %.1f a call)  rows/expert %6.1f  ~%5.1f TFLOPS\n",
9515                                 gg::iq::name(kv.first.first), kv.first.second ? "down" : "gate+up", kv.second.ms, kv.second.calls,
9516                                 kv.second.experts, kv.second.experts > 0 ? 1e3 * kv.second.ms / (double) kv.second.experts : 0.0,
9517                                 kv.second.calls > 0 ? (double) kv.second.experts / (double) kv.second.calls : 0.0,
9518                                 kv.second.experts > 0 ? (double) kv.second.rows / (double) kv.second.experts : 0.0,
9519                                 kv.second.ms > 0 ? kv.second.flops / kv.second.ms / 1e9 : 0.0);
9520                std::fprintf(stderr, "ds4 prof  expert kernels total %.1f ms\n", tot);
9521            }
9522            for (double& v : cprof_ms) v = 0;
9523            prof_chunk = false;
9524        }
9525        if (o.verbose || std::getenv("DS4_FLOW_STATS") != nullptr) {
9526            const double ms = now_ms() - tl;
9527            for (size_t di = 0; di < chunks.size(); ++di) {
9528                const Chunk& c = *chunks[di];
9529                if (!c.flow) continue;
9530                const double db = (double) (c.io->direct_bytes() - c.io_d0) / 1e9;
9531                const double bb = (double) (c.io->buffered_bytes() - c.io_b0) / 1e9;
9532                const double fb = db + bb, rb = (double) c.it_ram * (double) L[0].blob / 1e9;   // (a member: its parts)
9533                char lcs[160] = "";
9534                if (c.lm)
9535                    std::snprintf(lcs, sizeof lcs, ", %llu again from the layer cache (layer-major, %d chunks, %.1f GB "
9536                                  "of RAM)", (unsigned long long) c.it_lc, (int) run.T.size(), (double) c.lc_bytes / 1e9);
9537                std::fprintf(stderr,
9538                             "ds4 prompt stream, CUDA%d: %d tokens in %.0f ms; %llu experts streamed: %llu from the files "
9539                             "(%.1f GB, %.2f GB/s: %.1f GB from the disk unbuffered, %.1f GB through the page cache), %llu "
9540                             "from RAM (%.1f GB)%s; %llu likely ones queued early, %llu of them unpicked; the compute waited "
9541                             "%.0f ms for reads; reads running %.0f ms, %.1f deep, %llu of them merged into %llu; %llu picks in VRAM\n",
9542                             devs[di].id, n, ms, (unsigned long long) (c.it_file + c.it_ram + c.it_lc),
9543                             (unsigned long long) c.it_file, fb, fb / std::max(1e-3, ms / 1000.0), db, bb,
9544                             (unsigned long long) c.it_ram, rb, lcs, (unsigned long long) c.it_spec,
9545                             (unsigned long long) c.it_spec_unused, c.wait_ms, c.io->any_ms() - c.io_any0,
9546                             (c.io->busy_ms() - c.io_busy0) / std::max(1e-3, c.io->any_ms() - c.io_any0),
9547                             (unsigned long long) (c.io->run_jobs() - c.io_rj0), (unsigned long long) (c.io->runs() - c.io_runs0),
9548                             (unsigned long long) c.it_vram);
9549            }
9550        }
9551        if (pm.on && run.T.size() == 1) {   // (the picks' spread for pick_path: the CPU-lane experts this run picked)
9552            bool tp = false;
9553            for (const Layer& l : L) tp = tp || l.nm > 1;
9554            double picked = 0;
9555            for (const auto& cp : chunks)
9556                if (cp != nullptr && cp->flow) picked += (double) (cp->it_file + cp->it_ram) - (double) cp->it_spec_unused;
9557            if (!tp) pm_learn(n, picked);
9558        }
9559        if (logits_all) n_logits = (T_last - 1) % kWin + 1;   // (sample() takes the last row of d.logits)
9560        pos += n;
9561        st.tokens += n;
9562        if (lent_ && !settle_defer) {   // (the experts back before the first token: the decode starts as it would have)
9563            lend_end_.on = false;
9564            lend_end_bufs();
9565            lend_tick_n_ = n;
9566            if (!lend_restore(err)) return false;
9567        } else if (lent_)
9568            lend_tick_n_ = n;   // (DS4_SETTLE_DEFER: the cache's tick once the experts are back, at the next forward)
9569        else
9570            cache_tick(n);
9571        if (lm_end_.on) {   // (the layer cache's RAM back before the store and the swaps want it)
9572            lm_end();
9573            lm_end_.on = false;
9574        }
9575        if (settle_defer || lent_) settle_due = true;
9576        else cache_settle();
9577        const int nr = std::min(T_last, tap_cap);
9578        if (!seed_drafter(pos - nr, nr, 0, err)) return false;
9579        if (snap_slot >= 0) {   // checkpoint `snap_slot` from what the layers kept (the drafter's blocks: as they are -
9580            // the next feed seeds them again from its own rows, past this position)
9581            Check& ckp = ck[snap_slot & 1];
9582            ckp.pos = run.snap_pos;
9583            ckp.win.resize(L.size());
9584            ckp.comp.resize(L.size() * 2);
9585            for (size_t i = 0; i < L.size(); ++i) {
9586                Layer& l = L[i];
9587                Dev& dv = devs[(size_t) l.dev];
9588                cudaSetDevice(dv.id);
9589                const bool kept = !l.mtp && l.snap_win != nullptr;
9590                ckp.win[i].resize((size_t) g.win * win_rb());
9591                CK(cudaMemcpyAsync(ckp.win[i].data(), kept ? l.snap_win : l.win, ckp.win[i].size(),
9592                                   cudaMemcpyDeviceToHost, dv.st));
9593                if (l.c_kv) {
9594                    ckp.comp[2 * i].resize((size_t) l.ratio * g.hd);
9595                    ckp.comp[2 * i + 1].resize((size_t) l.ratio * g.hd);
9596                    CK(cudaMemcpyAsync(ckp.comp[2 * i].data(), kept && l.snap_kv ? l.snap_kv : l.c_kv,
9597                                       ckp.comp[2 * i].size() * 4, cudaMemcpyDeviceToHost, dv.st));
9598                    CK(cudaMemcpyAsync(ckp.comp[2 * i + 1].data(), kept && l.snap_sc ? l.snap_sc : l.c_score,
9599                                       ckp.comp[2 * i + 1].size() * 4, cudaMemcpyDeviceToHost, dv.st));
9600                }
9601            }
9602            for (Dev& dv : devs) {
9603                cudaSetDevice(dv.id);
9604                CK(cudaStreamSynchronize(dv.st));
9605            }
9606        }
9607        return true;
9608    }
9609
9610    // the window's plan, in window order (the indexer's and the candidate source's sizes carry from window to window)
9611    void plan_window(int64_t p0, int T, WinPlan& wp) {
9612        wp.par = par;
9613        wp.async = par || (!sync_decode && T <= async_max_t);
9614        wp.vl = 0;
9615        for (int t = 0; t < T && !imgs.empty(); ++t)
9616            if (in_image(p0 + t)) wp.vl |= 1u << t;
9617        for (int il = 0; il < g.nl; ++il) {
9618            const Layer& l = L[(size_t) il];
9619            if (l.ratio > 0) {
9620                const int R = l.ratio;
9621                int n[kWin], k[kWin], clen_max = 0;
9622                for (int t = 0; t < T; ++t) {
9623                    n[t] = (int) ((p0 + t + 1) / R);
9624                    k[t] = std::min(g.ix_topk, n[t]);
9625                    clen_max = std::max(clen_max, n[t]);
9626                }
9627                if (l.ix_src) {
9628                    for (int t = 0; t < T; ++t) wp.cand[il][t] = cur_cand_n[t];
9629                    if (clen_max > 0 && l.cand_src)
9630                        for (int t = 0; t < T; ++t) cur_cand_n[t] = std::min(g.cand_topk, (n[t] + g.cand_blk - 1) / g.cand_blk);
9631                    for (int t = 0; t < T; ++t) cur_topk_n[t] = k[t];
9632                }
9633                for (int t = 0; t < T; ++t) wp.topk[il][t] = cur_topk_n[t];
9634            }
9635            if (wp.async) {
9636                wp.seq[il] = ++seq_issued;
9637                layer_of[wp.seq[il] % kRing].store(il, std::memory_order_release);
9638            }
9639        }
9640    }
9641
9642    int head_nm() const { return (int) groups[(size_t) devs[(size_t) head_dev].grp].mem.size(); }
9643    // the head's columns on member mi of its group of nm: an EXL3 head's split128 of the vocabulary (mat's), a GGUF's
9644    // BF16 / Q8_0 head's even shares (mat_bf16's) - head_share's, its gather's and the markov steps' rows
9645    void head_cols(int nm, int mi, int& v0, int& vn) const {
9646        const Tensor* tw = pk.get("head.weight");
9647        if (tw != nullptr && (tw->dtype == "BF16" || tw->dtype == "Q8_0")) {
9648            vn = g.vocab / nm;
9649            v0 = mi * vn;
9650        } else
9651            split128(g.vocab, nm, mi, v0, vn);
9652    }
9653    // the head over `rows` (<= 16) normed rows xn on member mi of the head group (device d): its share of each row's
9654    // logits (columns [v0, v0 + vn), head_cols); the lead gathers the others' into d.logits (rows V apart) - two
9655    // slots by seq (Vmax apart, the widest share's), a member reusing one once the lead acknowledged it.  gather
9656    // false: each member keeps its share (the drafter's markov steps over the group, mk_split)
9657    bool head_share(Dev& d, int mi, const float* xn, int rows, std::string& err, bool gather = true) {
9658        const int V = g.vocab, D = g.dim, nm = head_nm();
9659        int v0 = 0, vn = 0, Vmax = 0, z = 0;
9660        head_cols(nm, mi, v0, vn);
9661        head_cols(nm, 0, z, Vmax);
9662        Group& G = groups[(size_t) d.grp];
9663        float* out = mi == 0 ? d.logits : d.logits_part;
9664        const size_t ld = mi == 0 ? (size_t) V : (size_t) vn;
9665        cudaSetDevice(d.id);
9666        // (an EXL3 head: as many activations at a time as its split-K partials fit the scratch - 8 for a shared head, 4
9667        // for a whole one, each pass reading the whole share; a GGUF's: 4 at a time, as before)
9668        const int per = d.head.fmt != 0 ? 4 : std::max(1, x3::mv_cols(d.head));
9669        for (int c = 0; c < rows; c += per)
9670            if (!mv(d, {job(d.head, xn + (size_t) c * D, out + (size_t) c * ld, std::min(per, rows - c), D, ld)}, err))
9671                return false;
9672        if (nm == 1 || !gather) return true;
9673        const unsigned seq = ++d.head_seq;
9674        const int slot = (int) (seq % 2);
9675        auto stage = [&](int m) { return G.lg_stage + ((size_t) slot * (nm - 1) + (m - 1)) * kWin * Vmax; };
9676        auto flag = [&](int m) { return G.lg_flag + ((size_t) slot * (nm - 1) + (m - 1)) * 32; };
9677        if (mi > 0) {
9678            if (seq > 2) wait_flags(G.lg_ack + (size_t) slot * 32, 1, 32, seq - 2, d.st);
9679            Xfer x;
9680            x.n = 1;
9681            x.src[0] = d.logits_part;
9682            x.dst[0] = stage(mi);
9683            x.bytes[0] = (size_t) rows * vn * 4;
9684            xfer_put(x, flag(mi), seq, d.xcnt, d.st);
9685            return true;
9686        }
9687        for (int m = 1; m < nm; ++m) {
9688            int m0 = 0, mn = 0;
9689            head_cols(nm, m, m0, mn);
9690            Xfer x;
9691            x.n = 1;
9692            x.src[0] = stage(m);
9693            x.dst[0] = d.logits_part;
9694            x.bytes[0] = (size_t) rows * mn * 4;
9695            xfer_get(x, flag(m), seq, d.st);
9696            CK(cudaMemcpy2DAsync(d.logits + (size_t) m0, (size_t) V * 4, d.logits_part, (size_t) mn * 4,
9697                                 (size_t) mn * 4, (size_t) rows, cudaMemcpyDeviceToDevice, d.st));
9698        }
9699        set_flag(G.lg_ack + (size_t) slot * 32, seq, d.st);
9700        return true;
9701    }
9702
9703    // the head's rows (the last n_logits of the window) on head group member di (its h / pre: the group's)
9704    bool head_rows_dev(int di, int T, std::string& err) {
9705        Dev& d = devs[(size_t) di];
9706        cudaSetDevice(d.id);
9707        const int D = g.dim, H = g.hc;
9708        if (n_logits <= 0) return true;
9709        const int t0 = T - n_logits;
9710        hc_pre_norm(d.h + (size_t) t0 * H * D, d.pre + (size_t) t0 * 8, d.norm_w, D, H, n_logits, g.eps, d.x, d.st);
9711        return head_share(d, d.mi, d.x, n_logits, err);
9712    }
9713
9714    // the DSpark drafter's taps: the streams' mean entering target layer il, on device d (after the last seeding read
9715    // h_taps)
9716    bool tap(Dev& d, int il, int T, std::string& err) {
9717        const auto it = std::find(g.d_targets.begin(), g.d_targets.end(), il);
9718        if (g.n_mtp == 0 || it == g.d_targets.end()) return true;
9719        const size_t j = (size_t) (it - g.d_targets.begin()), nt = g.d_targets.size();
9720        const int D = g.dim;
9721        cudaSetDevice(d.id);
9722        hc_mean(d.h, T, g.hc, D, d.tap, D, d.st);
9723        CK(cudaStreamWaitEvent(d.st, ev_seed, 0));
9724        CK(cudaMemcpy2DAsync(h_taps + j * D, nt * D * 4, d.tap, (size_t) D * 4, (size_t) D * 4, (size_t) T,
9725                             cudaMemcpyDeviceToHost, d.st));
9726        return true;
9727    }
9728
9729    bool forward(const int* tk, int T, int logits_rows, std::string& err, int seed_rows = -1) {
9730        if (!lend_restore(err)) return false;
9731        settle_if_due();
9732        if (T < 1 || T > kWin) {
9733            err = "a window of " + std::to_string(T) + " tokens";
9734            return false;
9735        }
9736        if (pos + T > o.max_context) {
9737            err = "the context is full";
9738            return false;
9739        }
9740        for (int t = 0; t < T; ++t)
9741            if (tk[t] < 0 || tk[t] >= g.vocab) {
9742                err = "token " + std::to_string(tk[t]) + " out of range";
9743                return false;
9744            }
9745        const int64_t p0 = pos;
9746        slot_held = false;   // (the state grows now: what slot_save took is no longer the conversation)
9747        for (int t = 0; t < T; ++t) {
9748            toks.push_back(tk[t]);
9749            ctoks.push_back(ctok(pos + t, tk[t]));
9750        }
9751        // the Engram rows asked for now (the first Engram layer's first), collected right before their layer: what is
9752        // left of their reads by then is the window's Engram time
9753        const double te = now_ms();
9754        const int64_t eg_w0 = eg_wait_ns.load();
9755        for (int li = 0; li < pk.eg_layers; ++li) {
9756            EgBatch& b = *eg_win[(size_t) li];
9757            if (b.live) eg_finish(b);   // (a window that failed midway: its reads end before h_eg is reused)
9758            eg_issue(p0, T, li, nullptr, b);
9759        }
9760        st.engram_ms += now_ms() - te;
9761        const int D = g.dim;
9762        for (int t = 0; t < T; ++t)   // (h_emb is written again by the next window, after this one's last sync)
9763            std::memcpy(h_emb + (size_t) t * D, emb_row(p0 + t, tk[t]), (size_t) D * 2);
9764        plan_window(p0, T, wplan);
9765        prof_window = prof_on && T == 1;
9766        n_logits = std::min(logits_rows, T);
9767        const double tl = now_ms();
9768        if (par) {
9769            if (!forward_par(p0, T, err)) return false;
9770        } else if (!forward_serial(p0, T, err)) return false;
9771        st.layer_ms += now_ms() - tl;
9772        for (auto& b : eg_win)
9773            if (b->live) eg_finish(*b);
9774        st.engram_ms += (double) (eg_wait_ns.load() - eg_w0) / 1e6;
9775        eg_stats();
9776        Dev& d = devs[(size_t) head_dev];
9777        cudaSetDevice(d.id);
9778        const double th = now_ms();
9779        CK(cudaStreamSynchronize(d.st));
9780        st.head_ms += now_ms() - th;
9781        prof_collect();
9782        pos += T;
9783        st.tokens += T;
9784        cache_tick(T);
9785        if (seed_rows != 0 && !seed_drafter(p0, seed_rows < 0 ? T : seed_rows, 0, err)) return false;
9786        return true;
9787    }
9788
9789    // one thread: the layers device after device, the hand-offs through pinned memory and events
9790    bool forward_serial(int64_t p0, int T, std::string& err) {
9791        const int D = g.dim, H = g.hc;
9792        int cur = L[0].dev;
9793        {
9794            Dev& d = devs[(size_t) cur];
9795            cudaSetDevice(d.id);
9796            CK(cudaMemcpyAsync(d.emb_rows, h_emb, (size_t) T * D * 2, cudaMemcpyHostToDevice, d.st));
9797            embed(d.emb_rows, T, d.h, D, H, d.st);
9798            init_pre(d.pre, T, d.st);
9799        }
9800        std::vector<float> dump;
9801        if (dump_h != nullptr) dump.resize((size_t) T * g.nl * H * D);
9802        for (int il = 0; il < g.nl; ++il) {
9803            Layer& l = L[(size_t) il];
9804            if (l.dev != cur) {
9805                Dev& a = devs[(size_t) cur];
9806                Dev& b = devs[(size_t) l.dev];
9807                cudaSetDevice(a.id);
9808                const size_t nh = (size_t) T * H * D * 4, np = (size_t) T * 8 * 4, nk = (size_t) T * topk_stride() * 4,
9809                             nc = (size_t) T * cand_stride() * 4;
9810                uint8_t* bb = a.bounce;
9811                CK(cudaMemcpyAsync(bb, a.h, nh, cudaMemcpyDeviceToHost, a.st));
9812                CK(cudaMemcpyAsync(bb + nh, a.pre, np, cudaMemcpyDeviceToHost, a.st));
9813                CK(cudaMemcpyAsync(bb + nh + np, a.topk, nk, cudaMemcpyDeviceToHost, a.st));
9814                CK(cudaMemcpyAsync(bb + nh + np + nk, a.cand, nc, cudaMemcpyDeviceToHost, a.st));
9815                CK(cudaEventRecord(a.ev_out, a.st));
9816                cudaSetDevice(b.id);
9817                CK(cudaStreamWaitEvent(b.st, a.ev_out, 0));
9818                CK(cudaMemcpyAsync(b.h, bb, nh, cudaMemcpyHostToDevice, b.st));
9819                CK(cudaMemcpyAsync(b.pre, bb + nh, np, cudaMemcpyHostToDevice, b.st));
9820                CK(cudaMemcpyAsync(b.topk, bb + nh + np, nk, cudaMemcpyHostToDevice, b.st));
9821                CK(cudaMemcpyAsync(b.cand, bb + nh + np + nk, nc, cudaMemcpyHostToDevice, b.st));
9822                cur = l.dev;
9823            }
9824            if (!tap(devs[(size_t) l.dev], il, T, err)) return false;
9825            if (!layer(l, 0, p0, T, wplan, err)) return false;
9826            if (dump_h != nullptr) {   // DS4_DUMP_H: every layer's residual stream, for tools/ds4/compare.py --layers
9827                Dev& dd = devs[(size_t) l.dev];
9828                std::vector<float> hv((size_t) T * H * D);
9829                cudaSetDevice(dd.id);
9830                CK(cudaMemcpyAsync(hv.data(), dd.h, hv.size() * 4, cudaMemcpyDeviceToHost, dd.st));
9831                CK(cudaStreamSynchronize(dd.st));
9832                for (int t = 0; t < T; ++t)
9833                    std::memcpy(dump.data() + ((size_t) t * g.nl + l.il) * H * D, hv.data() + (size_t) t * H * D,
9834                                (size_t) H * D * 4);
9835            }
9836        }
9837        if (dump_h != nullptr) std::fwrite(dump.data(), 4, dump.size(), dump_h);
9838        if (cur != head_dev) {
9839            err = "the head is not on the last layer's GPU";
9840            return false;
9841        }
9842        return head_rows_dev(head_dev, T, err);
9843    }
9844
9845    // threads: each device's thread enqueues its layers (a group's members each their share) at once, the
9846    // devices waiting on each other through host-mapped flags (the window's seq)
9847    bool forward_par(int64_t p0, int T, std::string& err) {
9848        wplan.win = ++win_seq;
9849        std::vector<std::string> errs(devs.size());
9850        for (size_t di = 0; di < devs.size(); ++di)
9851            workers[di]->submit([this, di, p0, T, &errs] {
9852                std::string e;
9853                if (!run_dev((int) di, p0, T, wplan, e)) errs[di] = e.empty() ? "a device's thread failed" : e;
9854            });
9855        for (auto& w : workers) w->wait();
9856        for (const std::string& e : errs)
9857            if (!e.empty()) {
9858                err = e;
9859                return false;
9860            }
9861        return true;
9862    }
9863
9864    // the hand-off between groups: h | pre | topk | cand of device d <-> the host-mapped buffer
9865    Xfer hand_xfer(uint8_t* host, Dev& d, int T, bool put) const {
9866        const size_t nh = (size_t) T * g.hc * g.dim * 4, np = (size_t) T * 8 * 4, nk = (size_t) T * topk_stride() * 4,
9867                     nc = (size_t) T * cand_stride() * 4;
9868        void* dv[4] = {d.h, d.pre, d.topk, d.cand};
9869        uint8_t* hv[4] = {host, host + nh, host + nh + np, host + nh + np + nk};
9870        const size_t nb[4] = {nh, np, nk, nc};
9871        Xfer x;
9872        x.n = 4;
9873        for (int i = 0; i < 4; ++i) {
9874            x.src[i] = put ? (const void*) dv[i] : (const void*) hv[i];
9875            x.dst[i] = put ? (void*) hv[i] : dv[i];
9876            x.bytes[i] = nb[i];
9877        }
9878        return x;
9879    }
9880
9881    bool run_dev(int di, int64_t p0, int T, const WinPlan& wp, std::string& err) {
9882        Dev& d = devs[(size_t) di];
9883        cudaSetDevice(d.id);
9884        cudaStream_t s = d.st;
9885        const int D = g.dim, H = g.hc;
9886        bool started = false;
9887        std::vector<char> got(srcs.size(), 0);
9888        for (int il = 0; il < g.nl; ++il) {
9889            Layer& L0 = L[(size_t) il];
9890            int mi = -1;
9891            for (int m = 0; m < L0.nm; ++m)
9892                if (member(L0, m).dev == di) mi = m;
9893            if (mi < 0) continue;
9894            if (!started) {   // the window's input: the embedding rows, or the previous group's hand-off
9895                started = true;
9896                if (il == 0) {
9897                    CK(cudaMemcpyAsync(d.emb_rows, h_emb, (size_t) T * D * 2, cudaMemcpyHostToDevice, s));
9898                    embed(d.emb_rows, T, d.h, D, H, s);
9899                    init_pre(d.pre, T, s);
9900                } else {
9901                    const Dev& a = devs[(size_t) L[(size_t) il - 1].dev];
9902                    xfer_get(hand_xfer(a.hand, d, T, false), a.hand_flag, wp.win, s);
9903                }
9904            }
9905            // the compressed KV / index keys another group's source layer wrote this window
9906            for (int sidx : {L0.src, L0.ix_src ? L0.ik_src : -1}) {
9907                if (sidx < 0 || got[(size_t) sidx]) continue;
9908                got[(size_t) sidx] = 1;
9909                Src& sr = srcs[(size_t) sidx];
9910                if (L[(size_t) sr.layer].grp == L0.grp) continue;
9911                const int64_t g_first = p0 / sr.ratio;
9912                const int ng = (int) std::max<int64_t>(0, (p0 + T) / sr.ratio - g_first);
9913                if (ng == 0) continue;
9914                Xfer x;
9915                if (sr.ckv[(size_t) di] != nullptr) {
9916                    x.src[x.n] = sr.x_stage;
9917                    x.dst[x.n] = sr.ckv[(size_t) di] + (size_t) g_first * ckv_rb();
9918                    x.bytes[x.n++] = (size_t) ng * ckv_rb();
9919                }
9920                if (sr.ik[(size_t) di] != nullptr) {
9921                    x.src[x.n] = sr.x_stage + x_cap() * ckv_rb();
9922                    x.dst[x.n] = sr.ik[(size_t) di] + (size_t) g_first * ik_rb();
9923                    x.bytes[x.n++] = (size_t) ng * ik_rb();
9924                }
9925                if (x.n > 0) xfer_get(x, sr.x_flag, wp.win, s);
9926            }
9927            if (mi == 0 && !tap(d, il, T, err)) return false;
9928            if (!layer(L0, mi, p0, T, wp, err)) return false;
9929            if (dump_l != nullptr && mi == 0) dump_layer(d, d.h, il, p0, T);
9930            const bool last = il + 1 == g.nl || L[(size_t) il + 1].grp != L0.grp;
9931            if (last && mi == 0 && il + 1 < g.nl) xfer_put(hand_xfer(d.hand, d, T, true), d.hand_flag, wp.win, d.xcnt, s);
9932        }
9933        if (d.grp == devs[(size_t) head_dev].grp) return head_rows_dev(di, T, err);
9934        return true;
9935    }
9936
9937    // a source's new cache rows (src on device `from`, bytes of them) to the same place of its other devices' copies,
9938    // through pinned memory: the copy out on the source's stream, each copy in on its device's stream after it
9939    bool replicate(std::vector<uint8_t*>& copies, uint8_t* stage, cudaEvent_t ev, const uint8_t* src, size_t at,
9940                   size_t bytes, int from, std::string& err) {
9941        bool any = false;
9942        for (size_t od = 0; od < devs.size(); ++od) any = any || (copies[od] != nullptr && (int) od != from);
9943        if (!any) return true;
9944        Dev& d = devs[(size_t) from];
9945        CK(cudaMemcpyAsync(stage, src, bytes, cudaMemcpyDeviceToHost, d.st));
9946        CK(cudaEventRecord(ev, d.st));
9947        for (size_t od = 0; od < devs.size(); ++od) {
9948            if (copies[od] == nullptr || (int) od == from) continue;
9949            Dev& o2 = devs[od];
9950            cudaSetDevice(o2.id);
9951            CK(cudaStreamWaitEvent(o2.st, ev, 0));
9952            CK(cudaMemcpyAsync(copies[od] + at, stage, bytes, cudaMemcpyHostToDevice, o2.st));
9953        }
9954        cudaSetDevice(d.id);
9955        return true;
9956    }
9957
9958    // layer L0 for the window, as group member mi (its share of the heads, of the output projection and of the FFNs;
9959    // the partial sums all-reduced across the group)
9960    bool layer(Layer& L0, int mi, int64_t p0, int T, const WinPlan& wp, std::string& err) {
9961        Layer& l = member(L0, mi);
9962        Dev& d = devs[(size_t) l.dev];
9963        cudaSetDevice(d.id);
9964        cudaStream_t s = d.st;
9965        const int nm = L0.nm;
9966        const int D = g.dim, H = g.hc, HD = g.hd, NHL = l.ahn, HQ = NHL * HD, OG = l.ogn, FF = l.ffn;
9967        const ArGroup& ag = groups[(size_t) L0.grp].ar;
9968        const float* freqs = l.ratio ? d.freqs_comp : d.freqs_win;
9969        prof_mark(d, 0);
9970        // Engram
9971        if (l.eg >= 0) {
9972            const int cols = (pk.eg_ngram - 1) * pk.eg_heads, ehd = pk.eg_hd;
9973            const size_t per = (size_t) cols * (ehd + ehd / 32);
9974            eg_finish(*eg_win[(size_t) l.eg]);   // (asked for when the window began)
9975            uint8_t* src = h_eg + (size_t) l.eg * eg_cap * per;
9976            for (int t = 0; t < T; ++t)   // [token][rows | scales] -> [all rows][all scales]
9977                CK(cudaMemcpyAsync(d.eg_rows + (size_t) t * cols * ehd, src + (size_t) t * per, (size_t) cols * ehd,
9978                                   cudaMemcpyHostToDevice, s));
9979            uint8_t* sc = d.eg_rows + (size_t) T * cols * ehd;
9980            for (int t = 0; t < T; ++t)
9981                CK(cudaMemcpyAsync(sc + (size_t) t * cols * (ehd / 32), src + (size_t) t * per + (size_t) cols * ehd,
9982                                   (size_t) cols * (ehd / 32), cudaMemcpyHostToDevice, s));
9983            engram_dequant(d.eg_rows, sc, T * cols, ehd, d.eg_x, s, (int) eg_fmt[(size_t) l.eg]);
9984            if (!mv(d, {job(l.eg_wkv, d.eg_x, d.eg_kv, T, (size_t) cols * ehd, (size_t) (H + 1) * D)}, err)) return false;
9985            engram_gate(d.h, d.eg_kv, l.eg_w, H, D, T, g.eps, s);
9986        }
9987        // attention
9988        hc_mix_split(d.h, l.hca_fn, H * D, (2 + H) * H, T, g.eps, d.mix, d.hccnt, l.hca_scale, l.hca_base, H, g.sinkhorn, g.hc_eps,
9989                     d.a_pre, d.a_post, d.a_comb, s);
9990        hc_pre_norm(d.h, d.pre, l.attn_norm, D, H, T, g.eps, d.x, s);
9991        {
9992            x3::MvJob j[4];
9993            int nj = 0;
9994            j[nj++] = job(l.wq_a, d.x, d.qr, T, D, g.q_lora);
9995            j[nj++] = job(l.wkv, d.x, d.kvr, T, D, HD);
9996            if (l.kv_src) j[nj++] = job(l.c_wkv, d.x, d.ckr, T, D, HD);
9997            if (l.kv_src && l.ratio > 1) j[nj++] = job(l.c_wgate, d.x, d.cgr, T, D, HD);
9998            if (!mv_n(d, j, nj, err)) return false;
9999        }
10000        Finish fq;
10001        fq.w = l.q_norm;
10002        fq.eps = g.eps;
10003        finish(d.qr, T, g.q_lora, g.q_lora, fq, s);
10004        if (NHL > 0) {
10005            if (!mv(d, {job(l.wq_b, d.qr, d.q, T, g.q_lora, HQ)}, err)) return false;
10006            Finish fr;
10007            fr.rd = g.rd;
10008            fr.pos = (int) p0;
10009            fr.vpp = NHL;
10010            fr.freqs = freqs;
10011            finish(d.q, T * NHL, HD, HD, fr, s);
10012        }
10013        // the window rows: the ring's (positions p0 - win ..) then this window's, each query its own 128.  A DSpark
10014        // block's ring holds the trunk's main KV (positions <= p0 - 1, seeded); its block of drafts attends to all of
10015        // that ring and to the whole block, and leaves the ring as it was
10016        ring_to_ext(l.win, d.ext, l.mtp ? (int64_t) g.win : p0, g.win, HD, s);   // (a block's ring: its rows as they lie)
10017        Finish fk;
10018        fk.w = l.kv_norm;
10019        fk.eps = g.eps;
10020        fk.rd = g.rd;
10021        fk.pos = (int) p0;
10022        fk.freqs = freqs;
10023        fk.quant = 1;
10024        fk.dst = d.ext + (size_t) g.win * HD;
10025        fk.dst_stride = HD;
10026        finish(d.kvr, T, HD, HD, fk, s);
10027        if (!l.mtp) ext_to_ring(d.ext, l.win, p0, g.win, T, HD, s, spec_win ? l.ring_bak : nullptr);
10028        AttnRows ar;
10029        for (int t = 0; t < T; ++t) {
10030            if (l.mtp) {
10031                ar.win0[t] = 0;
10032                ar.nwin[t] = (int) std::min<int64_t>(g.win, p0);
10033                ar.nsel[t] = T;
10034                continue;
10035            }
10036            const int64_t band_first = scr_band_start >= 0 ? g.win + scr_band_start - p0 : 0;
10037            // During bounded replay, ignore ring rows preceding the replay segment.
10038            const int first = (int) std::max<int64_t>(std::max<int64_t>(g.win - p0, t + 1), band_first);
10039            ar.win0[t] = first;
10040            ar.nwin[t] = g.win + t - first + 1;
10041            ar.nsel[t] = 0;
10042        }
10043        const void* ckv = nullptr;
10044        int ckv_fmt = kKvFp4;
10045        if (l.ratio > 0) {
10046            Src& sr = srcs[(size_t) l.src];
10047            const int R = l.ratio;
10048            // the groups this window completes: g_first .. g_first + ng - 1
10049            const int64_t g_first = p0 / R;              // the first group whose last position is >= p0
10050            const int64_t g_end = (p0 + T) / R;          // groups completed by p0 + T - 1
10051            const int ng = (int) std::max<int64_t>(0, g_end - g_first);
10052            if (l.kv_src) {
10053                if (R == 1) {
10054                    Finish fc;
10055                    fc.w = l.c_norm;
10056                    fc.eps = g.eps;
10057                    finish(d.ckr, T, HD, HD, fc, s);
10058                    CK(cudaMemcpyAsync(d.latent, d.ckr, (size_t) T * HD * 4, cudaMemcpyDeviceToDevice, s));
10059                } else {
10060                    if (spec_win && l.c_snap != nullptr) {   // to replay the accepted rows if drafts are rejected
10061                        const size_t ns = (size_t) R * HD * 4, nr = (size_t) T * HD * 4;
10062                        CK(cudaMemcpyAsync(l.c_snap, l.c_kv, ns, cudaMemcpyDeviceToDevice, s));
10063                        CK(cudaMemcpyAsync(l.c_snap + (size_t) R * HD, l.c_score, ns, cudaMemcpyDeviceToDevice, s));
10064                        CK(cudaMemcpyAsync(l.c_rows, d.ckr, nr, cudaMemcpyDeviceToDevice, s));
10065                        CK(cudaMemcpyAsync(l.c_rows + (size_t) kWin * HD, d.cgr, nr, cudaMemcpyDeviceToDevice, s));
10066                    }
10067                    compress_win(d.ckr, d.cgr, l.c_kv, l.c_score, R, (int) p0, T, HD, l.c_norm, g.eps, d.latent, s);
10068                }
10069            }
10070            Rows lim;
10071            int clen_max = 0;
10072            for (int t = 0; t < T; ++t) {
10073                lim.n[t] = (int) ((p0 + t + 1) / R);
10074                lim.k[t] = std::min(g.ix_topk, lim.n[t]);
10075                clen_max = std::max(clen_max, lim.n[t]);
10076            }
10077            if (l.ix_src) {
10078                Src& ks = srcs[(size_t) l.ik_src];
10079                if (l.owns_k && ng > 0) {
10080                    if (!mv(d, {job(l.i_wk, d.latent, d.ikr, ng, HD, g.ix_hd)}, err)) return false;
10081                    Finish fi;
10082                    fi.w = l.ik_norm;
10083                    fi.eps = g.eps;
10084                    fi.rd = g.rd;
10085                    fi.pos = (int) (g_first * R);
10086                    fi.pos_step = R;
10087                    fi.freqs = freqs;
10088                    fi.quant = 3;
10089                    fi.pdst = ks.ik[(size_t) l.dev] + (size_t) g_first * ik_rb();
10090                    fi.pdst_stride = (long long) ik_rb();
10091                    if (scr_master) { fi.master = ks.master_ik[(size_t) l.dev] + (size_t) g_first * g.rd; fi.master_stride = g.rd; fi.master_valid = ks.master_ik_valid[(size_t) l.dev] + g_first; }
10092                    finish(d.ikr, ng, g.ix_hd, g.ix_hd, fi, s);
10093                    if (!wp.par && !replicate(ks.ik, ks.h_ik, ks.ev_ik, fi.pdst, (size_t) g_first * ik_rb(),
10094                                              (size_t) ng * ik_rb(), l.dev, err))
10095                        return false;
10096                }
10097                if (clen_max > 0) {
10098                    if (!mv(d, {job(l.i_wq_b, d.qr, d.iq, T, g.q_lora, (size_t) g.ix_heads * g.ix_hd)}, err)) return false;
10099                    Finish fi;
10100                    fi.rd = g.rd;
10101                    fi.pos = (int) p0;
10102                    fi.vpp = g.ix_heads;
10103                    fi.freqs = freqs;
10104                    fi.quant = 3;
10105                    finish(d.iq, T * g.ix_heads, g.ix_hd, g.ix_hd, fi, s);
10106                    // (iw rows are 64 apart)
10107                    gemv_f16_rows(l.i_wproj, d.x, (size_t) D, g.ix_heads, D, T,
10108                                  1.0f / std::sqrt((float) g.ix_hd) / std::sqrt((float) g.ix_heads), d.iw, 64, s);
10109                    const long long ss = (long long) o.max_context + 64;
10110                    bool restrict_ = false;
10111                    for (int t = 0; t < T; ++t)
10112                        restrict_ = restrict_ || (lim.n[t] + g.cand_blk - 1) / g.cand_blk > g.cand_topk;
10113                    if (l.uses_cand && restrict_) {
10114                        Rows cl;   // the candidate positions of each query: its blocks x blk
10115                        int nmax = 0;
10116                        for (int t = 0; t < T; ++t) {
10117                            cl.n[t] = lim.n[t];
10118                            cl.k[t] = wp.cand[l.il][t];
10119                            nmax = std::max(nmax, wp.cand[l.il][t] * g.cand_blk);
10120                        }
10121                        index_score(d.iq, d.iw, ks.ik[(size_t) l.dev], g.ix_heads, g.ix_hd, T, nmax, d.cand,
10122                                    (int) cand_stride(), g.cand_blk, cl, d.scores, ss, s);
10123                        Rows tr;
10124                        for (int t = 0; t < T; ++t) {
10125                            tr.n[t] = wp.cand[l.il][t] * g.cand_blk;
10126                            tr.k[t] = lim.k[t];
10127                        }
10128                        topk(d.scores, ss, T, tr, d.cand, (int) cand_stride(), g.cand_blk, d.topk, (int) topk_stride(), s);
10129                    } else {
10130                        index_score(d.iq, d.iw, ks.ik[(size_t) l.dev], g.ix_heads, g.ix_hd, T, clen_max, nullptr, 0, 1,
10131                                    lim, d.scores, ss, s);
10132                        if (l.cand_src) {
10133                            Rows cr;
10134                            for (int t = 0; t < T; ++t) {
10135                                cr.n[t] = lim.n[t];
10136                                cr.k[t] = g.cand_topk;
10137                            }
10138                            cand_blocks(d.scores, ss, T, cr, g.cand_blk, d.bm, (long long) bm_stride(), d.cand,
10139                                        (int) cand_stride(), s);
10140                        }
10141                        topk(d.scores, ss, T, lim, nullptr, 0, 1, d.topk, (int) topk_stride(), s);
10142                    }
10143                }
10144            }
10145            if (l.kv_src && ng > 0) {
10146                Finish fc;
10147                fc.rd = g.rd;
10148                fc.pos = (int) (g_first * R);
10149                fc.pos_step = R;
10150                fc.freqs = freqs;
10151                fc.quant = 2;
10152                fc.pdst = sr.ckv[(size_t) l.dev] + (size_t) g_first * ckv_rb();
10153                fc.pdst_stride = (long long) ckv_rb();
10154                if (scr_master) { fc.master = sr.master[(size_t) l.dev] + (size_t) g_first * g.rd; fc.master_stride = g.rd; fc.master_valid = sr.master_valid[(size_t) l.dev] + g_first; }
10155                finish(d.latent, ng, HD, HD, fc, s);
10156                if (!wp.par && !replicate(sr.ckv, sr.h_ckv, sr.ev_ckv, fc.pdst, (size_t) g_first * ckv_rb(),
10157                                          (size_t) ng * ckv_rb(), l.dev, err))
10158                    return false;
10159                if (wp.par && mi == 0 && sr.remote) {   // the new rows for the other groups' readers
10160                    Xfer x;
10161                    x.src[0] = fc.pdst;
10162                    x.dst[0] = sr.x_stage;
10163                    x.bytes[0] = (size_t) ng * ckv_rb();
10164                    x.n = 1;
10165                    if (l.owns_k && srcs[(size_t) l.ik_src].ik[(size_t) l.dev] != nullptr) {
10166                        x.src[1] = srcs[(size_t) l.ik_src].ik[(size_t) l.dev] + (size_t) g_first * ik_rb();
10167                        x.dst[1] = sr.x_stage + x_cap() * ckv_rb();
10168                        x.bytes[1] = (size_t) ng * ik_rb();
10169                        x.n = 2;
10170                    }
10171                    xfer_put(x, sr.x_flag, wp.win, d.xcnt, s);
10172                }
10173            }
10174            for (int t = 0; t < T; ++t) ar.nsel[t] = lim.n[t] > 0 ? wp.topk[l.il][t] : 0;
10175            ckv = sr.ckv[(size_t) l.dev];
10176        }
10177        if (l.mtp) {   // the block's rows (BF16), after the ring's in ext, as every query's selection
10178            ckv = d.ext + (size_t) g.win * HD;
10179            ckv_fmt = kKvBf16;
10180            iota_rows(d.topk, T, T, (int) topk_stride(), s);
10181        }
10182        if (NHL > 0) {
10183            sparse_attn(d.q, d.ext, ckv, d.topk, (int) topk_stride(), ar, l.sink, NHL, HD, T,
10184                        1.0f / std::sqrt((float) HD), d.o, s, ckv_fmt, 0, &d.attn_scr);
10185            Finish fo;
10186            fo.rd = g.rd;
10187            fo.pos = (int) p0;
10188            fo.vpp = NHL;
10189            fo.freqs = freqs;
10190            fo.inverse = 1;
10191            fo.quant = 1;
10192            finish(d.o, T * NHL, HD, HD, fo, s);
10193            x3::MvJob j[16];
10194            const int per = HQ / OG;
10195            for (int gi = 0; gi < OG; ++gi)
10196                j[gi] = job(l.wo_a[gi], d.o + (size_t) gi * per, d.oa + (size_t) gi * g.o_lora, T, HQ, (size_t) OG * g.o_lora);
10197            if (!mv_n(d, j, OG, err)) return false;
10198            if (!mv(d, {job(l.wo_b, d.oa, d.ao, T, (size_t) OG * g.o_lora, D)}, err)) return false;
10199        } else CK(cudaMemsetAsync(d.ao, 0, (size_t) T * D * sizeof(*d.ao), s));   // (no heads: nothing to add)
10200        if (nm > 1) allreduce(d.ao, T * D, ag, mi, ++d.ar_seq, d.xcnt, s);
10201        hc_post(d.ao, d.h, d.a_post, d.a_comb, D, H, T, d.h2, s);
10202        std::swap(d.h, d.h2);
10203        if (dump_l != nullptr && mi == 0) dump_layer(d, d.h, 1000 + l.il, p0, T);   // (DS4_DUMP_L: after the attention)
10204        prof_mark(d, 1);
10205        // the MoE
10206        hc_mix_split(d.h, l.hcf_fn, H * D, (2 + H) * H, T, g.eps, d.mix, d.hccnt, l.hcf_scale, l.hcf_base, H, g.sinkhorn, g.hc_eps,
10207                     d.f_pre, d.f_post, d.f_comb, s);
10208        hc_pre_norm(d.h, d.a_pre, l.ffn_norm, D, H, T, g.eps, d.x, s);
10209        if (wp.async) {
10210            // the routing goes to the service thread through the mailbox (a group's lead publishes it, the members
10211            // make the same plan) while the device runs the shared expert and the VRAM experts (from the plan the
10212            // router made), and waits for the answer only before the experts' sum
10213            gemv_f32(l.gate_w, d.x, l.n_exp, D, T, d.glog, 1024, s);
10214            const unsigned sq = wp.seq[l.il];
10215            const int slot = (int) (sq % kRing);
10216            const bool lead = mi == 0;
10217            int na[2] = {0, 0};   // lookahead: the next layers' guesses (their gate on this FFN input), published below
10218            for (int a = 1; lead && a <= std::min(2, ahead_mode); ++a) {
10219                const Layer* nx = ahead_layer(L0, a);
10220                if (nx == nullptr) break;
10221                const int m = a == 1 ? std::max(1, std::min(kAhead1, nx->k_exp + ahead_extra)) : std::min(kPicks, nx->k_exp);
10222                float* gl = d.glog_a + (size_t) (a - 1) * kWin * 1024;
10223                gemv_f32(nx->gate_w, d.x, nx->n_exp, D, T, gl, 1024, s);   // (normed with the next layer's FFN
10224                                                                         // weights instead: the same hit rate)
10225                if (a == 1 && ahead_adapter(l) && l.ad_r > 0)
10226                    lowrank_add(d.x, D, T, l.ad_U, l.ad_V, l.ad_r, nx->n_exp, gl, 1024, ad_tmp(d, l.ad_r), s);
10227                route_ahead(gl, nx->gate_bias, nx->n_exp, m, T, reqs + slot, (a - 1) * kAhead1, s);
10228                na[a - 1] = m;
10229            }
10230            route_publish(d.glog, l.gate_bias, l.n_exp, l.k_exp, T, g.route_scale, l.vram_tab, d.x, D, d.ridx, d.rw,
10231                          d.plan_ptr, lead ? reqs + slot : nullptr, sq, s, l.gate_bias_vl, l.mtp ? 0u : wp.vl, na[0],
10232                          na[1], l.res_tab);
10233            if (!mv(d, {job(l.s1, d.x, d.sg, T, D, FF), job(l.s3, d.x, d.su, T, D, FF)}, err)) return false;
10234            swiglu(d.sg, d.su, T * FF, g.lim, d.sh, s);
10235            if (!mv(d, {job(l.s2, d.sh, d.sh_out, T, FF, D)}, err)) return false;
10236            prof_mark(d, 2);
10237            const x3::ExpertLayout& lay = nm > 1 ? l.hlay : l.lay;
10238            if (T == 1 && moe_token_path) {
10239                x3::MoeArgs ma;
10240                ma.plan_ptr = d.plan_ptr;
10241                ma.plan_w = d.rw;
10242                ma.cpu_part = lead ? resps[slot].part[0] : nullptr;
10243                ma.cpu_flag = lead ? &resps[slot].cpu[0] : nullptr;
10244                ma.lay = lay;
10245                ma.k = l.k_exp;
10246                ma.n_embd = D;
10247                ma.n_ff = FF;
10248                ma.limit = g.lim;
10249                const bool mx = lay.fmt == gg::kFmtMXFP4;
10250                if (zc_stage_buf != nullptr && l.zc_tab != nullptr)   // (the store's experts copied to VRAM at the PCIe rate first)
10251                    zc_stage(d.plan_ptr, d.ridx, l.zc_tab, l.k_exp, zc_stage_buf, zc_stride, l.blob, s);
10252                if (mx) gg::moe_gate_up(ma, d.x, d.xg, s);
10253                else x3::moe_gate_up(ma, d.x, d.xg, s);
10254                prof_mark(d, 3);
10255                if (lead) wait_seq(&resps[slot].seq, sq, s);
10256                prof_mark(d, 4);
10257                if (mx) gg::moe_down(ma, d.xg, d.sh_out, d.moe_out, s);
10258                else x3::moe_down(ma, d.xg, d.sh_out, d.moe_out, s);
10259            } else {   // each distinct expert read once for the window's tokens
10260                gf::MoeWin mw;
10261                mw.plan_ptr = d.plan_ptr;
10262                mw.T = T;
10263                mw.k = l.k_exp;
10264                mw.grp_ptr = d.grp_ptr;
10265                mw.grp_start = d.grp_start;
10266                mw.grp_ent = d.grp_ent;
10267                mw.n_groups = d.n_groups;
10268                gf::moe_win_group(mw, s);
10269                x3::WinArgs wa;
10270                wa.grp_ptr = d.grp_ptr;
10271                wa.grp_start = d.grp_start;
10272                wa.grp_ent = d.grp_ent;
10273                wa.n_groups = d.n_groups;
10274                wa.plan_ptr = d.plan_ptr;
10275                wa.plan_w = d.rw;
10276                wa.cpu_part = lead ? &resps[slot].part[0][0] : nullptr;
10277                wa.cpu_stride = kMaxDim;
10278                wa.cpu_flag = lead ? resps[slot].cpu : nullptr;
10279                wa.wait_ptr = lead ? &resps[slot].seq : nullptr;
10280                wa.wait_val = sq;
10281                wa.x = d.x;
10282                wa.x_stride = (size_t) D;
10283                wa.h = d.xg;
10284                wa.part = d.ed;
10285                wa.sh_out = d.sh_out;
10286                wa.out = d.moe_out;
10287                wa.out_stride = (size_t) D;
10288                wa.lay = lay;
10289                wa.T = T;
10290                wa.k = l.k_exp;
10291                wa.n_embd = D;
10292                wa.n_ff = FF;
10293                wa.limit = g.lim;
10294                if (!(lay.fmt == gg::kFmtMXFP4 ? gg::win_experts(wa, s) : x3::win_experts(wa, s))) {
10295                    err = "exl3 win_experts failed";
10296                    return false;
10297                }
10298            }
10299            if (lead) st.experts += (int64_t) T * l.k_exp;
10300            if (nm > 1) allreduce(d.moe_out, T * D, ag, mi, ++d.ar_seq, d.xcnt, s);
10301            hc_post(d.moe_out, d.h, d.f_post, d.f_comb, D, H, T, d.h2, s);
10302            std::swap(d.h, d.h2);
10303            CK(cudaMemcpyAsync(d.pre, d.f_pre, (size_t) T * 8 * 4, cudaMemcpyDeviceToDevice, s));
10304            prof_mark(d, 5);
10305            return true;
10306        }
10307        if (nm > 1) {
10308            err = "a tensor-parallel layer on the host-routed path";
10309            return false;
10310        }
10311        // (glog rows are 1024 apart: route reads them so)
10312        gemv_f32(l.gate_w, d.x, l.n_exp, D, T, d.glog, 1024, s);
10313        VlBits vb = {};
10314        vb.w[0] = l.mtp ? 0u : wp.vl;
10315        route(d.glog, l.gate_bias, l.n_exp, l.k_exp, T, g.route_scale, d.ridx, d.rw, s, l.gate_bias_vl,
10316              vb.w[0] != 0 ? &vb : nullptr);
10317        CK(cudaMemcpyAsync(h_idx, d.ridx, (size_t) T * kPicks * 4, cudaMemcpyDeviceToHost, s));
10318        CK(cudaMemcpyAsync(h_w, d.rw, (size_t) T * kPicks * 4, cudaMemcpyDeviceToHost, s));
10319        CK(cudaMemcpyAsync(h_x, d.x, (size_t) T * D * 4, cudaMemcpyDeviceToHost, s));
10320        CK(cudaEventRecord(d.ev, s));
10321        // the shared expert while the host looks at the picks
10322        if (!mv(d, {job(l.s1, d.x, d.sg, T, D, g.ff), job(l.s3, d.x, d.su, T, D, g.ff)}, err)) return false;
10323        swiglu(d.sg, d.su, T * g.ff, g.lim, d.sh, s);
10324        if (!mv(d, {job(l.s2, d.sh, d.sh_out, T, g.ff, D)}, err)) return false;
10325        const double tw = now_ms();
10326        CK(cudaEventSynchronize(d.ev));
10327        st.gpu_wait_ms += now_ms() - tw;
10328        // the picks by expert: the VRAM ones' rows (gathered inputs, one GEMV per matrix for all their tokens), the
10329        // CPU lane's entries
10330        Combine cm;
10331        Gather ga;
10332        uint32_t* pr = prof.data() + (size_t) l.il * g.n_exp;
10333        int vex[kWin * kPicks], vrow0[kWin * kPicks], vn[kWin * kPicks];
10334        int nvex = 0, nrows = 0;
10335        std::vector<Ent> ents;
10336        std::vector<std::pair<int, float>> cpu_rows;   // slot -> (token, weight)
10337        std::vector<std::vector<std::pair<int, int>>> per((size_t) l.n_exp);   // expert -> (token, pick)
10338        for (int t = 0; t < T; ++t) {
10339            cm.n[t] = 0;
10340            cm.cpu[t] = 0;
10341            for (int i = 0; i < l.k_exp; ++i) {
10342                const int e = h_idx[t * kPicks + i];
10343                if (e < 0 || e >= l.n_exp) {
10344                    err = "router picked expert " + std::to_string(e);
10345                    return false;
10346                }
10347                ++pr[e];
10348                l.heat[(size_t) e] += 1.0f;
10349                if (l.slot[(size_t) e] < 0) l.cpu_hits.push_back(e);
10350                per[(size_t) e].push_back({t, i});
10351            }
10352        }
10353        int nslots = 0;
10354        for (int e = 0; e < l.n_exp; ++e) {
10355            const auto& pe = per[(size_t) e];
10356            if (pe.empty()) continue;
10357            if (l.slot[(size_t) e] >= 0) {
10358                vex[nvex] = e;
10359                vrow0[nvex] = nrows;
10360                vn[nvex] = (int) pe.size();
10361                for (const auto& tp : pe) {
10362                    ga.src[nrows] = tp.first;
10363                    const int t = tp.first;
10364                    cm.row[t][cm.n[t]] = nrows;
10365                    cm.w[t][cm.n[t]] = h_w[t * kPicks + tp.second];
10366                    ++cm.n[t];
10367                    ++nrows;
10368                }
10369                ++nvex;
10370            } else {
10371                for (size_t a = 0; a < pe.size(); a += (size_t) ent_cap(l)) {
10372                    Ent en;
10373                    en.e = e;
10374                    en.slot0 = nslots;
10375                    en.n = (int) std::min<size_t>((size_t) ent_cap(l), pe.size() - a);
10376                    for (int i = 0; i < en.n; ++i) {
10377                        en.tok[i] = pe[a + (size_t) i].first;
10378                        cpu_rows.push_back({pe[a + (size_t) i].first, h_w[pe[a + (size_t) i].first * kPicks + pe[a + (size_t) i].second]});
10379                        cm.cpu[en.tok[i]] = 1;
10380                    }
10381                    nslots += en.n;
10382                    ents.push_back(en);
10383                }
10384            }
10385        }
10386        st.experts += (int64_t) T * l.k_exp;
10387        st.cpu_experts += nslots;
10388        if (nrows > 0) {
10389            gather_rows(d.x, ga, nrows, D, d.xe, s);
10390            x3::MvJob j[2 * kWin * kPicks];
10391            int nj = 0;
10392            for (int i = 0; i < nvex; ++i) {
10393                const auto& vm = l.vm[(size_t) vex[i]];
10394                j[nj++] = job(vm[0], d.xe + (size_t) vrow0[i] * D, d.xg + (size_t) vrow0[i] * g.ff, vn[i], D, g.ff);
10395                j[nj++] = job(vm[1], d.xe + (size_t) vrow0[i] * D, d.xu + (size_t) vrow0[i] * g.ff, vn[i], D, g.ff);
10396            }
10397            if (!mv_n(d, j, nj, err)) return false;
10398            swiglu(d.xg, d.xu, nrows * g.ff, g.lim, d.xhh, s);
10399            nj = 0;
10400            for (int i = 0; i < nvex; ++i)
10401                j[nj++] = job(l.vm[(size_t) vex[i]][2], d.xhh + (size_t) vrow0[i] * g.ff, d.ed + (size_t) vrow0[i] * D,
10402                              vn[i], g.ff, D);
10403            if (!mv_n(d, j, nj, err)) return false;
10404        }
10405        if (!ents.empty()) {
10406            const double tc = now_ms();
10407            cpu_experts(l, h_x, ents);
10408            std::fill(h_part, h_part + (size_t) T * D, 0.0f);
10409            for (int sl = 0; sl < nslots; ++sl) {
10410                float* o = h_part + (size_t) cpu_rows[(size_t) sl].first * D;
10411                const float wv = cpu_rows[(size_t) sl].second;
10412                const float* y = c_yd.data() + (size_t) sl * D;
10413                for (int e = 0; e < D; ++e) o[e] += wv * y[e];
10414            }
10415            st.cpu_ms += now_ms() - tc;
10416            CK(cudaMemcpyAsync(d.cpu_part, h_part, (size_t) T * D * 4, cudaMemcpyHostToDevice, s));
10417        }
10418        combine(d.ed, ents.empty() ? nullptr : d.cpu_part, d.sh_out, cm, T, D, d.moe_out, s);
10419        hc_post(d.moe_out, d.h, d.f_post, d.f_comb, D, H, T, d.h2, s);
10420        std::swap(d.h, d.h2);
10421        CK(cudaMemcpyAsync(d.pre, d.f_pre, (size_t) T * 8 * 4, cudaMemcpyDeviceToDevice, s));
10422        // (h_part / h_x are written again only after the next layer's route has synchronized, which follows these)
10423        return true;
10424    }
10425
10426    int sample(float temperature, float top_p, int top_k, float min_p, uint64_t seed, uint64_t counter) {
10427        Dev& d = devs[(size_t) head_dev];
10428        cudaSetDevice(d.id);
10429        strata::dsv41k::SamplerParams sp;
10430        sp.temperature = temperature;
10431        sp.greedy = temperature <= 0.0f;
10432        sp.top_p = top_p;
10433        sp.top_k = top_k;
10434        sp.min_p = min_p;
10435        sp.seed = seed;
10436        sp.counter = counter;
10437        strata::dsv41k::sample_tokens(d.logits + (size_t) std::max(0, n_logits - 1) * g.vocab, 1, g.vocab, nullptr, 0,
10438                                       sp, d.tok, d.st);
10439        int t = -1;
10440        cudaMemcpyAsync(&t, d.tok, 4, cudaMemcpyDeviceToHost, d.st);
10441        cudaStreamSynchronize(d.st);
10442        return t;
10443    }
10444
10445    bool logits(std::vector<float>& out) {
10446        if (logits_all) {
10447            out = chunk_logits;
10448            return true;
10449        }
10450        Dev& d = devs[(size_t) head_dev];
10451        cudaSetDevice(d.id);
10452        out.resize((size_t) std::max(1, n_logits) * g.vocab);
10453        return cudaMemcpy(out.data(), d.logits, out.size() * 4, cudaMemcpyDeviceToHost) == cudaSuccess;
10454    }
10455
10456    void save_profile() const {
10457        if (o.profile.empty()) return;
10458        const std::string tmp = o.profile + ".tmp";
10459        std::FILE* f = std::fopen(tmp.c_str(), "wb");
10460        if (f == nullptr) return;
10461        const bool ok = std::fwrite(prof.data(), 4, prof.size(), f) == prof.size();
10462        std::fclose(f);
10463        // (the old profile replaced: std::rename does not replace an existing file on Windows, so there the profile
10464        // never moved on and only .tmp files were left)
10465        if (!ok || !os::replace_file(tmp, o.profile)) std::remove(tmp.c_str());
10466    }
10467
10468    std::vector<std::string> info_lines() const {
10469        std::vector<std::string> v;
10470        int nh = 0;
10471        for (const Layer& l : L) nh += l.n_exp - l.n_vram;
10472        char b[512];
10473        // kv=fp4: DeepSeek's own cache layout (the compressed KV and the index keys FP4, the window FP8)
10474        std::snprintf(b, sizeof b, "INFO context=%lld kv=fp4 kv_resident=%lld expert_slots=%d engine_kind=ds4 "
10475                                   "cpu_experts=%d ram_experts=%d engine=ds4-0.1",
10476                      (long long) o.max_context, (long long) o.max_context, g.nl * g.n_exp - nh, nh, ram_held);
10477        v.push_back(b);
10478        if (commit_kept > 0) {   // (Windows, an integrated GPU: the commit kept experts off the GPU - the server says so)
10479            std::snprintf(b, sizeof b,
10480                          "NOTE experts: %.0f GB stay off the GPU - Windows' page file is too small to hold them there; "
10481                          "a page file of %.0f GB keeps them on the GPU (System > About > Advanced system settings > "
10482                          "Performance > Advanced > Virtual memory), then restart Maya", commit_kept / 1e9, pagefile_hint);
10483            v.push_back(b);
10484            std::snprintf(b, sizeof b, "INFO gpu_commit_capped_gb=%.0f pagefile_hint_gb=%.0f", std::ceil(commit_kept / 1e9),
10485                          pagefile_hint);
10486            v.push_back(b);
10487        }
10488        if (pk.eg_layers > 0) {   // the n-gram memory's (Engram's) table rows a token reads, for the Monitor
10489            std::snprintf(b, sizeof b, "INFO engram_layers=%d engram_lookups=%d", pk.eg_layers,
10490                          pk.eg_layers * (pk.eg_ngram - 1) * pk.eg_heads);
10491            v.push_back(b);
10492        }
10493        if (img_tok >= 0) {   // the server's image resize (DeepSeek's image_processor.py)
10494            std::snprintf(b, sizeof b,
10495                          "INFO vision=ds4 vision_patch=%d vision_merge=%d vision_min_pixels=%lld vision_max_tokens=%d "
10496                          "vision_max_wh_ratio=%lld image_token=%d vision_gpu=%d vision_mib=%lld",
10497                          vg.patch, vg.merge, (long long) pk.num("vision.min_pixels", 0), vg.max_tokens,
10498                          (long long) pk.num("vision.max_wh_ratio", 0), img_tok, vt.device(),
10499                          (long long) (vt.device_bytes() >> 20));
10500            v.push_back(b);
10501        } else if (!vision_err.empty()) {   // (the server offers no pictures and says why)
10502            std::string why = vision_err;
10503            for (char& ch : why)
10504                if (ch == '\n' || ch == '\r') ch = ' ';
10505            v.push_back("NOTE images: OFF - the model's vision tower did not load (" + why + ")");
10506            v.push_back("INFO vision=off");
10507        }
10508        return v;
10509    }
10510};
10511
10512Model::Model() : p_(new Impl) {}
10513Model::~Model() = default;
10514bool Model::load(const Options& o, std::string& err) { return p_->load(o, err); }
10515bool Model::step(int token, bool logits, std::string& err) { return p_->step(token, logits, err); }
10516bool Model::feed(const int* tokens, int n, int logits_rows, std::string& err) {
10517    Impl& p = *p_;
10518    p.pm.last = -1;
10519    p.halted = false;
10520    if (p.chunk > 0 && n >= p.chunk_min) {   // a long run - or one the flow could take, if it is the faster path here
10521        const double t0 = now_ms();   // (every row's logits (tests): the chunked path, which keeps them all)
10522        const bool ok = logits_rows > kWin || p.pick_path(n) ? p.forward_chunks(tokens, n, logits_rows, err)
10523                                                             : p.feed_windows(tokens, n, logits_rows, err);
10524        if (ok) p.path_done(now_ms() - t0);
10525        return ok;
10526    }
10527    return p.feed_windows(tokens, n, logits_rows, err);
10528}
10529bool Model::feed_mark(const int* tokens, int n, int logits_rows, int slot, std::string& err) {
10530    Impl& p = *p_;
10531    p.pm.last = -1;
10532    p.halted = false;
10533    const double t0 = now_ms();
10534    if (n >= 2 && p.chunk > 0 && n >= p.chunk_min && p.pick_path(n)) {   // (the last token rides along; its layers
10535        const bool ok = p.forward_chunks(tokens, n, logits_rows, err, slot);   // keep the state before it)
10536        if (ok) p.path_done(now_ms() - t0);
10537        return ok;
10538    }
10539    if (n > 1 && !p.feed_windows(tokens, n - 1, 0, err)) return false;
10540    p.checkpoint(slot);
10541    const bool ok = n < 1 || p.feed_windows(tokens + n - 1, 1, logits_rows, err);
10542    if (ok) p.path_done(now_ms() - t0);   // (windows, when pick_path chose them)
10543    return ok;
10544}
10545int Model::feed_unit() const { return p_->chunk > 0 ? std::max(p_->chunk, (int) p_->o.max_context) : kWin; }
10546void Model::set_progress(std::function<void(int64_t)> f) { p_->progress = std::move(f); }
10547void Model::set_cancel(std::function<bool()> f) { p_->cancel = std::move(f); }
10548bool Model::cancelled() const { return p_->halted; }
10549int Model::sample(float t, float tp, int tk, float mp, uint64_t seed, uint64_t counter) {
10550    return p_->sample(t, tp, tk, mp, seed, counter);
10551}
10552bool Model::logits(std::vector<float>& out) { return p_->logits(out); }
10553int Model::image_token() const { return p_->img_tok; }
10554int Model::dim() const { return p_->g.dim; }
10555bool Model::encode_image(const uint8_t* rgb, int width, int height, std::vector<uint16_t>& span, std::string& err) {
10556    return p_->encode_image(rgb, width, height, span, err);
10557}
10558void Model::mark_images(const std::vector<std::pair<int64_t, int64_t>>& spans) {
10559    for (const auto& s : spans)
10560        for (int64_t p = std::max<int64_t>(0, s.first); p < s.first + s.second && p < (int64_t) p_->ctoks.size(); ++p)
10561            if (p_->toks[(size_t) p] == p_->img_tok) p_->ctoks[(size_t) p] = -1;
10562}
10563void Model::set_images(std::vector<Image> images) {
10564    std::sort(images.begin(), images.end(), [](const Image& a, const Image& b) { return a.start < b.start; });
10565    p_->imgs = std::move(images);
10566}
10567int Model::draft_block() const { return p_->g.n_mtp > 0 ? p_->g.d_block : 0; }
10568bool Model::draft(int y, std::vector<int>& d, std::vector<float>& c, std::string& err, float t, float tp, int tk,
10569                  float mp, uint64_t seed, uint64_t counter) {
10570    return p_->draft(y, d, c, err, t, tp, tk, mp, seed, counter);
10571}
10572bool Model::verify(int y, const std::vector<int>& d, float t, float tp, int tk, float mp, uint64_t seed, uint64_t counter,
10573                   int& accepted, int& next, std::string& err) {
10574    return p_->verify(y, d, t, tp, tk, mp, seed, counter, accepted, next, err);
10575}
10576int64_t Model::pos() const { return p_->pos; }
10577int64_t Model::max_context() const { return p_->o.max_context; }
10578int Model::vocab() const { return p_->g.vocab; }
10579const std::vector<int32_t>& Model::tokens() const { return p_->toks; }
10580int Model::scr_relocate(const std::vector<ScrMove>& moves, std::string& err) { return p_->scr_relocate(moves, err); }
10581bool Model::scr_jump(const std::vector<int>& ids, int64_t at, std::string& err, int64_t keep) {
10582    return p_->scr_jump(ids, at, err, keep);
10583}
10584void Model::reset() { p_->reset(); }
10585void Model::checkpoint(int slot) { p_->checkpoint(slot); }
10586bool Model::restore(int64_t limit) { return p_->restore(limit); }
10587void Model::pin() { p_->pin(); }
10588std::vector<int64_t> Model::check_positions() const { return p_->check_positions(); }
10589int64_t Model::restorable(int64_t limit) const { return p_->restorable(limit); }
10590uint64_t Model::slot_save(std::vector<uint8_t>& out, std::string& err) { return p_->slot_save(out, err); }
10591bool Model::slot_load(const uint8_t* data, size_t bytes, int64_t n_pos, std::string& err) {
10592    return p_->slot_load(data, bytes, n_pos, err);
10593}
10594std::string Model::slot_identity() const { return p_->slot_identity(); }
10595void Model::save_profile() const { p_->save_profile(); }
10596void Model::tier_dump(const std::string& path) const { p_->tier_dump(path); }
10597const Stats& Model::stats() const {
10598    Stats& st = p_->st;
10599    if (p_->store) {   // (the store keeps its own counters: copied in when asked)
10600        const ExpertStore& x = *p_->store;
10601        st.store_hits = x.stats().hits.load();
10602        st.store_misses = x.stats().misses.load();
10603        st.store_prefetched = x.stats().prefetched.load();
10604        st.store_pf_used = x.stats().prefetch_used.load();
10605        st.store_pf_wasted = x.stats().prefetch_wasted.load();
10606        st.store_evictions = x.stats().evictions.load();
10607        st.store_bytes = x.stats().bytes_read.load();
10608        st.store_fails = x.stats().fails.load();
10609        st.store_wait_ms = x.stats().wait_ns.load() / 1e6;
10610        st.store_busy_ms = x.busy_ms();
10611        st.store_zc_visible = (int64_t) x.visible_count();
10612        st.store_slots = (int64_t) x.slots_allocated();
10613        st.store_slots_max = (int64_t) x.slots_max();
10614    }
10615    return st;
10616}
10617std::string Model::describe() const { return p_->describe(); }
10618std::vector<std::string> Model::info_lines() const { return p_->info_lines(); }
10619
10620}  // namespace strata::ds4