okami.mom/strata

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

Niko1221Merge f-q4-metal (ed1f58d27): the Mac (Metal) engine follows the compiled geometry (q4_lite/q4_mid/q4_big kernel parity 40/40, gate 2 like CUDA), plus the PLE row-buffer fix in src/program/generate.cpp (sized by the compiled hidden size, not 2560; it overran 24 KB at hidden 4096 and crashed Metal serve); default build unchanged (CUDA SASS 3573/3573 and 160/160 host objects, HIP gfx1201/gfx1151 string offsets only, SYCL 129/129 objects and 22/22 checksums, Metal per-token functions identical, UD-Q4_K_XL 10/10 tokens, CUDA IQ3_S 26/26 tokens) (Qwen4 prep)7f46672a4

main
38.5 KiB827 linesraw
1// metal/src/engine/stream.cpp - see stream.h.
2#include "geo.h"
3#include "stream.h"
4
5#include "ref_quant.h"
6#include "arena_budget.h"
7
8#include <sys/sysctl.h>
9
10#include <fcntl.h>
11#include <sys/mman.h>
12#include <sys/stat.h>
13#include <unistd.h>
14
15#include <algorithm>
16#include <chrono>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <map>
21
22namespace strata::metal_engine {
23
24namespace {
25constexpr int NL = strata_metal::geo::NL, NE = 512;   // layers of the compiled shape (engine/geo.h); NE: the row stride of the per-layer maps (the largest expert count)
26constexpr uint64_t PAGE = 16384;
27double now_ms() { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
28int env_int(const char* n, int d) {
29    const char* e = std::getenv(n);
30    return e && *e ? std::atoi(e) : d;
31}
32}  // namespace
33
34bool ExpertStream::wanted(const gguf::File& f, const mtl::Context& cx) {
35    const char* e = std::getenv("STRATA_METAL_STREAM");
36    if (e && std::string(e) == "1") return true;
37    if (e && std::string(e) == "0") return false;
38    // auto: stream when the mapped weights (experts and dense) and ~12 GiB beside them (the prompt buffers, KV, the
39    // draft layer, macOS) do not fit the resident footprint cap: the GPU working set, or on a big Mac the RAM less the
40    // 30% macOS and its file cache keep (arena_budget.h: footprint_cap).  M5 Max (115.4 GB working set, 96.2 GB cap):
41    // GSQ packs, IQ3_S and UD-Q4_K_XL stay resident, UD-Q5/Q6_K_XL stream; M4 32 GB (26.8 GB): every pack streams.
42    uint64_t all = 0;
43    for (const auto& kv : f.tensors)
44        if (kv.first != "per_layer_token_embd.weight") all += kv.second.bytes;
45    uint64_t phys = 0;
46    size_t len = sizeof phys;
47    sysctlbyname("hw.memsize", &phys, &len, nullptr, 0);
48    return !resident_fits((double) phys, (double) cx.recommended_working_set(), (double) all, 12.0 * (1ull << 30));
49}
50
51ExpertStream::~ExpertStream() {
52    {
53        std::lock_guard<std::mutex> g(mu_);
54        stop_ = true;
55    }
56    cv_.notify_all();
57    for (auto& t : io_) t.join();
58    if (fd_ >= 0) ::close(fd_);
59}
60
61bool ExpertStream::open(const gguf::File& f, std::string& err) {
62    fd_ = ::open(f.path.c_str(), O_RDONLY);
63    if (fd_ < 0) { err = "metal stream: cannot open " + f.path; return false; }
64    fcntl(fd_, F_NOCACHE, 1);
65    fcntl(fd_, F_RDAHEAD, 0);
66    lay_.resize(NL);
67    if (const gguf::Tensor* g0 = f.find("blk.0.ffn_gate_exps.weight"); g0 && g0->shape.size() >= 3 && g0->shape[2] > 0 && g0->shape[2] <= NE)
68        ne_ = (int) g0->shape[2];
69    for (int l = 0; l < NL; ++l) {
70        const std::string b = "blk." + std::to_string(l) + ".";
71        const gguf::Tensor* g = f.find(b + "ffn_gate_exps.weight");
72        const gguf::Tensor* u = f.find(b + "ffn_up_exps.weight");
73        const gguf::Tensor* d = f.find(b + "ffn_down_exps.weight");
74        if (!g || !u || !d) { err = "metal stream: layer " + std::to_string(l) + " has no routed experts"; return false; }
75        lay_[(size_t) l] = {g->offset, g->bytes / ne_, u->offset, u->bytes / ne_, d->offset, d->bytes / ne_, -1};
76    }
77    // the expert-contiguous copy beside the GGUF, when it is this GGUF's (sizes in its header) and its first and
78    // last experts match the GGUF's bytes
79    if (env_int("STRATA_METAL_CONTIG", 1) != 0) {
80        const std::string cp = f.path + ".experts";
81        const int cfd = ::open(cp.c_str(), O_RDONLY);
82        bool ok = cfd >= 0;
83        std::vector<uint64_t> off(NL);
84        if (ok) {
85            uint8_t h[64];
86            std::vector<uint64_t> t((size_t) NL * 4);
87            struct stat st {};
88            ::fstat(fd_, &st);
89            ok = ::pread(cfd, h, 64, 0) == 64 && std::memcmp(h, "STRX", 4) == 0 &&
90                 ::pread(cfd, t.data(), t.size() * 8, 64) == (ssize_t) (t.size() * 8);
91            uint32_t ver = 0, nl = 0, ne = 0;
92            uint64_t src = 0;
93            std::memcpy(&ver, h + 4, 4); std::memcpy(&nl, h + 8, 4); std::memcpy(&ne, h + 12, 4); std::memcpy(&src, h + 16, 8);
94            ok = ok && ver == 1 && nl == (uint32_t) NL && ne == (uint32_t) ne_ && src == (uint64_t) st.st_size;
95            for (int l = 0; ok && l < NL; ++l) {
96                const Lay& x = lay_[(size_t) l];
97                ok = t[(size_t) l * 4 + 1] == x.gs && t[(size_t) l * 4 + 2] == x.us && t[(size_t) l * 4 + 3] == x.ds;
98                off[(size_t) l] = t[(size_t) l * 4];
99            }
100            if (ok) {   // spot check: layer 0's first and layer 47's last expert, every slice
101                for (const int l : {0, NL - 1}) {
102                    const Lay& x = lay_[(size_t) l];
103                    const int e = l == 0 ? 0 : ne_ - 1;
104                    std::vector<uint8_t> a(x.gs + x.us + x.ds), b(a.size());
105                    ok = ok && ::pread(cfd, a.data(), a.size(), (off_t) (off[(size_t) l] + (uint64_t) e * a.size())) == (ssize_t) a.size() &&
106                         ::pread(fd_, b.data(), x.gs, (off_t) (x.g + (uint64_t) e * x.gs)) == (ssize_t) x.gs &&
107                         ::pread(fd_, b.data() + x.gs, x.us, (off_t) (x.u + (uint64_t) e * x.us)) == (ssize_t) x.us &&
108                         ::pread(fd_, b.data() + x.gs + x.us, x.ds, (off_t) (x.d + (uint64_t) e * x.ds)) == (ssize_t) x.ds &&
109                         a == b;
110                }
111            }
112        }
113        if (ok) {
114            fcntl(cfd, F_NOCACHE, 1);
115            fcntl(cfd, F_RDAHEAD, 0);
116            cfd_ = cfd;
117            coff_ = off;
118            std::fprintf(stderr, "strata metal stream: experts read from %s (one request per expert)\n", cp.c_str());
119        } else if (cfd >= 0) {
120            ::close(cfd);
121            std::fprintf(stderr, "strata metal stream: %s is not this GGUF's (sizes or bytes differ): the GGUF is read\n",
122                         cp.c_str());
123        }
124    }
125    // size classes: one LRU pool per class.  The layers' slot sizes (9 in the IQ3_XXS mix) are merged into a few
126    // classes, each as big as its largest member, so that no member wastes more than STRATA_METAL_CLASS_WASTE (default
127    // 0.15) of its slot: every class must hold a whole layer's experts for a prompt chunk, so fewer classes = less
128    // memory tied up in those minimums.
129    {
130        const char* ew = std::getenv("STRATA_METAL_CLASS_WASTE");
131        const double waste = ew ? std::atof(ew) : 0.15;
132        std::vector<uint64_t> pages_of(NL);
133        std::vector<uint64_t> sizes;
134        for (int l = 0; l < NL; ++l) {
135            const Lay& x = lay_[(size_t) l];
136            pages_of[(size_t) l] = (x.gs + x.us + x.ds + PAGE - 1) / PAGE;
137            sizes.push_back(pages_of[(size_t) l]);
138        }
139        std::sort(sizes.begin(), sizes.end());
140        sizes.erase(std::unique(sizes.begin(), sizes.end()), sizes.end());
141        std::vector<uint64_t> tops;   // each class's slot pages, largest first
142        for (auto it = sizes.rbegin(); it != sizes.rend(); ++it)
143            if (tops.empty() || (double) *it < (1.0 - waste) * (double) tops.back()) tops.push_back(*it);
144        for (uint64_t t : tops) { Cls c; c.pages = t; cls_.push_back(c); }
145        for (int l = 0; l < NL; ++l) {
146            int best = 0;   // the smallest class that holds the layer's slot
147            for (int c = 0; c < (int) cls_.size(); ++c)
148                if (cls_[(size_t) c].pages >= pages_of[(size_t) l]) best = c;
149            lay_[(size_t) l].cls = best;
150        }
151    }
152    nio_ = std::max(1, env_int("STRATA_METAL_IO_THREADS", 6));
153    split_ = std::max(1, std::min(8, env_int("STRATA_METAL_READ_SPLIT", 1)));
154    // The read-ahead's depth and where its experts wait in the LRU, measured on the M4 (notes-mac-ssd.md, 3 interleaved
155    // pairs each): Q2_0 (1.38 MB experts) top 10 at the LRU front 12.2 tok/s vs top 6 at the tail 11.3; the IQ3_XXS
156    // mix (1.75 MB, the SSD is the limit) top 6 at the tail 8.06 vs top 10 at the front 7.43.
157    uint64_t eb = 0;
158    for (const auto& x : lay_) eb += x.gs + x.us + x.ds;
159    const bool big = (double) eb / NL > 1.5e6;
160    pre_k_ = env_int("STRATA_METAL_PREFETCH", big ? 6 : 10);
161    pre_k2_ = env_int("STRATA_METAL_PREFETCH2", 0);
162    prefetch_ = pre_k_ > 0;
163    pre_mru_ = env_int("STRATA_METAL_PREFETCH_MRU", big ? 0 : 1) != 0;
164    // timing only (WRONG answers): every missing expert is pointed at slot 0, nothing is read
165    fake_ = env_int("STRATA_METAL_STREAM_FAKE", 0) != 0;
166    return true;
167}
168
169bool ExpertStream::read(void* dst, uint64_t len, uint64_t off) const {
170    uint8_t* p = (uint8_t*) dst;
171    while (len > 0) {
172        const ssize_t r = ::pread(fd_, p, (size_t) std::min<uint64_t>(len, 64ull << 20), (off_t) off);
173        if (r <= 0) return false;
174        p += r;
175        off += (uint64_t) r;
176        len -= (uint64_t) r;
177    }
178    return true;
179}
180
181bool ExpertStream::load_dense(gguf::File& f, mtl::Context& cx, const std::vector<std::string>& skip, mtl::Buffer& out,
182                              std::string& err) {
183    const double t0 = now_ms();
184    std::vector<gguf::Tensor*> ts;
185    uint64_t tot = 0;
186    for (auto& kv : f.tensors) {
187        gguf::Tensor& t = kv.second;
188        if (t.name.find("_exps") != std::string::npos) continue;
189        // the n-gram table is read by the host from the SSD, a few rows at a time (src/ngram/ple_reader.cpp).  It is its own shard in
190        // the ISTA / Unsloth files; in agentionai's Gyro files it is the first 28.8 GB of the one file, and must not be read in here
191        if (t.name == "per_layer_token_embd.weight") continue;
192        if (std::find(skip.begin(), skip.end(), t.name) != skip.end()) { t.offset = 0; continue; }
193        ts.push_back(&t);
194        tot += (t.bytes + 255) / 256 * 256;
195    }
196    out = cx.alloc((tot + PAGE - 1) / PAGE * PAGE);
197    std::vector<uint64_t> src(ts.size()), dst(ts.size());
198    uint64_t o = 0;
199    for (size_t i = 0; i < ts.size(); ++i) {
200        src[i] = ts[i]->offset;
201        dst[i] = o;
202        o += (ts[i]->bytes + 255) / 256 * 256;
203    }
204    std::atomic<size_t> next{0};
205    std::atomic<bool> ok{true};
206    std::vector<std::thread> th;
207    for (int k = 0; k < 4; ++k)
208        th.emplace_back([&] {
209            for (;;) {
210                const size_t i = next++;
211                if (i >= ts.size()) break;
212                if (!read(out.as<uint8_t>() + dst[i], ts[i]->bytes, src[i])) ok = false;
213            }
214        });
215    for (auto& x : th) x.join();
216    if (!ok) { err = "metal stream: reading the dense tensors failed"; return false; }
217    for (size_t i = 0; i < ts.size(); ++i) ts[i]->offset = dst[i];
218    std::fprintf(stderr, "strata metal stream: %zu dense tensors read into memory (%.2f GB, %.1f s; %zu left out)\n", ts.size(),
219                 tot / 1e9, (now_ms() - t0) / 1e3, skip.size());
220    return true;
221}
222
223int ExpertStream::cls_of(int s) const {   // the class ranges are contiguous
224    int ci = 0;
225    while (!(s >= cls_[(size_t) ci].base && s < cls_[(size_t) ci].base + cls_[(size_t) ci].n)) ++ci;
226    return ci;
227}
228
229void ExpertStream::lru_unlink(int s) {
230    Slot& x = slots_[(size_t) s];
231    Cls& k = cls_[(size_t) cls_of(s)];
232    if (x.prev >= 0) slots_[(size_t) x.prev].next = x.next; else k.head = x.next;
233    if (x.next >= 0) slots_[(size_t) x.next].prev = x.prev; else k.tail = x.prev;
234    x.prev = x.next = -1;
235}
236
237void ExpertStream::lru_back(int s) {
238    lru_unlink(s);
239    Cls& k = cls_[(size_t) cls_of(s)];
240    Slot& x = slots_[(size_t) s];
241    x.prev = k.tail;
242    x.next = -1;
243    if (k.tail >= 0) slots_[(size_t) k.tail].next = s;
244    k.tail = s;
245    if (k.head < 0) k.head = s;
246}
247
248void ExpertStream::lru_front(int s) {
249    lru_unlink(s);
250    Cls& k = cls_[(size_t) cls_of(s)];
251    Slot& x = slots_[(size_t) s];
252    x.next = k.head;
253    x.prev = -1;
254    if (k.head >= 0) slots_[(size_t) k.head].prev = s;
255    k.head = s;
256    if (k.tail < 0) k.tail = s;
257}
258
259int ExpertStream::victim(int ci) {
260    Cls& k = cls_[(size_t) ci];
261    for (int s = k.tail; s >= 0; s = slots_[(size_t) s].prev)
262        if (slots_[(size_t) s].state.load() == 0 && slots_[(size_t) s].pin != stamp_) {
263            Slot& x = slots_[(size_t) s];
264            if (x.layer >= 0) {
265                const int key = x.layer * NE + x.e;
266                where_[(size_t) key] = -1;
267                smap_.as<uint32_t>()[key] = 0xFFFFFFFFu;
268            }
269            x.layer = x.e = -1;
270            return s;
271        }
272    return -1;
273}
274
275// One piece of an expert: slice part / split_ (gate, up, down), piece part % split_ of it.  The pieces of one expert
276// go to several I/O threads, so a single miss is read with several requests in flight (its latency, not only the
277// SSD's throughput, is what a layer waits for).
278void ExpertStream::read_part(int s, int l, int e, int part) {
279    const Lay& x = lay_[(size_t) l];
280    if (cfd_ >= 0) {   // the contiguous copy: the whole expert, piece part of split_ (the slot keeps gate | up | down)
281        const uint64_t len = x.gs + x.us + x.ds, src = coff_[(size_t) l] + (uint64_t) e * len;
282        const uint64_t a = len * (uint64_t) part / (uint64_t) split_ / 4096 * 4096;
283        const uint64_t b = part + 1 == split_ ? len : len * (uint64_t) (part + 1) / (uint64_t) split_ / 4096 * 4096;
284        uint8_t* p = host_[(size_t) s] + a;
285        uint64_t n = b - a, o = src + a;
286        while (n > 0) {
287            const ssize_t r = ::pread(cfd_, p, (size_t) n, (off_t) o);
288            if (r <= 0) {
289                std::fprintf(stderr, "strata metal stream: reading expert %d of layer %d failed\n", e, l);
290                std::exit(6);
291            }
292            p += r; o += (uint64_t) r; n -= (uint64_t) r;
293        }
294        bytes_read_ += b - a;
295        return;
296    }
297    const int k = part / split_, p = part % split_;
298    const uint64_t len = k == 0 ? x.gs : (k == 1 ? x.us : x.ds);
299    const uint64_t src = (k == 0 ? x.g : (k == 1 ? x.u : x.d)) + (uint64_t) e * len;
300    const uint64_t dst = k == 0 ? 0 : (k == 1 ? x.gs : x.gs + x.us);
301    const uint64_t a = len * (uint64_t) p / (uint64_t) split_ / 4096 * 4096;
302    const uint64_t b = p + 1 == split_ ? len : len * (uint64_t) (p + 1) / (uint64_t) split_ / 4096 * 4096;
303    if (b > a && !read(host_[(size_t) s] + dst + a, b - a, src + a)) {
304        std::fprintf(stderr, "strata metal stream: reading expert %d of layer %d failed\n", e, l);
305        std::exit(6);
306    }
307    bytes_read_ += b - a;
308}
309
310void ExpertStream::io_main() {
311    for (;;) {
312        Job j;
313        {
314            std::unique_lock<std::mutex> g(mu_);
315            cv_.wait(g, [&] { return stop_ || !urgent_q_.empty() || !pre_q_.empty(); });
316            if (stop_) return;
317            if (!urgent_q_.empty()) { j = urgent_q_.front(); urgent_q_.pop_front(); }
318            else { j = pre_q_.front(); pre_q_.pop_front(); }
319            slots_[(size_t) j.slot].state = 2;
320        }
321        read_part(j.slot, j.layer, j.e, j.part);
322        bool done = false;
323        {
324            std::lock_guard<std::mutex> g(mu_);
325            Slot& x = slots_[(size_t) j.slot];
326            if (--x.left == 0) {
327                smap_.as<uint32_t>()[j.layer * NE + j.e] = code_[(size_t) j.slot];
328                x.state = 0;
329                --outstanding_;
330                ++reads_;
331                done = true;
332            }
333        }
334        if (done) done_cv_.notify_all();
335    }
336}
337
338void ExpertStream::submit(int s, int l, int e, bool urgent) {
339    Slot& x = slots_[(size_t) s];
340    x.layer = (int16_t) l;
341    x.e = (int16_t) e;
342    x.state = 1;
343    x.pre = !urgent;
344    const int parts = cfd_ >= 0 ? split_ : 3 * split_;
345    x.left = parts;
346    ++outstanding_;
347    where_[(size_t) (l * NE + e)] = s;
348    for (int p = 0; p < parts; ++p) (urgent ? urgent_q_ : pre_q_).push_back({s, l, e, p});
349}
350
351// a queued read-ahead nobody wants: its pieces dropped, the slot freed (only before any piece has started)
352void ExpertStream::cancel_slot(int s) {
353    Slot& x = slots_[(size_t) s];
354    for (auto it = pre_q_.begin(); it != pre_q_.end();) it = it->slot == s ? pre_q_.erase(it) : it + 1;
355    where_[(size_t) (x.layer * NE + x.e)] = -1;
356    x.layer = x.e = -1;
357    x.state = 0;
358    x.pre = false;
359    x.left = 0;
360    --outstanding_;
361    ++pre_cancel_;
362    lru_back(s);
363}
364
365// a read-ahead that is wanted now: its queued pieces go first
366void ExpertStream::promote_slot(int s) {
367    std::vector<Job> mine;
368    for (auto it = pre_q_.begin(); it != pre_q_.end();)
369        if (it->slot == s) { mine.push_back(*it); it = pre_q_.erase(it); }
370        else ++it;
371    for (auto it = mine.rbegin(); it != mine.rend(); ++it) urgent_q_.push_front(*it);
372}
373
374bool ExpertStream::make_arena(mtl::Context& cx, uint64_t budget, const std::string& profile, int min_slots, std::string& err,
375                              const std::function<uint64_t()>& recheck, const std::function<bool(uint64_t)>& grow) {
376    const double t0 = now_ms();
377    shrink_to_ = 0;
378    for (auto& k : cls_) k.n = 0;   // a second try (after a shrink) lays the arena out again
379    // the ranking: the profile's pairs, then every pair it misses, layer-interleaved
380    std::vector<std::pair<int, int>> rank;
381    std::vector<uint8_t> seen((size_t) NL * NE, 0);
382    if (FILE* f = std::fopen(profile.c_str(), "rb")) {
383        char magic[4];
384        uint32_t h[5];
385        if (std::fread(magic, 1, 4, f) == 4 && std::memcmp(magic, "STRP", 4) == 0 && std::fread(h, 4, 5, f) == 5 &&
386            h[1] == (uint32_t) NL && h[2] == (uint32_t) ne_) {
387            for (uint32_t i = 0; i < h[4]; ++i) {
388                uint16_t p[2];
389                if (std::fread(p, 2, 2, f) != 2) break;
390                if (p[0] < NL && p[1] < ne_ && !seen[(size_t) p[0] * NE + p[1]]) {
391                    seen[(size_t) p[0] * NE + p[1]] = 1;
392                    rank.push_back({p[0], p[1]});
393                }
394            }
395        }
396        std::fclose(f);
397    } else {
398        std::fprintf(stderr, "strata metal stream: no expert profile at %s: the arena starts layer-interleaved\n", profile.c_str());
399    }
400    const size_t from_profile = rank.size();
401    for (int e = 0; e < ne_; ++e)
402        for (int l = 0; l < NL; ++l)
403            if (!seen[(size_t) l * NE + e]) rank.push_back({l, e});
404    // the pool of each size class: at least min_slots (a prompt chunk's layer needs up to 512 at once), then the
405    // top-ranked pairs that fit in the budget
406    uint64_t used = 0;
407    for (const auto& k : cls_) used += (uint64_t) min_slots * k.pages * PAGE;
408    std::vector<std::pair<int, int>> fill;
409    for (const auto& p : rank) {
410        Cls& k = cls_[(size_t) lay_[(size_t) p.first].cls];
411        const uint64_t cost = k.n < min_slots ? 0 : k.pages * PAGE;
412        if (used + cost > budget) break;
413        used += cost;
414        ++k.n;
415        fill.push_back(p);
416    }
417    int base = 0;
418    for (auto& k : cls_) {
419        k.n = std::max(k.n, min_slots);
420        k.base = base;
421        base += k.n;
422    }
423    // the slots placed in chunks of at most maxBufferLength (and 8 GB), up to 4 (the kernels' buffers 0, 7, 8, 9)
424    // (8 GB each unless the arena needs bigger ones to fit 4: the M4 refused one 20.6 GB buffer, the M5 Max takes an
425    // 89 GB arena for UD-Q5_K_XL in 4 of ~23 GB; STRATA_METAL_ARENA_CHUNK_GB sets it)
426    uint64_t total = 0, biggest = 0;
427    for (const auto& k : cls_) {
428        total += (uint64_t) k.n * k.pages * PAGE;
429        biggest = std::max<uint64_t>(biggest, k.pages * PAGE);
430    }
431    uint64_t want = std::max<uint64_t>(8ull << 30, total / 4 + 4 * biggest);
432    if (const char* e = std::getenv("STRATA_METAL_ARENA_CHUNK_GB")) want = (uint64_t) (std::atof(e) * (1ull << 30));
433    const uint64_t cmax = std::min<uint64_t>(cx.max_buffer_length(), want) / PAGE * PAGE;
434    code_.assign((size_t) base, 0);
435    host_.assign((size_t) base, nullptr);
436    std::vector<uint64_t> csize;
437    std::vector<std::pair<int, uint64_t>> at((size_t) base);
438    uint64_t cur = 0;
439    for (const auto& k : cls_)
440        for (int s = k.base; s < k.base + k.n; ++s) {
441            if (csize.empty() || cur + k.pages * PAGE > cmax) {
442                if (!csize.empty()) csize.back() = cur;
443                csize.push_back(0);
444                cur = 0;
445            }
446            at[(size_t) s] = {(int) csize.size() - 1, cur / PAGE};
447            cur += k.pages * PAGE;
448        }
449    if (!csize.empty()) csize.back() = cur;
450    if (csize.size() > 4) { err = "metal stream: the arena needs more than 4 buffers (lower STRATA_METAL_ARENA_GB)"; return false; }
451    if (recheck) {   // the memory macOS can give, asked again just before the arena is committed
452        uint64_t total = 0;
453        for (uint64_t b : csize) total += b;
454        const uint64_t allowed = recheck();
455        if (allowed + (64ull << 20) < total) {
456            shrink_to_ = allowed;
457            err = "metal stream: less memory than planned is free now: the arena shrinks";
458            return false;
459        }
460    }
461    for (uint64_t b : csize) {   // anonymous memory wrapped no-copy: a prompt's buffers can alias a region of it
462        void* m = mmap(nullptr, (size_t) b, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
463        if (m == MAP_FAILED) { err = "metal stream: cannot map the arena"; return false; }
464        chunks_.push_back(cx.wrap(m, (size_t) b));
465        arena_bytes_ += b;
466    }
467    for (int s = 0; s < base; ++s) {
468        code_[(size_t) s] = ((uint32_t) at[(size_t) s].first << 28) | (uint32_t) at[(size_t) s].second;
469        host_[(size_t) s] = chunks_[(size_t) at[(size_t) s].first].as<uint8_t>() + at[(size_t) s].second * PAGE;
470    }
471    smap_ = cx.alloc((size_t) NL * NE * 4);
472    std::memset(smap_.ptr, 0xFF, (size_t) NL * NE * 4);
473    slots_ = std::vector<Slot>((size_t) base);
474    retired_.assign((size_t) base, 0);
475    where_.assign((size_t) NL * NE, -1);
476    for (auto& k : cls_) {
477        for (int s = k.base; s < k.base + k.n; ++s) {
478            slots_[(size_t) s].prev = s == k.base ? -1 : s - 1;
479            slots_[(size_t) s].next = s + 1 == k.base + k.n ? -1 : s + 1;
480        }
481        k.head = k.n ? k.base : -1;
482        k.tail = k.n ? k.base + k.n - 1 : -1;
483    }
484    for (int i = 0; i < nio_; ++i) io_.emplace_back([this] { io_main(); });
485    // the fill: the ranked pairs in steps (best first; each step in file order) on the I/O threads; before each step
486    // grow() asks whether macOS still has the memory for it (arena_grow); the best-ranked ends at the LRU front
487    uint64_t step = 1536ull << 20;
488    if (const char* e = std::getenv("STRATA_METAL_ARENA_STEP_GB")) step = std::max<uint64_t>(64ull << 20, (uint64_t) (std::atof(e) * 1e9));
489    std::vector<int> next_free(cls_.size());
490    for (size_t c = 0; c < cls_.size(); ++c) next_free[c] = cls_[c].base;
491    size_t done = 0;
492    bool stopped = false;
493    uint64_t filled = 0;
494    while (done < fill.size()) {
495        size_t j = done;
496        uint64_t sb = 0;
497        while (j < fill.size() && (sb < step || j == done)) sb += cls_[(size_t) lay_[(size_t) fill[j++].first].cls].pages * PAGE;
498        if (grow && !grow(sb)) { stopped = true; break; }
499        std::vector<std::pair<int, int>> order(fill.begin() + (long) done, fill.begin() + (long) j);
500        std::sort(order.begin(), order.end(), [&](const auto& a, const auto& b) {
501            return lay_[(size_t) a.first].g + (uint64_t) a.second * lay_[(size_t) a.first].gs <
502                   lay_[(size_t) b.first].g + (uint64_t) b.second * lay_[(size_t) b.first].gs;
503        });
504        {
505            std::lock_guard<std::mutex> g(mu_);
506            for (const auto& p : order) {
507                const int c = lay_[(size_t) p.first].cls;
508                submit(next_free[(size_t) c]++, p.first, p.second, true);
509            }
510        }
511        cv_.notify_all();
512        {
513            std::unique_lock<std::mutex> g(mu_);
514            done_cv_.wait(g, [&] { return outstanding_ == 0; });
515        }
516        filled += sb;
517        done = j;
518    }
519    uint64_t retired_bytes = 0;
520    size_t nretired = 0;
521    {
522        std::unique_lock<std::mutex> g(mu_);
523        if (stopped)   // the slots not filled stay unused (their pages never touched), all but min_slots of each class
524            for (size_t c = 0; c < cls_.size(); ++c) {
525                const Cls& k = cls_[c];
526                for (int s = std::max(next_free[c], k.base + std::min(min_slots, k.n)); s < k.base + k.n; ++s) {
527                    lru_unlink(s);
528                    retired_[(size_t) s] = 1;
529                    retired_bytes += k.pages * PAGE;
530                    ++nretired;
531                }
532            }
533        // the LRU order = the rank order (best at the front)
534        for (size_t i = done; i-- > 0;) lru_front(where_[(size_t) (fill[i].first * NE + fill[i].second)]);
535    }
536    if (stopped)
537        std::fprintf(stderr, "strata metal stream: the arena's fill stopped after %.2f GB: macOS's free memory reached what it "
538                             "keeps; %.2f GB of the arena (%zu slots) stay unused\n", filled / 1e9, retired_bytes / 1e9, nretired);
539    arena_live_ = arena_bytes_ - retired_bytes;
540    fill_s_ = (now_ms() - t0) / 1e3;
541    fill_bytes_ = bytes_read_.load();
542    uint64_t pairs = 0;
543    for (const auto& k : cls_) pairs += (uint64_t) k.n;
544    std::fprintf(stderr, "strata metal stream: expert arena %.2f GB, %llu slots in %zu size classes, %zu experts read from the "
545                         "profile's top (%zu ranked) in %.1f s (%.2f GB/s); %d I/O threads, read-ahead top %d; %zu buffers\n",
546                 (arena_bytes_ - retired_bytes) / 1e9, (unsigned long long) (pairs - nretired), cls_.size(), done, from_profile, fill_s_,
547                 fill_bytes_ / 1e9 / std::max(1e-9, fill_s_), nio_, prefetch_ ? pre_k_ : 0, chunks_.size());
548    // Wire the filled arena (mlock).  Unwired, the arena is ordinary anonymous memory whenever the GPU is not running a command buffer
549    // (the GPU's own wiring ends a few seconds after the last one; a Metal residency set did not hold it either, measured), and
550    // macOS compresses it when anything else wants memory: a 20 GB file written beside the idle engine took tens of GB of the arena
551    // into the compressor in seconds and froze the 128 GB M5 Max (watchdog panic, 2026-10-13).  Wired, a file write can only
552    // shrink the file cache.  STRATA_METAL_WIRE_ARENA=0/1; the default is on for a Mac of 64 GB or more (the M4 32 GB was measured
553    // unwired).  Not when the fill stopped early for lack of memory (the unused slots would be wired too).
554    {
555        uint64_t phys = 0;
556        size_t plen = sizeof phys;
557        sysctlbyname("hw.memsize", &phys, &plen, nullptr, 0);
558        const char* we = std::getenv("STRATA_METAL_WIRE_ARENA");
559        const bool want = we && *we ? std::atoi(we) != 0 : (double) phys >= kBigMac;
560        if (want && !stopped) {
561            const double tp = now_ms();
562            uint64_t pinned = 0;
563            int failed = 0;
564            for (const auto& c : chunks_) {
565                if (mlock(c.ptr, c.bytes) == 0) pinned += c.bytes;
566                else ++failed;
567            }
568            std::fprintf(stderr, "strata metal stream: %.1f GB of the arena wired (mlock) in %.0f ms%s; macOS cannot compress it while "
569                                 "the engine idles (STRATA_METAL_WIRE_ARENA=0 turns it off)\n", pinned / 1e9, now_ms() - tp,
570                         failed ? "; SOME CHUNKS COULD NOT BE WIRED" : "");
571        }
572    }
573    (void) err;
574    return true;
575}
576
577// the experts a predicted routing names, most likely first (by the best logit over the window's tokens)
578void ExpertStream::ahead(int ln, int T, const float* pred, int K) {
579    K = std::min(K, 32);
580    std::pair<float, int> pw[8 * 32];
581    int np = 0;
582    for (int t = 0; t < T; ++t) {
583        const float* lg = pred + (size_t) t * NE;
584        int top[32];
585        int nt = 0;
586        for (int e = 0; e < ne_; ++e) {
587            if (nt < K) { top[nt++] = e; continue; }
588            int m = 0;
589            for (int j = 1; j < K; ++j) if (lg[top[j]] < lg[top[m]]) m = j;
590            if (lg[e] > lg[top[m]]) top[m] = e;
591        }
592        for (int j = 0; j < nt; ++j) {
593            int q = 0;
594            while (q < np && pw[q].second != top[j]) ++q;
595            if (q == np) pw[np++] = {lg[top[j]], top[j]};
596            else pw[q].first = std::max(pw[q].first, lg[top[j]]);
597        }
598    }
599    std::sort(pw, pw + np, [](const auto& a, const auto& b) { return a.first > b.first; });
600    bool any = false;
601    {
602        std::lock_guard<std::mutex> g(mu_);
603        for (int j = 0; j < np; ++j) {
604            const int key = ln * NE + pw[j].second;
605            const int s0 = where_[(size_t) key];
606            if (s0 >= 0) { lru_front(s0); continue; }
607            const int s = victim(lay_[(size_t) ln].cls);
608            if (s < 0) break;
609            submit(s, ln, pw[j].second, false);
610            slots_[(size_t) s].pin = stamp_;
611            if (pre_mru_) lru_front(s);
612            else lru_back(s);
613            ++pre_issued_;
614            any = true;
615        }
616    }
617    if (any) cv_.notify_all();
618}
619
620void ExpertStream::at_layer(int l, int T, int topk, const int32_t* ids, const float* pred, const float* pred2) {
621    const double t0 = now_ms();
622    const bool prompt = T > 8;   // a prompt chunk (the GEMM path): nearly every expert of the layer is used
623    if (l == 0) { if (prompt) ++p_chunks_; else ++windows_; }
624    ++stamp_;                    // the slots this layer uses are pinned until the next handshake
625    bool used[NE] = {};
626    int want[NE];
627    int nw = 0;
628    for (int i = 0; i < T * topk; ++i) {
629        const int e = ids[i];
630        if (e < 0 || e >= NE || used[e]) continue;
631        used[e] = true;
632        want[nw++] = e;
633    }
634    if (fake_) {
635        for (int j = 0; j < nw; ++j)
636            if (where_[(size_t) (l * NE + want[j])] < 0) smap_.as<uint32_t>()[l * NE + want[j]] = code_[0];
637        host_ms_ += now_ms() - t0;
638        return;
639    }
640    std::vector<int> wait;
641    {
642        std::lock_guard<std::mutex> g(mu_);
643        // read-aheads of this layer (or older) that were not started and are not wanted: dropped (the slot goes free)
644        {
645            std::vector<int> drop;
646            for (const Job& j : pre_q_) {
647                if (j.layer > l || slots_[(size_t) j.slot].state.load() != 1) continue;
648                if (!(j.layer == l && used[j.e]) && std::find(drop.begin(), drop.end(), j.slot) == drop.end()) drop.push_back(j.slot);
649            }
650            for (int s : drop) cancel_slot(s);
651        }
652        for (int j = 0; j < nw; ++j)   // pass 1: pin what is resident (or on its way), so no miss below evicts it
653            if (where_[(size_t) (l * NE + want[j])] >= 0) slots_[(size_t) where_[(size_t) (l * NE + want[j])]].pin = stamp_;
654        for (int j = 0; j < nw; ++j) {
655            const int e = want[j], key = l * NE + e;
656            uint64_t& lk = prompt ? p_lookups_ : lookups_;
657            ++lk;
658            int s = where_[(size_t) key];
659            if (s >= 0) {
660                Slot& x = slots_[(size_t) s];
661                x.pin = stamp_;
662                const int st = x.state.load();
663                if (st == 0) { if (x.pre) ++(prompt ? p_pre_ : pre_hits_); else ++(prompt ? p_hits_ : hits_); }
664                else {
665                    ++(prompt ? p_pre_ : pre_hits_);
666                    if (!prompt) ++late_;
667                    promote_slot(s);   // a queued read-ahead becomes urgent
668                    wait.push_back(s);
669                }
670                if (!(prompt && x.pre)) lru_front(s);   // a prompt's streamed experts stay at the LRU tail
671                x.pre = false;
672                continue;
673            }
674            ++(prompt ? p_misses_ : misses_);
675            s = victim(lay_[(size_t) l].cls);
676            if (s < 0) { std::fprintf(stderr, "strata metal stream: no free slot (layer %d)\n", l); std::exit(6); }
677            submit(s, l, e, true);
678            slots_[(size_t) s].pin = stamp_;
679            if (!prompt) lru_front(s);
680            wait.push_back(s);
681        }
682    }
683    if (!wait.empty()) {
684        cv_.notify_all();
685        const double tw = now_ms();
686        std::unique_lock<std::mutex> g(mu_);
687        done_cv_.wait(g, [&] {
688            for (int s : wait) if (slots_[(size_t) s].state.load() != 0) return false;
689            return true;
690        });
691        (prompt ? p_wait_ms_ : wait_ms_) += now_ms() - tw;
692    }
693    if (prompt) {
694        // a chunk uses nearly all of the next layer's experts: every one not in the arena is streamed in behind this
695        // layer's compute, into the LRU tail (the decode-hot experts stay)
696        if (l + 1 < NL) {
697            bool any = false;
698            std::lock_guard<std::mutex> g(mu_);
699            const int ln = l + 1;
700            for (int e = 0; e < ne_; ++e) {
701                if (where_[(size_t) (ln * NE + e)] >= 0) continue;
702                const int s = victim(lay_[(size_t) ln].cls);
703                if (s < 0) break;
704                submit(s, ln, e, false);
705                slots_[(size_t) s].pin = stamp_;
706                ++p_streamed_;
707                any = true;
708            }
709            if (any) cv_.notify_all();
710        }
711        (prompt ? p_host_ms_ : host_ms_) += now_ms() - t0;
712        return;
713    }
714    // read-ahead: layer l + 1 (each token's top pre_k_ of the predicted router logits), then layer l + 2 (top pre_k2_)
715    if (prefetch_ && pred && l + 1 < NL) ahead(l + 1, T, pred, pre_k_);
716    if (pre_k2_ > 0 && pred2 && l + 2 < NL) ahead(l + 2, T, pred2, pre_k2_);
717    host_ms_ += now_ms() - t0;
718}
719
720// A region of `bytes` at the end of one arena buffer, for a prompt's scratch buffers: its slots are emptied and held
721// (state 3) while a prompt runs (hold_region), and are ordinary slots again for decoding.
722uint8_t* ExpertStream::region(uint64_t bytes) {
723    for (int c = (int) chunks_.size() - 1; c >= 0; --c) {
724        if (chunks_[(size_t) c].bytes < bytes + (64ull << 20)) continue;
725        uint8_t* end = chunks_[(size_t) c].as<uint8_t>() + chunks_[(size_t) c].bytes;
726        uint8_t* lo = end - (bytes + PAGE - 1) / PAGE * PAGE;
727        region_slots_.clear();
728        uint8_t* first = end;
729        for (int s = 0; s < (int) slots_.size(); ++s) {
730            const uint8_t* h = host_[(size_t) s];
731            const uint64_t sz = cls_[(size_t) cls_of(s)].pages * PAGE;
732            if (h + sz > lo && h < end) { region_slots_.push_back(s); first = std::min(first, (uint8_t*) h); }
733        }
734        {   // a class left with fewer slots than a prompt chunk's layer can use (NE) would stop with "no free slot": a small
735            // arena (a Mac with little free memory at start) gets the prompt's buffers as their own allocation instead
736            std::vector<int> stolen(cls_.size(), 0);
737            for (int s : region_slots_) ++stolen[(size_t) cls_of(s)];
738            bool tight = false;
739            for (size_t i = 0; i < cls_.size(); ++i) tight = tight || (cls_[i].n > 0 && cls_[i].n - stolen[i] < ne_);
740            if (tight) return standalone_region(bytes);
741        }
742        region_ = lo;
743        region_bytes_ = (uint64_t) (end - lo);
744        std::fprintf(stderr, "strata metal stream: %.2f GB of the arena (%zu slots) hold a prompt's buffers while it runs\n",
745                     bytes / 1e9, region_slots_.size());
746        return lo;
747    }
748    // no chunk is big enough for the prompt's buffers (an arena that shrank at the start, a 24 GB Mac): the fallback
749    // inside the loop above is only reached when a chunk fits, so the buffers get their own allocation here too
750    return standalone_region(bytes);
751}
752
753// The prompt's buffers as their own anonymous allocation (fresh zero pages), when no region of the arena's slots
754// takes them: no slots are held while a prompt runs, and the arena keeps decoding with all of its slots.
755uint8_t* ExpertStream::standalone_region(uint64_t bytes) {
756    const uint64_t sz = (bytes + PAGE - 1) / PAGE * PAGE;
757    void* m = mmap(nullptr, (size_t) sz, PROT_READ | PROT_WRITE, MAP_ANON | MAP_PRIVATE, -1, 0);
758    if (m == MAP_FAILED) return nullptr;
759    region_slots_.clear();
760    region_ = (uint8_t*) m;
761    region_bytes_ = 0;   // fresh zero pages; nothing in the arena to empty
762    std::fprintf(stderr, "strata metal stream: the arena is small: the prompt's %.2f GB of buffers are their own "
763                         "allocation, not a region of its slots\n", bytes / 1e9);
764    return region_;
765}
766
767void ExpertStream::hold_region(bool hold) {
768    std::unique_lock<std::mutex> g(mu_);
769    if (hold) {
770        // nothing may be reading into those slots: the queued read-aheads are dropped, the running ones waited for
771        std::vector<int> drop;
772        for (const Job& j : pre_q_)
773            if (slots_[(size_t) j.slot].state.load() == 1 && std::find(drop.begin(), drop.end(), j.slot) == drop.end())
774                drop.push_back(j.slot);
775        for (int s : drop) cancel_slot(s);
776        done_cv_.wait(g, [&] { return outstanding_ == 0; });
777        for (int s : region_slots_) {
778            Slot& x = slots_[(size_t) s];
779            if (x.layer >= 0) {
780                const int key = x.layer * NE + x.e;
781                where_[(size_t) key] = -1;
782                smap_.as<uint32_t>()[key] = 0xFFFFFFFFu;
783            }
784            x.layer = x.e = -1;
785            x.pre = false;
786            x.state = 3;
787        }
788        if (region_) std::memset(region_, 0, (size_t) region_bytes_);
789    } else {
790        for (int s : region_slots_) {
791            slots_[(size_t) s].state = 0;
792            if (!retired_[(size_t) s]) lru_back(s);   // a retired slot's memory serves the prompt only
793        }
794    }
795}
796
797void ExpertStream::reset_stats() {
798    lookups_ = hits_ = pre_hits_ = late_ = misses_ = pre_issued_ = pre_cancel_ = windows_ = 0;
799    p_lookups_ = p_hits_ = p_pre_ = p_misses_ = p_streamed_ = p_chunks_ = 0;
800    p_wait_ms_ = p_host_ms_ = 0;
801    bytes_read_ = 0;
802    reads_ = 0;
803    wait_ms_ = host_ms_ = 0;
804}
805
806void ExpertStream::report(FILE* f) const {
807    if (!ready()) return;
808    if (p_chunks_)
809        std::fprintf(f, "expert stream prompts    %llu chunks: %llu distinct lookups (%.1f per layer), in the arena %.4f, streamed "
810                        "ahead %.4f, missed %.4f; %llu streamed in; host %.1f ms per chunk, of it waiting %.1f ms\n",
811                     (unsigned long long) p_chunks_, (unsigned long long) p_lookups_, p_lookups_ / (double) NL / p_chunks_,
812                     p_hits_ / std::max(1.0, (double) p_lookups_), p_pre_ / std::max(1.0, (double) p_lookups_),
813                     p_misses_ / std::max(1.0, (double) p_lookups_), (unsigned long long) p_streamed_, p_host_ms_ / p_chunks_,
814                     p_wait_ms_ / p_chunks_);
815    const double w = std::max<uint64_t>(1, windows_);
816    std::fprintf(f,
817                 "expert stream            %llu windows: %llu distinct lookups (%.1f per window), hits %.4f, read-ahead hits "
818                 "%.4f (%llu of them late), misses %.4f (%.1f per window); read-aheads %llu (%.1f per window, %llu dropped); %.1f MB "
819                 "read per window (%llu reads); host %.2f ms per window, of it waiting %.2f ms\n",
820                 (unsigned long long) windows_, (unsigned long long) lookups_, lookups_ / w,
821                 hits_ / std::max(1.0, (double) lookups_), pre_hits_ / std::max(1.0, (double) lookups_),
822                 (unsigned long long) late_, misses_ / std::max(1.0, (double) lookups_), misses_ / w,
823                 (unsigned long long) pre_issued_, pre_issued_ / w, (unsigned long long) pre_cancel_,
824                 (bytes_read_.load() - 0) / 1e6 / w, (unsigned long long) reads_.load(), host_ms_ / w, wait_ms_ / w);
825}
826
827}  // namespace strata::metal_engine