okami.mom/strata

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

waveringanaedge0 port: gate or drop the fork's remaining unconditional debug printsd510921bc

main
387.6 KiB7418 linesraw
1// src/core/expert_source.cpp - the adapter.  See the header for the three clauses of the contract.
2#include "strata/core/expert_source.hpp"
3#include "strata/kernels/cpu/kq_avx2.hpp"
4#include "ggml.h"
5#include "ggml-cpu.h"
6#include "strata/core/latent_share.hpp"
7#include "strata/core/expert_nibble.hpp"
8#include "strata/core/conversation_memory.hpp"
9#include "strata/core/foresight_swap.hpp"
10#include "strata/core/on_device.hpp"
11#include "strata/core/page_cache_drop.hpp"
12#include "strata/core/ple_residency.hpp"
13#include "strata/core/resident_ram_copy.hpp"
14#include "strata/platform/aux_cpus.hpp"
15#include "strata/core/remote_experts.hpp"
16#include "strata/core/peer_experts.hpp"
17#include "strata/kernels/cpu/expert_layout.hpp"
18#include "strata/kernels/window_limits.hpp"
19#include "strata/artifact/gguf_reader.hpp"
20
21#include "strata/core/pinned.hpp"
22#include "strata/platform/memory.hpp"
23#include "strata/kernels/elementwise.hpp"
24#include "strata/kernels/quantize_act.hpp"
25#include "strata/kernels/s2_expert_grouped.hpp"
26#include "strata/kernels/cpu/kq_avx1.hpp"
27#include "strata/kernels/cpu/kq_avx2.hpp"
28#include "strata/kernels/cpu/pool.hpp"
29#include "strata/kernels/f16_bits.hpp"
30
31#include <cuda_runtime.h>
32#ifndef _WIN32
33#include <signal.h>
34#include <unistd.h>
35#endif
36
37#include <algorithm>
38#include <atomic>
39#include <cassert>
40#include <cerrno>
41#include <chrono>
42#include <cstdio>
43#include <cstdlib>
44#include <cstring>
45#include <deque>
46#include <fstream>
47#include <filesystem>
48#include <iterator>
49#include <sstream>
50#include <limits>
51#include <map>
52#include <memory>
53#include <mutex>
54#include <thread>
55#include <utility>
56#include <vector>
57
58#if defined(_WIN32)
59#define WIN32_LEAN_AND_MEAN
60#ifndef NOMINMAX
61#define NOMINMAX   // std::numeric_limits<T>::max() below
62#endif
63#include <windows.h>
64#else
65#include <fcntl.h>
66#if defined(__APPLE__)
67#include <mach/mach.h>   // host_statistics64: the available memory
68#endif
69#include <sys/mman.h>
70#include <sys/stat.h>
71#include <unistd.h>
72#endif
73#if defined(__linux__)
74#include <cerrno>
75#include <linux/aio_abi.h>   // the kernel's own asynchronous reads (io_submit): no library, allowed by Docker's seccomp
76#include <sched.h>
77#include <sys/syscall.h>
78#endif
79
80// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform
81#ifndef STRATA_FSEEK64
82#ifdef _WIN32
83#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET)
84#else
85#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET)
86#endif
87#endif
88
89// The pid of this process and whether a pid still exists (the shared arena's reader election, both OSes)
90static uint64_t arena_this_pid() {
91#ifdef _WIN32
92    return (uint64_t) GetCurrentProcessId();
93#else
94    return (uint64_t) getpid();
95#endif
96}
97static bool arena_pid_alive(uint64_t pid) {
98#ifdef _WIN32
99    HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, (DWORD) pid);
100    if (h == nullptr) return GetLastError() == ERROR_ACCESS_DENIED;     // (denied: it exists; invalid parameter: it does not)
101    DWORD code = 0;
102    const bool alive = GetExitCodeProcess(h, &code) && code == STILL_ACTIVE;
103    CloseHandle(h);
104    return alive;
105#else
106    return !(kill((pid_t) pid, 0) != 0 && errno == ESRCH);
107#endif
108}
109
110namespace strata::core {
111
112namespace detail {
113
114bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes) {
115    bytes = 0;
116    if (!stat.valid) return false;
117
118    // memory.stat's counters can race memory.current, so bound them to charged usage first.  The whole clean page
119    // cache is reclaimable (149: MemAvailable counts active file pages too); the kernel keeps a low-watermark share.
120    uint64_t reclaimable = std::min(std::max(stat.file, stat.inactive_file), stat.current);
121    reclaimable = stat.file_dirty >= reclaimable ? 0 : reclaimable - stat.file_dirty;
122    reclaimable = stat.file_writeback >= reclaimable ? 0 : reclaimable - stat.file_writeback;
123    reclaimable -= std::min(reclaimable / 2, limit / 64);
124
125    // Reclaiming clean file pages reduces usage; saturating subtraction also handles a transient over-limit read.
126    const uint64_t usage_after_reclaim = stat.current - reclaimable;
127    bytes = usage_after_reclaim < limit ? limit - usage_after_reclaim : 0;
128    return true;
129}
130
131uint64_t clamp_resident_budget(uint64_t requested, uint64_t physical, uint64_t commit, uint64_t headroom) {
132    const uint64_t available = std::min(physical, commit);
133    const uint64_t room = available > headroom ? available - headroom : 0;
134    if (requested <= room) return requested;
135    const uint64_t margin = 256ull << 20;
136    return room > margin ? room - margin : 0;
137}
138
139bool pin_depends_on_reclaim(uint64_t free_now, uint64_t bytes, uint64_t reserve) {
140    return bytes > 0 && free_now < bytes + reserve;
141}
142
143bool wait_for_ram(uint64_t need, double max_wait_s, double step_s, double note_s,
144                  const std::function<bool(uint64_t&)>& sample, const std::function<void(double)>& sleep,
145                  const std::function<void(double, uint64_t)>& progress, double& waited, uint64_t& available) {
146    waited = 0.0;
147    if (!sample(available)) return false;
148    double next_note = 0.0;
149    while (available < need && waited < max_wait_s) {
150        if (progress && waited >= next_note) {
151            progress(waited, available);
152            next_note = waited + note_s;
153        }
154        sleep(step_s);
155        waited += step_s;
156        if (!sample(available)) return false;
157    }
158    return available >= need;
159}
160
161bool pin_step_fits(uint64_t available, uint64_t step, uint64_t reserve) {
162    return available >= step + reserve;
163}
164
165uint64_t meminfo_bytes(const std::string& meminfo_text, const std::string& key) {
166    std::istringstream in(meminfo_text);
167    std::string line;
168    const std::string want = key + ":";
169    while (std::getline(in, line)) {
170        std::istringstream fields(line);
171        std::string k, unit;
172        uint64_t value = 0;
173        if (fields >> k >> value && k == want) {
174            fields >> unit;
175            return unit == "kB" ? value * 1024 : value;
176        }
177    }
178    return 0;
179}
180
181uint64_t numa_pin_free(uint64_t global_free, const std::vector<uint64_t>& node_free) {
182    if (node_free.size() < 2) return global_free;
183    const uint64_t smallest = *std::min_element(node_free.begin(), node_free.end());
184    return std::min<uint64_t>(global_free, smallest * (uint64_t) node_free.size());
185}
186
187std::array<std::pair<uint64_t, uint64_t>, 3> numa_slice_ranges(uint64_t slot_off, const uint64_t role_bytes[3],
188                                                               int slice, uint64_t page) {
189    assert(slice == 0 || slice == 1);
190    std::array<std::pair<uint64_t, uint64_t>, 3> out{};
191    uint64_t start = slot_off;
192    for (int r = 0; r < 3; ++r) {
193        const uint64_t mid = start + role_bytes[r] / 2, end = start + role_bytes[r];
194        if (slice == 0) {
195            out[r] = {start / page * page, (mid + page - 1) / page * page};
196        } else {
197            const uint64_t lo = (mid + page - 1) / page * page, hi = end / page * page;
198            out[r] = hi > lo ? std::make_pair(lo, hi) : std::make_pair(lo, lo);
199        }
200        start = end;
201    }
202    return out;
203}
204
205std::string page_cache_hint(const std::string& meminfo_text) {
206    const uint64_t cache = meminfo_bytes(meminfo_text, "Cached") + meminfo_bytes(meminfo_text, "Buffers");
207    if (cache < (1ull << 30)) return "";
208    char msg[420];
209    std::snprintf(msg, sizeof msg,
210                  "; %.1f GiB of the RAM is file cache (earlier runs' model files, which Linux gives back on demand - "
211                  "'free' showing little is normal). If the start still fails, free it with: "
212                  "sync; echo 1 | sudo tee /proc/sys/vm/drop_caches   (or start strata serve with "
213                  "STRATA_DROP_CACHE_ON_EXIT=1 so it releases its model files when it stops)",
214                  (double) cache / 1073741824.0);
215    return msg;
216}
217
218bool make_cache_complement_plan(
219    int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,
220    const std::vector<std::pair<int32_t, int32_t>>& primary_gpu_pairs,
221    const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs,
222    std::vector<uint64_t>& offsets, uint64_t& bytes, std::string& err) {
223    offsets.clear();
224    bytes = 0;
225    err.clear();
226    if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers) {
227        err = "FileExpertSource: invalid geometry for the cache complement plan";
228        return false;
229    }
230    if ((uint64_t) n_layers > (uint64_t) std::numeric_limits<size_t>::max() / (uint64_t) n_expert) {
231        err = "FileExpertSource: cache complement index table is too large";
232        return false;
233    }
234    const size_t count = (size_t) n_layers * (size_t) n_expert;
235    std::vector<uint8_t> omitted(count, 0);
236    auto mark_pairs = [&](const std::vector<std::pair<int32_t, int32_t>>& pairs, uint8_t bit,
237                          const char* label) -> bool {
238        for (const auto& pair : pairs) {
239            if (pair.first < 0 || pair.second < 0 || pair.first >= n_layers || pair.second >= n_expert) {
240                err = std::string("FileExpertSource: ") + label + " pair is outside the expert geometry";
241                return false;
242            }
243            const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second;
244            if ((omitted[index] & bit) != 0) {
245                err = std::string("FileExpertSource: duplicate ") + label + " pair in the cache complement plan";
246                return false;
247            }
248            if (bit == 2 && (omitted[index] & 1) != 0) {
249                err = "FileExpertSource: the primary and additional GPU expert tiers overlap";
250                return false;
251            }
252            omitted[index] |= bit;
253        }
254        return true;
255    };
256    if (!mark_pairs(primary_gpu_pairs, 1, "primary GPU") ||
257        !mark_pairs(additional_gpu_pairs, 2, "additional GPU")) return false;
258    for (uint64_t blob_bytes : layer_blob_bytes) {
259        if (blob_bytes == 0) {
260            err = "FileExpertSource: cache complement layer has zero-sized expert blobs";
261            return false;
262        }
263    }
264
265    offsets.assign(count, kNoCacheComplement);
266    for (int64_t layer = 0; layer < n_layers; ++layer) {
267        const uint64_t blob_bytes = layer_blob_bytes[(size_t) layer];
268        for (int64_t expert = 0; expert < n_expert; ++expert) {
269            const size_t index = (size_t) layer * (size_t) n_expert + (size_t) expert;
270            if (omitted[index] != 0) continue;
271            if (bytes > std::numeric_limits<uint64_t>::max() - blob_bytes) {
272                offsets.clear();
273                bytes = 0;
274                err = "FileExpertSource: cache complement size overflows";
275                return false;
276            }
277            offsets[index] = bytes;
278            bytes += blob_bytes;
279        }
280    }
281    if (bytes > (uint64_t) std::numeric_limits<size_t>::max()) {
282        offsets.clear();
283        bytes = 0;
284        err = "FileExpertSource: cache complement exceeds the host address space";
285        return false;
286    }
287    return true;
288}
289
290const uint8_t* cache_complement_blob_or_fallback(
291    size_t index, const std::vector<uint64_t>& offsets, const uint8_t* complement_host,
292    const uint8_t* mapped_fallback) {
293    if (complement_host != nullptr && index < offsets.size() && offsets[index] != kNoCacheComplement)
294        return complement_host + (size_t) offsets[index];
295    return mapped_fallback;
296}
297
298int64_t choose_resident_keep_from(const std::vector<uint64_t>& slot_bytes, uint64_t base_bytes, uint64_t budget,
299                                  int64_t lend_from) {
300    if (base_bytes > budget) return -1;
301    const int64_t slots = (int64_t) slot_bytes.size();
302    if (lend_from < 0 || lend_from > slots) lend_from = slots;   // no lend region: only the experts no slot holds
303    int64_t keep = slots;
304    uint64_t bytes = base_bytes;
305    while (keep > lend_from) {
306        const uint64_t b = slot_bytes[(size_t) keep - 1];
307        if (b > budget - bytes) break;
308        bytes += b;
309        --keep;
310    }
311    return keep;
312}
313
314int64_t append_stage_lend_regions(int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,
315                                  std::vector<uint64_t>& offsets, uint64_t& bytes, uint64_t cap_bytes,
316                                  const std::vector<std::vector<std::pair<int32_t, int32_t>>>& regions,
317                                  std::string& err) {
318    const size_t blobs = (size_t) (n_layers * n_expert);
319    if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers || offsets.size() != blobs) {
320        err = "append_stage_lend_regions: the plan does not match the geometry";
321        return -1;
322    }
323    std::vector<std::pair<int32_t, int32_t>> sorted;
324    for (const auto& region : regions) {   // validate the whole request before touching the plan
325        for (const auto& pair : region)
326            if (pair.first < 0 || pair.first >= n_layers || pair.second < 0 || pair.second >= n_expert) {
327                err = "append_stage_lend_regions: a lend-region expert is outside the model";
328                return -1;
329            }
330        sorted = region;
331        std::sort(sorted.begin(), sorted.end());
332        for (size_t i = 1; i < sorted.size(); ++i)
333            if (sorted[i] == sorted[i - 1]) {
334                err = "append_stage_lend_regions: a stage's lend region repeats an expert";
335                return -1;
336            }
337    }
338    int64_t kept = 0;
339    for (const auto& region : regions) {
340        for (const auto& pair : region) {
341            const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second;
342            if (offsets[index] != kNoCacheComplement) continue;   // already in the copy: the complement, or a
343                                                                  // CUDA0 lend slot the region is asked to skip
344            const uint64_t b = layer_blob_bytes[(size_t) pair.first];
345            if (b > cap_bytes - bytes) break;                     // this stage's rest keeps the file fallback
346            offsets[index] = bytes;
347            bytes += b;
348            ++kept;
349        }
350    }
351    return kept;
352}
353
354bool exchange_cache_complement(std::vector<uint64_t>& offsets, size_t in, size_t out) {
355    if (in == out || in >= offsets.size() || out >= offsets.size() || offsets[in] == kNoCacheComplement ||
356        offsets[out] != kNoCacheComplement) return false;
357    offsets[out] = offsets[in];
358    offsets[in] = kNoCacheComplement;
359    return true;
360}
361
362}  // namespace detail
363
364namespace {
365
366#if defined(__linux__)
367bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current,
368                             detail::CgroupMemoryStat& stat) {
369    std::ifstream input(path / "memory.stat");
370    if (!input) return false;
371
372    bool inactive_file = false, file_dirty = false, file_writeback = false, file = false;
373    std::string line;
374    while (std::getline(input, line)) {
375        std::istringstream fields(line);
376        std::string key;
377        uint64_t value = 0;
378        if (!(fields >> key >> value)) return false;
379        fields >> std::ws;
380        if (!fields.eof()) return false;
381
382        if (key == "inactive_file") {
383            if (inactive_file) return false;
384            inactive_file = true;
385            stat.inactive_file = value;
386        } else if (key == "file_dirty") {
387            if (file_dirty) return false;
388            file_dirty = true;
389            stat.file_dirty = value;
390        } else if (key == "file_writeback") {
391            if (file_writeback) return false;
392            file_writeback = true;
393            stat.file_writeback = value;
394        } else if (key == "file") {   // 149: optional (every v2 kernel has it); 0 = inactive_file alone
395            if (file) return false;
396            file = true;
397            stat.file = value;
398        }
399    }
400    if (!input.eof() || !inactive_file || !file_dirty || !file_writeback) return false;
401    stat.current = current;
402    stat.valid = true;
403    return true;
404}
405#endif
406
407}  // namespace
408
409namespace detail {
410
411bool host_available_memory(HostMemory& m, const std::string& meminfo, const std::string& self_cgroup,
412                           const std::string& cgroup_root) {
413    m = HostMemory{};
414#if defined(_WIN32)
415    (void) meminfo; (void) self_cgroup; (void) cgroup_root;
416    MEMORYSTATUSEX status{};
417    status.dwLength = sizeof(status);
418    if (!GlobalMemoryStatusEx(&status)) return false;
419    m.available = (uint64_t) status.ullAvailPhys;
420    m.commit = (uint64_t) status.ullAvailPageFile;
421    return m.available > 0;
422#elif defined(__linux__)
423    // MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES.
424    std::ifstream info(meminfo);
425    std::string line;
426    uint64_t bytes = 0;
427    std::optional<uint64_t> mem_total;   // a limit below it is a container's (its /proc/meminfo is the host's)
428    while (std::getline(info, line)) {
429        std::istringstream fields(line);
430        std::string key, unit;
431        uint64_t value = 0;
432        if (fields >> key >> value >> unit && key == "MemAvailable:" && unit == "kB" &&
433            value <= std::numeric_limits<uint64_t>::max() / 1024) bytes = value * 1024;
434        else if (key == "MemTotal:" && unit == "kB" && value <= std::numeric_limits<uint64_t>::max() / 1024) mem_total = value * 1024;
435    }
436    if (bytes == 0) return false;
437    const bool inactive_only = strata::core::mem_credit_inactive_only(std::getenv("STRATA_MEM_CREDIT_INACTIVE"));
438    // Account for the tightest cgroup ancestor limit when its normal mount is visible.
439    // This is a point-in-time guard, not a reservation against concurrent allocations.
440    std::ifstream groups(self_cgroup);
441    if (!groups) return false;
442    const std::filesystem::path root(cgroup_root);
443    bool v2 = false;
444    std::string v1_path;   // the memory controller's group (cgroup v1), when there is no v2 line
445    while (std::getline(groups, line)) {
446        if (line.rfind("0::/", 0) != 0) {
447            // v1: "N:controller[,controller]:/path"
448            const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1);
449            if (c2 == std::string::npos) continue;
450            std::istringstream ctl(line.substr(c1 + 1, c2 - c1 - 1));
451            for (std::string c; std::getline(ctl, c, ',');)
452                if (c == "memory") v1_path = line.substr(c2 + 1);
453            continue;
454        }
455        auto path = (root / line.substr(4)).lexically_normal();
456        if (path.string().rfind(root.string(), 0) != 0 || !std::filesystem::is_directory(path)) return false;
457        v2 = true;
458        while (path.string().rfind(root.string(), 0) == 0) {
459            std::ifstream limit_file(path / "memory.max"), current_file(path / "memory.current");
460            std::string limit;
461            uint64_t current = 0;
462            const bool readable = bool(limit_file >> limit) && bool(current_file >> current);
463            // The host's root cgroup has no memory.max; ordinary child groups must expose their limits.
464            if (!readable && !(path == root && !std::filesystem::exists(path / "memory.max") &&
465                               std::filesystem::exists(path / "cgroup.controllers"))) return false;
466            if (readable && limit != "max") {
467                try {
468                    size_t consumed = 0;
469                    const uint64_t cap = std::stoull(limit, &consumed);
470                    if (consumed != limit.size()) return false;
471                    CgroupMemoryStat stat;
472                    if (!read_cgroup_memory_stat(path, current, stat)) return false;
473                    uint64_t cgroup_available = 0;
474                    if (!cgroup_available_bytes(cap, stat, cgroup_available)) return false;
475                    // a container's limit: the memory guard's file-list credit (no shmem, no locked pages), this margin kept
476                    std::ifstream stat_file(path / "memory.stat");
477                    std::ostringstream stat_text;
478                    if (stat_file) stat_text << stat_file.rdbuf();
479                    const strata::core::ArenaCgroupRoom room =
480                        strata::core::arena_cgroup_room(cap, current, stat_text.str(), mem_total, inactive_only);
481                    if (room.applies) cgroup_available = room.room;
482                    bytes = std::min(bytes, cgroup_available);
483                    m.cgroup_limit = std::min(m.cgroup_limit, cap);
484                } catch (...) { return false; }
485            }
486            if (path == root) break;
487            path = path.parent_path();
488        }
489    }
490    if (!v2 && !v1_path.empty()) {
491        // #633: cgroup v1 (older Docker hosts, RHEL 7/8): the memory controller's group and its ancestors.  An
492        // unlimited group says a number near 2^63 (rounded to its page size); a group whose files are not
493        // visible (no mount in this namespace) is skipped - MemAvailable alone, as with no cgroup at all.
494        const std::filesystem::path mroot = root / "memory";
495        auto path = (mroot / v1_path.substr(v1_path.rfind('/', 0) == 0 ? 1 : 0)).lexically_normal();
496        while (path.string().rfind(mroot.string(), 0) == 0) {
497            std::ifstream limit_file(path / "memory.limit_in_bytes"), usage_file(path / "memory.usage_in_bytes");
498            uint64_t cap = 0, usage = 0;
499            if (limit_file >> cap && usage_file >> usage && cap < (1ull << 62)) {
500                bytes = std::min(bytes, usage < cap ? cap - usage : 0);
501                m.cgroup_limit = std::min(m.cgroup_limit, cap);
502            }
503            if (path == mroot) break;
504            path = path.parent_path();
505        }
506    }
507    m.available = bytes;
508    return true;
509#elif defined(__APPLE__)
510    // macOS: free + inactive + purgeable pages (what the OS can hand out without swapping), as vm_stat reports them
511    (void) meminfo; (void) self_cgroup; (void) cgroup_root;
512    vm_statistics64_data_t vs{};
513    mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
514    vm_size_t page_bytes = 0;
515    if (host_page_size(mach_host_self(), &page_bytes) != KERN_SUCCESS ||
516        host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &count) != KERN_SUCCESS) return false;
517    m.available = ((uint64_t) vs.free_count + vs.inactive_count + vs.purgeable_count) * (uint64_t) page_bytes;
518    return m.available > 0;
519#else
520    (void) meminfo; (void) self_cgroup; (void) cgroup_root;
521    const long pages = sysconf(_SC_AVPHYS_PAGES);
522    const long page_bytes = sysconf(_SC_PAGESIZE);
523    if (pages <= 0 || page_bytes <= 0 ||
524        (uint64_t) pages > std::numeric_limits<uint64_t>::max() / (uint64_t) page_bytes) return false;
525    m.available = (uint64_t) pages * (uint64_t) page_bytes;
526    return m.available > 0;
527#endif
528}
529
530}  // namespace detail
531
532namespace {
533
534bool available_memory_bytes(uint64_t& bytes, uint64_t* commit = nullptr) {
535    detail::HostMemory m;
536    if (!detail::host_available_memory(m)) return false;
537    bytes = m.available;
538    if (commit != nullptr) *commit = m.commit;
539    return bytes > 0;
540}
541
542/// #1250: the pages that are really free (MemFree), not the reclaimable cache MemAvailable counts; false when unknown.
543bool free_memory_bytes(uint64_t& bytes) {
544#if defined(__linux__)
545    std::ifstream info("/proc/meminfo");
546    if (!info) return false;
547    std::stringstream text;
548    text << info.rdbuf();
549    bytes = detail::meminfo_bytes(text.str(), "MemFree");
550    if (bytes == 0) return false;
551    // 0.1.42: a multi-socket host's nodes each have their own free pages; judge by the emptiest one too
552    std::vector<uint64_t> nodes;
553    for (int n = 0; n < 64; ++n) {
554        std::ifstream node("/sys/devices/system/node/node" + std::to_string(n) + "/meminfo");
555        if (!node) break;
556        std::string line;
557        while (std::getline(node, line)) {
558            std::istringstream f(line);
559            std::string a, id, key;
560            uint64_t kb = 0;
561            if (f >> a >> id >> key >> kb && key == "MemFree:") { nodes.push_back(kb * 1024); break; }
562        }
563    }
564    bytes = detail::numa_pin_free(bytes, nodes);
565    return bytes > 0;
566#else
567    bytes = 0;
568    return false;
569#endif
570}
571
572void log_complement_memory(const char* stage, uint64_t requested) {
573#if defined(_WIN32)
574    MEMORYSTATUSEX status{};
575    status.dwLength = sizeof(status);
576    if (!GlobalMemoryStatusEx(&status)) {
577        std::fprintf(stderr, "FileExpertSource: %s: GlobalMemoryStatusEx failed (error %lu)\n", stage, GetLastError());
578        return;
579    }
580    std::fprintf(stderr, "FileExpertSource: %s: requested %.2f GiB, available RAM %.2f GiB, available commit %.2f GiB "
581                         "(limit %.2f GiB), available virtual address space %.2f GiB\n",
582                 stage, (double) requested / 1073741824.0, (double) status.ullAvailPhys / 1073741824.0,
583                 (double) status.ullAvailPageFile / 1073741824.0, (double) status.ullTotalPageFile / 1073741824.0,
584                 (double) status.ullAvailVirtual / 1073741824.0);
585#else
586    (void) stage;
587    (void) requested;
588#endif
589}
590
591#if defined(__linux__)
592/// STRATA_NUMA_SPLIT step B: each NUMA slice of every complement slot (numa_slice_ranges) is first-touched by a helper
593/// thread pinned to one core of that slice's node, so the default local policy puts its pages there (no mbind: ~113k
594/// ranges would split the arena into more VMAs than vm.max_map_count allows).  Inactive (`place` false) unless the
595/// live pool split on real nodes; then the paced fault loop hands it each step to touch.
596struct NumaComplementPlacement {
597    bool place = false;
598    int nodes[2] = {-1, -1};
599    int core[2] = {-1, -1};
600    std::vector<std::pair<uint64_t, uint64_t>> ranges[2];   ///< page-aligned, sorted, coalesced, arena offsets
601    uint64_t slice_bytes[2] = {0, 0};
602    std::vector<uint64_t> free_before;                      ///< MemFree per node before the allocation
603    std::vector<uint64_t> free_after;                       ///< the same after the model files' pages are released
604    std::atomic<bool> pin_failed{false};
605    std::chrono::steady_clock::time_point t0;
606
607    static std::vector<uint64_t> node_free() {
608        // CBA: stops at the first missing node directory (as free_memory_bytes does), sparse node ids give a false
609        // "at risk 0.00" line only; list the node directory if a sparse-id host ever shows it
610        std::vector<uint64_t> out;
611        for (int n = 0; n < 64; ++n) {
612            std::ifstream node("/sys/devices/system/node/node" + std::to_string(n) + "/meminfo");
613            if (!node) break;
614            std::string line;
615            uint64_t kb = 0;
616            while (std::getline(node, line)) {
617                std::istringstream f(line);
618                std::string a, id, key;
619                if (f >> a >> id >> key >> kb && key == "MemFree:") break;
620                kb = 0;
621            }
622            out.push_back(kb * 1024);
623        }
624        return out;
625    }
626    static std::string free_text(const std::vector<uint64_t>& free) {
627        std::string s;
628        char buf[64];
629        for (size_t n = 0; n < free.size(); ++n) {
630            std::snprintf(buf, sizeof buf, "%snode %zu %.2f GiB", n ? ", " : "", n, (double) free[n] / 1073741824.0);
631            s += buf;
632        }
633        return s;
634    }
635
636    /// Decides from the live pool's plan; false with a logged reason when the split is on but placement cannot run.
637    void init(const std::vector<uint64_t>& offsets, int64_t n_expert, const std::vector<uint64_t>& blob_bytes,
638              const std::vector<uint64_t>& role_bytes) {
639        // relies on the pool being built first (generate.cpp: the ExpertPool at ~5632, the complement at ~7690)
640        const auto& plan = strata::kernels::cpu::active_numa_split();
641        if (!plan.on || plan.test) return;
642        free_before = node_free();
643        const char* why = nullptr;
644        if (role_bytes.size() != 3 * blob_bytes.size()) why = "this pack has no per-role byte sizes (not a GGUF-mapped native pack)";
645        for (size_t l = 0; why == nullptr && l < blob_bytes.size(); ++l)
646            if (role_bytes[3 * l] + role_bytes[3 * l + 1] + role_bytes[3 * l + 2] != blob_bytes[l])
647                why = "the role sizes do not add up to the expert blob";
648        for (int k = 0; why == nullptr && k < 2; ++k)
649            if (plan.cores[k].empty()) why = "a slice has no core";
650            else if (plan.nodes[k] < 0 || plan.nodes[k] >= 64) why = "a node id is out of range";
651        if (why != nullptr) {
652            std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: %s; the complement is placed by "
653                                 "first touch as usual (the split runs with remote reads)\n", why);
654            return;
655        }
656        for (int k = 0; k < 2; ++k) {
657            nodes[k] = plan.nodes[k];
658            core[k] = plan.cores[k].front();   // workers come before the host core in the plan
659            std::vector<std::pair<uint64_t, uint64_t>> all;
660            for (size_t i = 0; i < offsets.size(); ++i) {
661                if (offsets[i] == detail::kNoCacheComplement) continue;
662                const size_t l = i / (size_t) n_expert;
663                for (const auto& r : detail::numa_slice_ranges(offsets[i], &role_bytes[3 * l], k))
664                    if (r.second > r.first) all.push_back(r);
665            }
666            std::sort(all.begin(), all.end());
667            for (const auto& r : all) {   // coalesce: ends become monotonic, so a step finds its first range by bisection
668                if (!ranges[k].empty() && r.first <= ranges[k].back().second)
669                    ranges[k].back().second = std::max(ranges[k].back().second, r.second);
670                else ranges[k].push_back(r);
671            }
672            for (const auto& r : ranges[k]) slice_bytes[k] += r.second - r.first;
673        }
674        place = true;
675        t0 = std::chrono::steady_clock::now();
676        std::fprintf(stderr, "FileExpertSource: NUMA placement of the complement: slice 0 -> node %d (%.2f GiB, toucher "
677                             "CPU %d), slice 1 -> node %d (%.2f GiB, toucher CPU %d), 4 KiB pages; free before: %s\n",
678                     nodes[0], (double) slice_bytes[0] / 1073741824.0, core[0], nodes[1],
679                     (double) slice_bytes[1] / 1073741824.0, core[1], free_text(free_before).c_str());
680    }
681
682    /// Touches one byte per page of each slice's ranges clipped to [lo, hi), one pinned thread per slice; then the
683    /// calling thread touches the step's other pages (outside every slice: slot tails, the arena end).  The caller
684    /// must not re-touch slice pages: with automatic NUMA balancing on, its access faults would migrate them to its node.
685    void touch_step(uint8_t* arena, uint64_t lo, uint64_t hi) {
686        // CBA: two threads spawned per 1 GiB step (~50 spawns per start); long-lived touchers if the spawn ever shows
687        auto touch = [&](int k) {
688            cpu_set_t set;
689            CPU_ZERO(&set);
690            CPU_SET(core[k], &set);
691            if (sched_setaffinity(0, sizeof set, &set) != 0) pin_failed = true;
692            const auto& rs = ranges[k];
693            auto it = std::partition_point(rs.begin(), rs.end(), [&](const auto& r) { return r.second <= lo; });
694            for (; it != rs.end() && it->first < hi; ++it)
695                for (uint64_t at = std::max(it->first, lo); at < std::min(it->second, hi); at += 4096)
696                    ((volatile uint8_t*) arena)[at] = 0;
697        };
698        // CBA: a failed spawn terminates; fall back to an unpinned touch if it ever happens
699        std::thread a(touch, 0), b(touch, 1);
700        a.join();
701        b.join();
702        size_t c[2] = {0, 0};   // the pages no slice holds, as the default loop touches them
703        for (uint64_t at = lo; at < hi; at += 4096) {
704            bool covered = false;
705            for (int k = 0; k < 2; ++k) {
706                while (c[k] < ranges[k].size() && ranges[k][c[k]].second <= at) ++c[k];
707                covered = covered || (c[k] < ranges[k].size() && ranges[k][c[k]].first <= at);
708            }
709            if (!covered) ((volatile uint8_t*) arena)[at] = 0;
710        }
711    }
712
713    /// After the drop: a node whose free memory cannot take its slice plus `reserve_share` will spill to the other node
714    /// (no local reclaim); named up front, the 95 % check stays the verdict.
715    void check_room(uint64_t reserve_share) const {
716        for (int k = 0; k < 2; ++k) {
717            const uint64_t room = (size_t) nodes[k] < free_after.size() ? free_after[(size_t) nodes[k]] : 0;
718            if (room < slice_bytes[k] + reserve_share)
719                std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement at risk: node %d has %.2f GiB free for its "
720                                     "%.2f GiB slice plus %.2f GiB of reserve\n",
721                             nodes[k], (double) room / 1073741824.0, (double) slice_bytes[k] / 1073741824.0,
722                             (double) reserve_share / 1073741824.0);
723        }
724    }
725
726    /// Samples one page in 64 of each slice with move_pages (null node list: returns each page's node) and logs the
727    /// share on the intended node, once the arena is registered (its final state); `got < bytes` means the paced loop
728    /// stopped early, `registered < bytes` that the driver did not page-lock all of it: the placement then fails.
729    void report(const uint8_t* arena, uint64_t got, uint64_t registered, uint64_t bytes, const char* stop) const {
730        const double secs = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
731        uint64_t on_node[2] = {0, 0}, sampled[2] = {0, 0}, per_node[2][64] = {}, absent[2] = {0, 0};
732        constexpr int kNotSampled = -100000;   // outside any per-page status (a node id, or -errno)
733        int sys_errno[2] = {0, 0};              // first errno of a failed move_pages batch, per slice
734        size_t batches[2] = {0, 0}, failed[2] = {0, 0};
735        std::vector<void*> pages;
736        std::vector<int> status;
737        for (int k = 0; k < 2; ++k) {
738            uint64_t n = 0;
739            pages.clear();
740            for (const auto& r : ranges[k])
741                for (uint64_t at = r.first; at < r.second; at += 4096, ++n)
742                    if (n % 64 == 0) pages.push_back((void*) (arena + at));
743            status.assign(pages.size(), -1);
744            for (size_t b = 0; b < pages.size(); b += 4096) {
745                const size_t cnt = std::min<size_t>(4096, pages.size() - b);
746                ++batches[k];
747                if (syscall(SYS_move_pages, 0, (unsigned long) cnt, pages.data() + b, nullptr, status.data() + b, 0) != 0) {
748                    if (sys_errno[k] == 0) sys_errno[k] = errno;
749                    ++failed[k];
750                    for (size_t i = b; i < b + cnt; ++i) status[i] = kNotSampled;   // the syscall failed: no sample, unlike a page's own -errno
751                }
752            }
753            for (int s : status) {
754                if (s == kNotSampled) continue;
755                ++sampled[k];
756                if (s >= 0 && s < 64) ++per_node[k][s];
757                else ++absent[k];
758            }
759            on_node[k] = nodes[k] >= 0 && nodes[k] < 64 ? per_node[k][nodes[k]] : 0;
760        }
761        double share[2];
762        for (int k = 0; k < 2; ++k) share[k] = sampled[k] > 0 ? 100.0 * (double) on_node[k] / (double) sampled[k] : 0.0;
763        char what[2][96];   // a slice whose move_pages batches all failed has no share to print
764        for (int k = 0; k < 2; ++k) {
765            if (batches[k] > 0 && failed[k] == batches[k]) std::snprintf(what[k], sizeof what[k], "not verified");
766            else std::snprintf(what[k], sizeof what[k], "%.2f GiB (%.1f %% of its slices)",
767                               share[k] / 100.0 * (double) slice_bytes[k] / 1073741824.0, share[k]);
768        }
769        std::fprintf(stderr, "FileExpertSource: NUMA placement: node %d %s, node %d %s; free before: %s; after the drop: %s; "
770                             "pages taken and page-locked in %.1f s since the placement started\n",
771                     nodes[0], what[0], nodes[1], what[1], free_text(free_before).c_str(), free_text(free_after).c_str(), secs);
772        if (got < bytes)
773            std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: the paced loop stopped at %.2f of %.2f "
774                                 "GiB (%s); the rest is first-touched by unpinned copy threads (memory not placed on its node: the split runs with remote reads)\n",
775                         (double) got / 1073741824.0, (double) bytes / 1073741824.0, stop != nullptr ? stop : "?");
776        else if (registered < bytes)
777            std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: only %.2f of %.2f GiB page-locked (%s); "
778                                 "the unregistered pages can be migrated by NUMA balancing (memory not placed on its node: the split runs with remote reads)\n",
779                         (double) registered / 1073741824.0, (double) bytes / 1073741824.0, stop != nullptr ? stop : "?");
780        if (pin_failed)
781            std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement: a toucher could not be pinned to its core\n");
782        for (int k = 0; k < 2; ++k) {
783            if (batches[k] > 0 && failed[k] == batches[k]) {
784                std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement could not be verified: move_pages failed "
785                                     "(errno %d: %s) for slice %d (node %d)\n", sys_errno[k], std::strerror(sys_errno[k]), k, nodes[k]);
786                continue;
787            }
788            if (failed[k] > 0)
789                std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement: move_pages failed (errno %d: %s) for %zu of %zu "
790                                     "batches of slice %d; judged on the other samples\n", sys_errno[k],
791                             std::strerror(sys_errno[k]), failed[k], batches[k], k);
792            if (share[k] < 95.0)
793                std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: slice %d has %.1f %% of its pages "
794                                     "on node %d (< 95 %%; of %llu sampled: node %d %llu, node %d %llu, not present %llu)\n",
795                             k, share[k], nodes[k], (unsigned long long) sampled[k], nodes[0],
796                             (unsigned long long) per_node[k][nodes[0]], nodes[1], (unsigned long long) per_node[k][nodes[1]],
797                             (unsigned long long) absent[k]);
798        }
799    }
800};
801#endif
802
803/// #286: an unbuffered file handle - a HANDLE on Windows, an O_DIRECT descriptor (as a pointer-sized integer) on Linux.
804void close_direct(void* h) {
805#if defined(_WIN32)
806    CloseHandle((HANDLE) h);
807#else
808    ::close((int) (intptr_t) h);
809#endif
810}
811
812#if defined(__linux__)
813/// #3237: how fast this drive serves the experts' reads the two ways the file tier can take them - O_DIRECT preads of
814/// 1 MiB at random places on 8 threads (the unbuffered tier's I/O threads) against first touches of the pages of random
815/// 1 MiB pieces of a mapping on 3 threads (the cached tier: the pool's threads faulting the page cache in).  Regions the
816/// page cache already holds are skipped, and the probed ranges are dropped from the cache again.  The best of two
817/// rounds each; a few hundred MiB read, under two seconds per pass.  Done once per process.  false: not measurable.
818struct TierProbeResult { bool done = false, ok = false; double direct_bps = 0, cached_bps = 0; };
819
820bool file_tier_probe(const std::vector<std::string>& paths, double& direct_bps, double& cached_bps) {
821    static std::mutex mu;
822    static TierProbeResult memo;
823    std::lock_guard<std::mutex> lk(mu);
824    if (memo.done) { direct_bps = memo.direct_bps; cached_bps = memo.cached_bps; return memo.ok; }
825    memo.done = true;
826    const std::string* best = nullptr;
827    uint64_t size = 0;
828    for (const std::string& p : paths) {
829        struct stat st{};
830        if (::stat(p.c_str(), &st) == 0 && (uint64_t) st.st_size > size) { size = (uint64_t) st.st_size; best = &p; }
831    }
832    constexpr uint64_t kRegion = 1ull << 20;
833    constexpr int kPerPass = 96, kRounds = 2;
834    constexpr int kDirectThreads = 8, kCachedThreads = 3;
835    if (best == nullptr || size < 8ull * kPerPass * kRegion * 2) return false;
836    const int fd_d = ::open(best->c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC);
837    const int fd_b = ::open(best->c_str(), O_RDONLY | O_CLOEXEC);
838    void* map = fd_b >= 0 ? mmap(nullptr, (size_t) size, PROT_READ, MAP_SHARED, fd_b, 0) : MAP_FAILED;
839    auto cleanup = [&] {
840        if (map != MAP_FAILED) munmap(map, (size_t) size);
841        if (fd_d >= 0) ::close(fd_d);
842        if (fd_b >= 0) ::close(fd_b);
843    };
844    if (fd_d < 0 || map == MAP_FAILED) { cleanup(); return false; }
845    const uint8_t* base = static_cast<const uint8_t*>(map);
846    uint64_t seed = (uint64_t) std::chrono::steady_clock::now().time_since_epoch().count() * 6364136223846793005ull + 1442695040888963407ull;
847    std::vector<uint64_t> used;
848    auto pick = [&](std::vector<uint64_t>& out) {   // kPerPass distinct 1 MiB pieces the page cache does not hold
849        out.clear();
850        std::vector<unsigned char> vec(kRegion / 4096);
851        for (int tries = 0; (int) out.size() < kPerPass && tries < kPerPass * 40; ++tries) {
852            seed = seed * 6364136223846793005ull + 1442695040888963407ull;
853            const uint64_t off = ((seed >> 20) % (size / kRegion)) * kRegion;
854            if (std::find(used.begin(), used.end(), off) != used.end()) continue;
855            if (mincore((void*) (base + off), (size_t) kRegion, vec.data()) != 0) continue;
856            int res = 0;
857            for (unsigned char c : vec) res += c & 1;
858            if (res * 4 > (int) vec.size()) continue;
859            used.push_back(off);
860            out.push_back(off);
861        }
862        return (int) out.size() >= kPerPass / 2;
863    };
864    auto preadn = [&](uint8_t* dst, uint64_t off) {
865        uint64_t done = 0;
866        while (done < kRegion) {
867            const ssize_t r = ::pread(fd_d, dst + done, (size_t) (kRegion - done), (off_t) (off + done));
868            if (r < 0) { if (errno == EINTR) continue; return false; }
869            if (r == 0) return false;
870            done += (uint64_t) r;
871        }
872        return true;
873    };
874    double best_d = 0, best_c = 0;
875    bool ok = true;
876    for (int round = 0; round < kRounds && ok; ++round) {
877        for (int mode = 0; mode < 2 && ok; ++mode) {   // 0: direct, 1: cached
878            std::vector<uint64_t> offs;
879            if (!pick(offs)) { ok = false; break; }
880            std::atomic<size_t> next{0};
881            std::atomic<uint64_t> bytes{0};
882            std::atomic<int> failed{0};
883            const auto t0 = std::chrono::steady_clock::now();
884            const auto deadline = t0 + std::chrono::milliseconds(1500);
885            std::vector<std::thread> th;
886            const int nthreads = mode == 0 ? kDirectThreads : kCachedThreads;
887            for (int t = 0; t < nthreads; ++t) {
888                th.emplace_back([&] {
889                    void* buf = nullptr;
890                    if (mode == 0 && posix_memalign(&buf, 4096, kRegion) != 0) { failed = 1; return; }
891                    volatile uint8_t sink = 0;
892                    for (;;) {
893                        const size_t i = next.fetch_add(1);
894                        if (i >= offs.size() || std::chrono::steady_clock::now() > deadline) break;
895                        if (mode == 0) {
896                            if (!preadn((uint8_t*) buf, offs[i])) { failed = 1; break; }
897                        } else {
898                            for (uint64_t pg = 0; pg < kRegion; pg += 4096) sink = (uint8_t) (sink + base[offs[i] + pg]);
899                        }
900                        bytes.fetch_add(kRegion);
901                    }
902                    std::free(buf);
903                });
904            }
905            for (std::thread& x : th) x.join();
906            const double secs = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
907            if (failed.load() != 0 || bytes.load() == 0 || secs <= 0) { ok = false; break; }
908            const double bps = (double) bytes.load() / secs;
909            (mode == 0 ? best_d : best_c) = std::max(mode == 0 ? best_d : best_c, bps);
910            for (uint64_t off : offs) {   // leave the page cache as it was
911                (void) madvise((void*) (base + off), (size_t) kRegion, MADV_DONTNEED);
912                (void) posix_fadvise(fd_b, (off_t) off, (off_t) kRegion, POSIX_FADV_DONTNEED);
913            }
914        }
915    }
916    cleanup();
917    memo.ok = ok && best_d > 0 && best_c > 0;
918    memo.direct_bps = best_d;
919    memo.cached_bps = best_c;
920    direct_bps = best_d;
921    cached_bps = best_c;
922    return memo.ok;
923}
924#endif
925
926/// #286/#577: whether the file tier reads its `read_bytes` unbuffered, beside `arena_bytes` of RAM copy still to be
927/// taken.  Windows times probe reads too (experts_unbuffered); on Linux the same rule as its `cache_counts = false`
928/// arm decides: whether the file cache could keep those bytes at all, from MemAvailable and the tightest cgroup
929/// limit (host_available_memory).  STRATA_UNBUFFERED_LOAD=1 / 0 forces it either way, as on Windows.
930bool file_tier_unbuffered(const std::vector<std::string>& paths, uint64_t arena_bytes, uint64_t read_bytes,
931                          std::string& why) {
932#if defined(_WIN32)
933    return experts_unbuffered(paths, arena_bytes, why, /*cache_counts=*/false, read_bytes);
934#elif defined(__linux__)
935    (void) paths;
936    if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') {
937        why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
938        return env[0] != '0';
939    }
940    uint64_t avail = 0;
941    if (!available_memory_bytes(avail)) {
942        why = "the available RAM is unknown";
943        return false;
944    }
945    // The room the file cache can really have (on by default; STRATA_FILE_TIER_HONEST=0 turns it off; an I/O-path change only).  available_memory_bytes credits the group's whole `file`
946    // counter as reclaimable (cgroup_available_bytes), and on a RAM-budget config that credit includes pages the engine itself holds
947    // (P2003, v31, 22 GiB RAM copy: the room read 18.7 GiB while the group had limit 36 GiB, current 24.8 GiB, i.e. 11 GiB left).  The re-check
948    // after the copy then saw held >= 0.5, skipped the drive probe and switched the file tier to the cache: 2-3x slower prompts.  The
949    // conversation cache's sampler (only the clean inactive file cache is credited) is the honest figure; the smaller of the two decides.
950    // The operator cap (--memory-limit-mib) is NOT applied: it bounds the engine's own allocations, not the page cache (counting it sent IQ3_S
951    // unbuffered and cut its decode 2-3x).
952    if (const char* ho = std::getenv("STRATA_FILE_TIER_HONEST"); ho == nullptr || ho[0] != '0') {
953        if (const auto honest = strata::core::sample_host_memory(strata::core::MemoryProbePaths{}, 0); honest && honest->available < avail) avail = honest->available;
954    }
955    // #1194: the experts read from the files are a skewed set: a cache holding a twentieth of them (at least 1.5 GiB)
956    // serves most of the repeats, and beat the unbuffered reads at every room measured (it reads 2 to 7 times less from
957    // the drive).  `avail` already has what this process and the cgroup hold taken off, so 1 GiB is left for the rest.
958    // #1752 (KevinX8): ROCm queues are suspended while the kernel reclaims around the process's HMM-tracked arena
959    // (#1691) on an MI50 (gfx906): the cached reads churn the page cache and reclaim unmaps the arena, so the gfx906
960    // backend keeps the old room >= read_bytes rule.  Other HIP cards (gfx1201 measured: not affected) keep the new
961    // rule; STRATA_FILE_CACHE_OLD_RULE=1 / 0 forces the old rule on / off on any Linux build.
962    bool old_rule = false;
963#if defined(STRATA_HIP_GFX906)
964    old_rule = true;
965#endif
966    if (const char* r = std::getenv("STRATA_FILE_CACHE_OLD_RULE"); r != nullptr && r[0] != '\0') old_rule = r[0] != '0';
967    const bool keepable = old_rule
968        ? strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes)
969        : strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes, 1ull << 30, 0.05, 3ull << 29);
970    char msg[256];
971    std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB "
972                  "of experts read from the files: the file cache %s keep the ones that come back",
973                  (double) avail / (1ull << 30), (double) arena_bytes / (1ull << 30), (double) read_bytes / (1ull << 30),
974                  keepable ? "can" : "cannot");
975    why = msg;
976    // #3237: the room rule says the cache can keep the experts that come back, but when it holds under half of the read
977    // set, whether it pays depends on the drive: on a PCIe 5 NVMe (8 GB/s direct) the cached path read prompts at half
978    // the speed and decoded 3-4x slower than unbuffered reads, on a 1.7-2.5 GB/s NVMe the cache decodes faster.  So time
979    // both paths once at start and read unbuffered only when the drive is fast and serves direct reads clearly faster
980    // (platform::file_tier_prefers_direct).  STRATA_FILE_TIER_PROBE=0 keeps the room rule alone.
981    if (keepable && !old_rule && read_bytes > 0) {
982        const char* pe = std::getenv("STRATA_FILE_TIER_PROBE");
983        const uint64_t margin = 1ull << 30;
984        const double room = avail > arena_bytes + margin ? (double) (avail - arena_bytes - margin) : 0.0;
985        const double held = room / (double) read_bytes;
986        if (!(pe != nullptr && pe[0] == '0') && held < 0.5) {
987            double d = 0, c = 0;
988            char pm[256];
989            if (file_tier_probe(paths, d, c)) {
990                const bool direct = strata::platform::file_tier_prefers_direct(held, d, c);
991                std::snprintf(pm, sizeof pm, "; the cache holds %.0f%% of the read set, direct reads %.2f GB/s, cached-path reads "
992                              "%.2f GB/s (%.2fx): %s", held * 100.0, d / 1e9, c / 1e9, d / c,
993                              direct ? "the file tier reads unbuffered" : "the file cache stays");
994                why += pm;
995                return direct;
996            }
997            why += "; the drive probe could not run, the file cache stays";
998        }
999    }
1000    return !keepable;
1001#else
1002    (void) paths; (void) arena_bytes; (void) read_bytes;
1003    why = "through the file cache (no unbuffered reads on this platform)";
1004    return false;
1005#endif
1006}
1007
1008}  // namespace
1009
1010// ================================ THE FILE-BACKED SOURCE ================================
1011
1012FileExpertSource::~FileExpertSource() { close(); }
1013
1014#if defined(__linux__)
1015namespace {
1016/// Bytes of [p, p + n) whose pages are in the page cache (mincore, page-granular); 0 when the call fails.
1017uint64_t resident_in(const uint8_t* p, uint64_t n) {
1018    if (n == 0) return 0;
1019    static thread_local std::vector<unsigned char> vec;
1020    const uintptr_t a = (uintptr_t) p & ~(uintptr_t) 4095, e = ((uintptr_t) p + (uintptr_t) n + 4095) & ~(uintptr_t) 4095;
1021    vec.resize((size_t) ((e - a) / 4096));
1022    if (mincore((void*) a, (size_t) (e - a), vec.data()) != 0) return 0;
1023    uint64_t pages = 0;
1024    for (unsigned char c : vec) pages += c & 1;
1025    return std::min<uint64_t>(n, pages * 4096);
1026}
1027/// A cheap residency probe: the first, last and two inner pages; the bytes of the range when all four are cached, else 0.
1028uint64_t resident_sampled(const uint8_t* p, uint64_t n) {
1029    if (n == 0) return 0;
1030    const uintptr_t a = (uintptr_t) p & ~(uintptr_t) 4095, e = ((uintptr_t) p + (uintptr_t) n - 1) & ~(uintptr_t) 4095;
1031    const uintptr_t pages = (e - a) / 4096;
1032    const uintptr_t at[4] = {a, a + (pages / 3) * 4096, a + (pages * 2 / 3) * 4096, e};
1033    for (uintptr_t x : at) {
1034        unsigned char v = 0;
1035        if (mincore((void*) x, 4096, &v) != 0 || (v & 1) == 0) return 0;
1036    }
1037    return n;
1038}
1039bool resident_sampled_n(const uint8_t* p, uint64_t n) { return resident_sampled(p, n) >= n; }
1040/// The whole range with pread (a short read continues); false on an error or an end of file.
1041bool pread_full(int fd, uint8_t* dst, uint64_t n, uint64_t off) {
1042    uint64_t done = 0;
1043    while (done < n) {
1044        const ssize_t r = ::pread(fd, dst + done, (size_t) (n - done), (off_t) (off + done));
1045        if (r < 0) { if (errno == EINTR) continue; return false; }
1046        if (r == 0) return false;
1047        done += (uint64_t) r;
1048    }
1049    return true;
1050}
1051}  // namespace
1052#endif
1053
1054int FileExpertSource::spans(int64_t layer, int64_t expert, Span* out) const {
1055    if (layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return 0;
1056    if (!role_ptr_.empty()) {
1057        if (unmapped_) return 0;   // the GGUF views are closed (drop_mapping)
1058        uint64_t at = 0;
1059        for (int r = 0; r < 3; ++r) {
1060            const size_t i = (size_t) (3 * layer + r);
1061            const uint64_t per = role_bytes_[i];
1062            const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) expert * per);
1063            const size_t f = (size_t) role_file_[i];
1064            out[r] = {p, per, f < io_fds_.size() ? io_fds_[f] : -1, (uint64_t) (p - maps_[f].base), at};
1065            at += per;
1066        }
1067        return 3;
1068    }
1069    const uint8_t* b = mapped_blob(layer, expert);
1070    if (b == nullptr) return 0;
1071    out[0] = {b, layer_blob_bytes_[(size_t) layer], io_fds_.empty() ? -1 : io_fds_[0], (uint64_t) (b - base_), 0};
1072    return 1;
1073}
1074
1075uint64_t FileExpertSource::cached_bytes(int64_t layer, int64_t expert, uint64_t& total, bool exact) const {
1076    total = 0;
1077#if defined(__linux__)
1078    Span sp[3];
1079    const int ns = spans(layer, expert, sp);
1080    uint64_t res = 0;
1081    for (int i = 0; i < ns; ++i) {
1082        total += sp[i].n;
1083        res += exact ? resident_in(sp[i].p, sp[i].n) : resident_sampled(sp[i].p, sp[i].n);
1084    }
1085    return res;
1086#else
1087    (void) layer; (void) expert;
1088    return 0;
1089#endif
1090}
1091
1092FileExpertSource::IoCounters FileExpertSource::io_counters() const {
1093    IoCounters c;
1094    c.cached_bytes = io_cached_.load(std::memory_order_relaxed);
1095    c.uncached_bytes = io_uncached_.load(std::memory_order_relaxed);
1096    c.pread_bytes = io_pread_bytes_.load(std::memory_order_relaxed);
1097    c.pread_us = io_pread_us_.load(std::memory_order_relaxed);
1098    c.pread_n = io_pread_n_.load(std::memory_order_relaxed);
1099    c.pf_jobs = io_pf_jobs_.load(std::memory_order_relaxed);
1100    c.pf_demand = io_pf_demand_.load(std::memory_order_relaxed);
1101    c.pf_read_blobs = io_pf_blobs_.load(std::memory_order_relaxed);
1102    c.pf_resident_skips = io_pf_skips_.load(std::memory_order_relaxed);
1103    c.pf_dropped = io_pf_dropped_.load(std::memory_order_relaxed);
1104    c.pf_used = io_pf_used_.load(std::memory_order_relaxed);
1105    c.pf_unused = io_pf_unused_.load(std::memory_order_relaxed);
1106    c.crit_us = io_crit_us_.load(std::memory_order_relaxed);
1107    c.crit_n = io_crit_n_.load(std::memory_order_relaxed);
1108    c.pf_bytes = io_pf_bytes_.load(std::memory_order_relaxed);
1109    c.pf_used_bytes = io_pf_used_bytes_.load(std::memory_order_relaxed);
1110    c.pf_late = io_pf_late_.load(std::memory_order_relaxed);
1111    c.pf_rej_conf = io_pf_rej_conf_.load(std::memory_order_relaxed);
1112    c.pf_rej_budget = io_pf_rej_budget_.load(std::memory_order_relaxed);
1113    if (io_sched_) {
1114        std::lock_guard<std::mutex> lk(const_cast<std::mutex&>(io_mu_));
1115        c.pf_budget_bytes = io_budget_now();
1116    }
1117    return c;
1118}
1119
1120// 149-prefetch: the speculative bytes a decode window may read ahead.  Fixed (STRATA_IO_PF_BUDGET_MB), or what the workers
1121// measured they can read in one window (one worker's rate x the workers x the window's time) times STRATA_IO_PF_BUDGET_FRAC;
1122// 256 MB until both rates are known.
1123uint64_t FileExpertSource::io_budget_now() const {
1124    if (io_budget_fixed_ > 0) return io_budget_fixed_;
1125    if (io_bw_ <= 0.0 || io_win_us_ <= 0.0) return 256ull << 20;
1126    const double b = io_bw_ * (double) std::max(1, io_threads_) * io_win_us_ * io_budget_frac_ * io_scale_;
1127    return (uint64_t) std::max(16.0 * 1048576.0, b);
1128}
1129
1130void FileExpertSource::io_window_tick() {
1131    const auto now = std::chrono::steady_clock::now();
1132    std::lock_guard<std::mutex> lk(io_mu_);
1133    if (io_win_t0_.time_since_epoch().count() != 0) {
1134        const double us = std::chrono::duration<double, std::micro>(now - io_win_t0_).count();
1135        io_win_us_ = io_win_us_ <= 0.0 ? us : 0.8 * io_win_us_ + 0.2 * us;
1136    }
1137    io_win_t0_ = now;
1138    io_win_bytes_ = 0;
1139    // feedback: the share of the read-ahead bytes that a layer then used (the used count lags the reads by a window or
1140    // so; an EWMA over windows evens that out).  Below STRATA_IO_PF_TARGET the budget shrinks (x0.7 a window, to 1/20),
1141    // above it it grows back (x1.1, to 1): a box whose page cache cannot hold what is read ahead stops paying for it.
1142    const uint64_t pf = io_pf_bytes_.load(std::memory_order_relaxed), used = io_pf_used_bytes_.load(std::memory_order_relaxed);
1143    const uint64_t dpf = pf - io_prev_pf_, du = used - io_prev_used_;
1144    io_prev_pf_ = pf;
1145    io_prev_used_ = used;
1146    if (io_target_ > 0.0 && dpf > 0) {
1147        const double u = std::min(1.0, (double) du / (double) dpf);
1148        io_useful_ = io_useful_ < 0.0 ? u : 0.8 * io_useful_ + 0.2 * u;
1149        io_scale_ = io_useful_ < io_target_ ? std::max(0.05, io_scale_ * 0.7) : std::min(1.0, io_scale_ * 1.1);
1150    }
1151}
1152
1153// 149-prefetch: admit the predicted experts that are not resident.  An expert's bar is the base confidence, raised with
1154// the queue's fill against the window budget (a busy drive takes only the surer guesses); the window's speculative bytes
1155// stay within the budget; each job carries the layer clock by which it must have started (else the worker drops it).
1156void FileExpertSource::warm_scored(int64_t layer, const int64_t* experts, const float* conf, int64_t n, int ahead) {
1157    if (!io_sched_ || !io_pf_ || !direct_.empty() || !io_ahead_ || !gate_open()) { warm(layer, experts, n); return; }
1158    if (n <= 0 || layer < 0 || layer >= n_layers_) return;
1159    const uint64_t bytes = layer_blob_bytes_[(size_t) layer];
1160    const uint64_t deadline = io_epoch_.load(std::memory_order_relaxed) + (uint64_t) std::max(1, ahead);
1161    bool any = false;
1162    {
1163        std::lock_guard<std::mutex> lk(io_mu_);
1164        const uint64_t budget = io_budget_now();
1165        for (int64_t j = 0; j < n; ++j) {
1166            const int64_t e = experts[j];
1167            if (e < 0 || e >= n_expert_) continue;
1168            const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
1169            if (complement_ready_ && resident_blob(index) != nullptr) continue;   // in the RAM copy
1170            warm_count_.fetch_add(1, std::memory_order_relaxed);
1171            const double pressure = std::min(1.0, (double) io_q_bytes_ / (double) std::max<uint64_t>(1, budget));
1172            const double bar = (double) io_minconf_ + (1.0 - (double) io_minconf_) * pressure;
1173            const float c = conf != nullptr ? conf[j] : 1.0f;
1174            if ((double) c < bar) { io_pf_rej_conf_.fetch_add(1, std::memory_order_relaxed); continue; }
1175            if (io_win_bytes_ + bytes > budget) { io_pf_rej_budget_.fetch_add(1, std::memory_order_relaxed); continue; }
1176            bool dup = false;
1177            for (const IoJob& q : io_jobs_)
1178                if (q.layer == (int32_t) layer && q.expert == (int32_t) e) { dup = true; break; }
1179            if (dup) continue;
1180            io_jobs_.push_back({(int32_t) layer, (int32_t) e, c, deadline, bytes});
1181            io_q_bytes_ += bytes;
1182            io_win_bytes_ += bytes;
1183            any = true;
1184        }
1185    }
1186    if (any) io_cv_.notify_all();
1187}
1188
1189void FileExpertSource::set_io_prefetch(bool on, int threads) {
1190    io_stop();
1191    gate_on_ = false;   // the decode gate comes and goes with io prefetch
1192#if defined(__linux__)
1193    if (!on) return;
1194    if (base_ == nullptr || paths_.empty() || !direct_.empty()) return;   // unbuffered readers batch their own reads
1195    std::vector<int> fds;
1196    for (const std::string& path : paths_) {
1197        const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
1198        if (fd < 0) {
1199            for (int f : fds) ::close(f);
1200            return;
1201        }
1202        (void) posix_fadvise(fd, 0, 0, POSIX_FADV_RANDOM);   // read exactly the range asked for, no read-ahead beyond it
1203        fds.push_back(fd);
1204    }
1205    io_fds_ = std::move(fds);
1206    {
1207        std::lock_guard<std::mutex> lk(stage_mu_);
1208        for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
1209    }
1210    if (!warm_stamp_) warm_stamp_.reset(new std::atomic<uint32_t>[(size_t) (n_layers_ * n_expert_)]());
1211    io_threads_ = threads > 0 ? threads : 8;
1212    if (const char* v = std::getenv("STRATA_IO_PF_AHEAD")) io_ahead_ = std::atoi(v) != 0;
1213    {   // experts.bin: fill the page cache from the workers and let the kernels read the mapping (STRATA_IO_PF_STAGE=1: stage)
1214        const char* v = std::getenv("STRATA_IO_PF_STAGE");
1215        io_fill_ = role_ptr_.empty() && !(v != nullptr && std::atoi(v) != 0);
1216    }
1217    io_pf_ = true;
1218    io_stats_ = true;
1219    io_quit_ = false;
1220    {   // 149-prefetch: STRATA_IO_PF_SCHED=1 - deadlines, confidence admission and a per-window byte budget (off: as before)
1221        const char* v = std::getenv("STRATA_IO_PF_SCHED");
1222        io_sched_ = v != nullptr && std::atoi(v) != 0;
1223        if (const char* m = std::getenv("STRATA_IO_PF_MINCONF")) io_minconf_ = (float) std::clamp(std::atof(m), 0.0, 1.0);
1224        if (const char* m = std::getenv("STRATA_IO_PF_BUDGET_MB")) io_budget_fixed_ = (uint64_t) std::max(0.0, std::atof(m) * 1048576.0);
1225        if (const char* m = std::getenv("STRATA_IO_PF_BUDGET_FRAC")) io_budget_frac_ = std::clamp(std::atof(m), 0.01, 4.0);
1226        if (const char* m = std::getenv("STRATA_IO_PF_TARGET")) io_target_ = std::clamp(std::atof(m), 0.0, 1.0);
1227        gate_on_ = true;   // 0.2.0: the decode gate comes with io prefetch; STRATA_IO_PF_GATE=0 turns it off
1228        if (const char* m = std::getenv("STRATA_IO_PF_GATE"); m != nullptr && m[0] != '\0') gate_on_ = std::atoi(m) != 0;
1229        if (const char* m = std::getenv("STRATA_IO_PF_GATE_LO")) gate_lo_ = std::clamp(std::atof(m), 0.0, 1.0);
1230        if (const char* m = std::getenv("STRATA_IO_PF_GATE_HI")) gate_hi_ = std::clamp(std::atof(m), gate_lo_, 1.0);
1231        if (const char* m = std::getenv("STRATA_IO_PF_GATE_USEFUL")) gate_min_useful_ = std::clamp(std::atof(m), 0.0, 1.0);
1232    }
1233    if (!pf_mark_) {
1234        pf_mark_.reset(new std::atomic<uint8_t>[(size_t) (n_layers_ * n_expert_)]);
1235        for (int64_t i = 0; i < n_layers_ * n_expert_; ++i) pf_mark_[(size_t) i].store(0, std::memory_order_relaxed);
1236    }
1237    for (int i = 0; i < io_threads_; ++i) io_workers_.emplace_back([this] { io_worker(); });
1238#else
1239    (void) on; (void) threads;
1240#endif
1241}
1242
1243void FileExpertSource::io_stop() {
1244    {
1245        std::lock_guard<std::mutex> lk(io_mu_);
1246        io_quit_ = true;
1247        io_q_.clear();
1248        io_jobs_.clear();
1249        io_q_bytes_ = 0;
1250    }
1251    io_cv_.notify_all();
1252    for (std::thread& t : io_workers_)
1253        if (t.joinable()) t.join();
1254    io_workers_.clear();
1255#if defined(__linux__)
1256    for (int f : io_fds_) ::close(f);
1257#endif
1258    io_fds_.clear();
1259    io_pf_ = false;
1260    io_quit_ = false;
1261}
1262
1263void FileExpertSource::io_enqueue(int64_t layer, int64_t expert, bool ahead) {
1264    {
1265        std::lock_guard<std::mutex> lk(io_mu_);
1266        if (io_q_.size() >= 512) {   // the predictions run ahead of the reads: the oldest are the stalest
1267            io_q_.pop_front();
1268            io_pf_dropped_.fetch_add(1, std::memory_order_relaxed);
1269        }
1270        io_q_.emplace_back((int32_t) layer, (int32_t) expert | (ahead ? kIoAhead : 0));
1271    }
1272    io_cv_.notify_one();
1273}
1274
1275// A read-ahead worker: takes a predicted (layer, expert), skips it when its pages are cached or it is already
1276// staged, and otherwise reads the whole blob into a staging buffer (copy_from_files preads what is not cached).
1277void FileExpertSource::io_worker() {
1278    strata::platform::name_this_thread("strata-io");
1279    for (;;) {
1280        int32_t layer, expert;
1281        bool ahead = true;   // a prediction (marked for the used / unused count), not a layer's own demand read
1282        {
1283            std::unique_lock<std::mutex> lk(io_mu_);
1284            io_cv_.wait(lk, [&] { return io_quit_ || !io_q_.empty() || !io_jobs_.empty(); });
1285            if (io_quit_) return;
1286            if (io_sched_ && io_q_.empty() && !io_jobs_.empty()) {   // (the layers' own reads in io_q_ go first)
1287                // 149-prefetch: drop the jobs whose layer the decode has reached (its demand read covers them); then the
1288                // earliest deadline, the surest guess first among equals
1289                const uint64_t now = io_epoch_.load(std::memory_order_relaxed);
1290                size_t best = io_jobs_.size();
1291                for (size_t i = 0; i < io_jobs_.size();) {
1292                    if (io_jobs_[i].deadline <= now) {
1293                        io_q_bytes_ -= std::min(io_q_bytes_, io_jobs_[i].bytes);
1294                        io_jobs_[i] = io_jobs_.back();
1295                        io_jobs_.pop_back();
1296                        io_pf_late_.fetch_add(1, std::memory_order_relaxed);
1297                        continue;
1298                    }
1299                    ++i;
1300                }
1301                best = io_jobs_.size();
1302                for (size_t i = 0; i < io_jobs_.size(); ++i)
1303                    if (best == io_jobs_.size() || io_jobs_[i].deadline < io_jobs_[best].deadline ||
1304                        (io_jobs_[i].deadline == io_jobs_[best].deadline && io_jobs_[i].conf > io_jobs_[best].conf))
1305                        best = i;
1306                if (best == io_jobs_.size()) continue;   // all were late
1307                layer = io_jobs_[best].layer;
1308                expert = io_jobs_[best].expert;
1309                io_q_bytes_ -= std::min(io_q_bytes_, io_jobs_[best].bytes);
1310                io_jobs_[best] = io_jobs_.back();
1311                io_jobs_.pop_back();
1312            } else {
1313                if (io_q_.empty()) continue;
1314                layer = io_q_.back().first;   // the newest prediction first: it is the layer that comes next
1315                expert = io_q_.back().second & ~kIoAhead;
1316                ahead = (io_q_.back().second & kIoAhead) != 0;
1317                io_q_.pop_back();
1318            }
1319        }
1320        io_pf_jobs_.fetch_add(1, std::memory_order_relaxed);
1321        const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
1322        if (complement_ready_ && resident_blob(index) != nullptr) continue;
1323        if (!override_.empty() && override_[index] != nullptr) continue;
1324        const auto tjob = std::chrono::steady_clock::now();
1325        // 149-prefetch: one worker's read rate (bytes per microsecond), for the scheduler's window budget
1326        auto note_rate = [&](uint64_t b) {
1327            if (b == 0) return;
1328            const double us = std::max(1.0, std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - tjob).count());
1329            io_pf_bytes_.fetch_add(b, std::memory_order_relaxed);
1330            std::lock_guard<std::mutex> lk(io_mu_);
1331            const double r = (double) b / us;
1332            io_bw_ = io_bw_ <= 0.0 ? r : 0.9 * io_bw_ + 0.1 * r;
1333        };
1334        if (io_fill_) {   // read what is not cached into a scratch buffer: the pages stay in the page cache for the kernels
1335#if defined(__linux__)
1336            static thread_local std::vector<uint8_t> scratch;
1337            Span sp[3];
1338            const int ns = spans(layer, expert, sp);
1339            bool any = false;
1340            uint64_t got = 0;
1341            for (int i = 0; i < ns; ++i) {
1342                if (sp[i].fd < 0 || resident_sampled_n(sp[i].p, sp[i].n)) continue;
1343                if (scratch.size() < sp[i].n) scratch.resize((size_t) sp[i].n);
1344                const auto t0 = std::chrono::steady_clock::now();
1345                if (pread_full(sp[i].fd, scratch.data(), sp[i].n, sp[i].off)) {
1346                    io_pread_bytes_.fetch_add(sp[i].n, std::memory_order_relaxed);
1347                    io_pread_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
1348                                           std::memory_order_relaxed);
1349                    io_pread_n_.fetch_add(1, std::memory_order_relaxed);
1350                    any = true;
1351                    got += sp[i].n;
1352                }
1353            }
1354            if (any) {
1355                io_pf_blobs_.fetch_add(1, std::memory_order_relaxed);
1356                if (pf_mark_ && ahead) pf_mark_[index].store(1, std::memory_order_relaxed);   // read ahead: scored at the demand
1357                note_rate(got);
1358            }
1359            else io_pf_skips_.fetch_add(1, std::memory_order_relaxed);
1360#endif
1361            continue;
1362        }
1363        uint64_t total = 0;
1364        if (cached_bytes(layer, expert, total, false) >= total) {
1365            io_pf_skips_.fetch_add(1, std::memory_order_relaxed);
1366            continue;
1367        }
1368        size_t v = 0;
1369        bool fill = false;
1370        uint8_t* dst = nullptr;
1371        {
1372            std::lock_guard<std::mutex> lk(stage_mu_);
1373            if (stage_blob_ == 0) continue;
1374            const bool have = claim_stage((int64_t) layer * n_expert_ + expert, v, fill, /*ahead=*/true);
1375            if (have || !fill) continue;   // already staged or being read, or no buffer
1376            stage_pf_[v] = 1;
1377            dst = stage_buf_[v].get();
1378        }
1379        const bool ok = copy_from_files(layer, expert, dst);
1380        io_pf_blobs_.fetch_add(1, std::memory_order_relaxed);
1381        if (ok) file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
1382        if (ok) note_rate(layer_blob_bytes_[(size_t) layer]);
1383        {
1384            std::lock_guard<std::mutex> lk(stage_mu_);
1385            stage_busy_[v] = 0;
1386            if (!ok) {
1387                stage_of_.erase(stage_key_[v]);
1388                stage_key_[v] = -1;
1389                stage_pf_[v] = 0;
1390            }
1391        }
1392        stage_cv_.notify_all();
1393    }
1394}
1395
1396// The decode's hand-out of a blob in the experts.bin file tier with io prefetch on: what a layer's prediction read
1397// ahead is staged; a blob whose pages are all cached is the mapping itself (no copy); the rest is read with one
1398// pread into a staging buffer, not faulted in by the kernels one small request at a time.
1399const uint8_t* FileExpertSource::io_blob(int64_t layer, int64_t expert) {
1400    const int64_t key = layer * n_expert_ + expert;
1401    if (io_fill_) {
1402        const uint8_t* b = mapped_blob(layer, expert);
1403        if (b != nullptr) {
1404            const uint64_t total = layer_blob_bytes_[(size_t) layer];
1405            file_read_bytes_.fetch_add(total, std::memory_order_relaxed);
1406        }
1407        return b;
1408    }
1409    bool have;
1410    {
1411        std::lock_guard<std::mutex> lk(stage_mu_);
1412        have = stage_of_.find(key) != stage_of_.end();
1413    }
1414    if (!have) {
1415        // prefetch() (every decode layer calls it first) staged what was not cached: what is not staged is cached
1416        const uint8_t* b = mapped_blob(layer, expert);
1417        if (b != nullptr) {
1418            const uint64_t total = layer_blob_bytes_[(size_t) layer];
1419            io_cached_.fetch_add(total, std::memory_order_relaxed);
1420            file_read_bytes_.fetch_add(total, std::memory_order_relaxed);
1421            return b;
1422        }
1423    }
1424    return staged_blob(layer, expert);
1425}
1426
1427bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err) {
1428    close();
1429    if (n_layers <= 0 || n_expert <= 0) { err = "FileExpertSource: the geometry is empty"; return false; }
1430    const auto& layout = strata::kernels::cpu::expert_layout();
1431    if (layout.n_layers != n_layers || layout.n_expert != n_expert) {
1432        err = "FileExpertSource: the requested geometry does not match the loaded expert layout";
1433        return false;
1434    }
1435    if ((uint64_t) n_layers > (uint64_t) std::numeric_limits<int64_t>::max() / (uint64_t) n_expert) {
1436        err = "FileExpertSource: the expert count overflows";
1437        return false;
1438    }
1439    const uint64_t blob_count = (uint64_t) n_layers * (uint64_t) n_expert;
1440    if (blob_count > (uint64_t) std::numeric_limits<int64_t>::max() ||
1441        (uint64_t) n_layers > (uint64_t) std::numeric_limits<size_t>::max()) {
1442        err = "FileExpertSource: the expert count overflows";
1443        return false;
1444    }
1445
1446    std::vector<uint64_t> layer_offsets((size_t) n_layers), layer_blob_bytes((size_t) n_layers);
1447    const uint64_t want = layout.total;
1448    if (want == 0 || want > (uint64_t) std::numeric_limits<size_t>::max()) {
1449        err = "FileExpertSource: the loaded expert layout has an invalid size";
1450        return false;
1451    }
1452    if (!layout.native) {
1453        if (blob_count > std::numeric_limits<uint64_t>::max() / (uint64_t) strata::kernels::cpu::BLOB) {
1454            err = "FileExpertSource: the canonical expert size overflows";
1455            return false;
1456        }
1457        const uint64_t canonical_size = blob_count * (uint64_t) strata::kernels::cpu::BLOB;
1458        if (want != canonical_size) {
1459            err = "FileExpertSource: the canonical expert layout has an inconsistent size";
1460            return false;
1461        }
1462        const uint64_t bytes = (uint64_t) strata::kernels::cpu::BLOB;
1463        const uint64_t layer_bytes = (uint64_t) n_expert * bytes;
1464        for (int64_t layer = 0; layer < n_layers; ++layer) {
1465            layer_offsets[(size_t) layer] = (uint64_t) layer * layer_bytes;
1466            layer_blob_bytes[(size_t) layer] = bytes;
1467        }
1468    } else {
1469        if (layout.offset.size() != (size_t) n_layers || layout.bytes.size() != (size_t) n_layers ||
1470            layout.fmt.size() != (size_t) n_layers) {
1471            err = "FileExpertSource: the native expert layout is incomplete";
1472            return false;
1473        }
1474        uint64_t at = 0;
1475        for (int64_t layer = 0; layer < n_layers; ++layer) {
1476            const size_t i = (size_t) layer;
1477            const uint64_t bytes = (uint64_t) layout.fmt[i].bytes;
1478            if (layout.offset[i] != at || bytes == 0 || layout.bytes[i] != bytes ||
1479                bytes > std::numeric_limits<uint64_t>::max() / (uint64_t) n_expert) {
1480                err = "FileExpertSource: the native expert layout is invalid at layer " + std::to_string(layer);
1481                return false;
1482            }
1483            const uint64_t layer_bytes = bytes * (uint64_t) n_expert;
1484            if (at > want || layer_bytes > want - at) {
1485                err = "FileExpertSource: the native expert layout exceeds its declared size at layer " +
1486                      std::to_string(layer);
1487                return false;
1488            }
1489            layer_offsets[i] = layout.offset[i];
1490            layer_blob_bytes[i] = bytes;
1491            at += layer_bytes;
1492        }
1493        if (at != want) {
1494            err = "FileExpertSource: the native expert layout has an inconsistent size";
1495            return false;
1496        }
1497    }
1498    const std::string path = pack_dir + "/experts.bin";
1499    if (layout.native && !gguf_.empty() && !std::filesystem::exists(path)) {
1500        // CS-T: no experts.bin - the model's GGUF shards, read in place
1501        blobs_ = (int64_t) blob_count;
1502        n_layers_ = n_layers;
1503        n_expert_ = n_expert;
1504        layer_offsets_ = std::move(layer_offsets);
1505        layer_blob_bytes_ = std::move(layer_blob_bytes);
1506        if (!open_gguf(err)) { close(); return false; }
1507        record_inputs(path, gguf_, layout, true);
1508        return true;
1509    }
1510
1511#if defined(_WIN32)
1512    // UTF-8 -> UTF-16: the pack may live under a path with non-ASCII characters, and `CreateFileA` would
1513    // silently mangle it into a file-not-found.
1514    const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
1515    std::vector<wchar_t> wpath((size_t) (wide > 0 ? wide : 1));
1516    if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
1517    // **`FILE_FLAG_RANDOM_ACCESS` WAS HERE AND IT COST 14x.**
1518    //
1519    // The design depends on the OS page cache holding the whole 34 GB expert set, because this machine has
1520    // 64 GB of DDR5 and `L9` measured the CPU path at 44.14 GB/s from DRAM.  `FILE_FLAG_RANDOM_ACCESS` tells
1521    // the cache manager the opposite: it disables read-ahead AND it lets the manager drop the pages again
1522    // quickly, on the assumption that a large randomly-accessed file will not be re-read.  Measured, on
1523    // `strata generate --max-new 24`: **1.93 GB/s** - disk speed, 344 ms/token, and it never warmed up over 25
1524    // tokens, because the pages were being evicted as fast as they were faulted in.
1525    //
1526    // The correct flag is NO flag.  The access pattern IS random (10 of 512 experts per layer, a different 10
1527    // each layer), but every byte read is read again on the next token, so retention is the whole game.
1528    HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1529                           FILE_ATTRIBUTE_NORMAL, nullptr);
1530    if (f == INVALID_HANDLE_VALUE) {
1531        err = "FileExpertSource: cannot open " + path;
1532        return false;
1533    }
1534    LARGE_INTEGER sz{};
1535    if (!GetFileSizeEx(f, &sz)) {
1536        CloseHandle(f);
1537        err = "FileExpertSource: cannot size " + path;
1538        return false;
1539    }
1540    if ((uint64_t) sz.QuadPart != want) {
1541        char buf[400];
1542        std::snprintf(buf, sizeof buf,
1543                      "FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not "
1544                      "the pack this geometry came from",
1545                      path.c_str(), (unsigned long long) sz.QuadPart, (unsigned long long) want);
1546        CloseHandle(f);
1547        err = buf;
1548        return false;
1549    }
1550    HANDLE m = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr);
1551    if (m == nullptr) {
1552        CloseHandle(f);
1553        err = "FileExpertSource: CreateFileMapping failed on " + path;
1554        return false;
1555    }
1556    void* view = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0);
1557    if (view == nullptr) {
1558        CloseHandle(m);
1559        CloseHandle(f);
1560        err = "FileExpertSource: MapViewOfFile failed on " + path;
1561        return false;
1562    }
1563    file_ = f;
1564    mapping_ = m;
1565    base_ = (const uint8_t*) view;
1566    paths_.assign(1, path);
1567#else
1568    const int fd = ::open(path.c_str(), O_RDONLY);
1569    if (fd < 0) { err = "FileExpertSource: cannot open " + path; return false; }
1570    struct stat st{};
1571    if (fstat(fd, &st) != 0) { ::close(fd); err = "FileExpertSource: cannot stat " + path; return false; }
1572    if (st.st_size < 0 || (uint64_t) st.st_size != want) {
1573        char buf[400];
1574        std::snprintf(buf, sizeof buf,
1575                      "FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not "
1576                      "the pack this geometry came from",
1577                      path.c_str(), (unsigned long long) (st.st_size < 0 ? 0 : st.st_size),
1578                      (unsigned long long) want);
1579        ::close(fd);
1580        err = buf;
1581        return false;
1582    }
1583    void* view = mmap(nullptr, (size_t) want, PROT_READ, MAP_SHARED, fd, 0);
1584    if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: mmap failed on " + path; return false; }
1585    fd_ = fd;
1586    base_ = (const uint8_t*) view;
1587    paths_.assign(1, path);   // #286: open_direct opens it again with O_DIRECT
1588#endif
1589    blobs_ = (int64_t) blob_count;
1590    n_layers_ = n_layers;
1591    n_expert_ = n_expert;
1592    mapped_bytes_ = want;
1593    layer_offsets_ = std::move(layer_offsets);
1594    layer_blob_bytes_ = std::move(layer_blob_bytes);
1595    record_inputs(path, gguf_, layout, false);
1596    return true;
1597}
1598
1599void FileExpertSource::close() {
1600    prefetch_end();
1601    latent_io_stop();
1602    ram_stop();
1603    io_stop();
1604    inputs_.clear();
1605    if (complement_arena_ != nullptr) {
1606        if (complement_pinned_ && !complement_registered_) (void) cudaFreeHost(complement_arena_);
1607        else {
1608            if (complement_registered_) (void) cudaHostUnregister(complement_arena_);
1609            if (complement_locked_ > 0)
1610                strata::platform::unlock_resident((uint8_t*) complement_arena_ + complement_lock_off_, complement_locked_);
1611            std::free(complement_arena_);
1612        }
1613    }
1614    if (xstage_ != nullptr) {
1615        if (xstage_pinned_) (void) cudaFreeHost(xstage_);
1616        else std::free(xstage_);
1617    }
1618    xstage_ = nullptr;
1619    xstage_pinned_ = false;
1620    xstage_cap_ = 0;
1621    xstage_blob_ = 0;
1622    override_.clear();
1623    staged_.clear();
1624    exchange_storage_.clear();
1625    exchanges_ = 0;
1626    file_reads_.store(0);
1627    complement_arena_ = nullptr;
1628    complement_host_ = nullptr;
1629    complement_device_ = nullptr;
1630    complement_bytes_ = 0;
1631    complement_offsets_.clear();
1632    complement_pinned_ = false;
1633    complement_partial_ = false;
1634    complement_registered_ = false;
1635    complement_pin_limit_ = 0;
1636    complement_lock_off_ = 0;
1637    complement_ready_ = false;
1638    complement_locked_ = 0;
1639    complement_lent_slots_ = 0;
1640    if (!maps_.empty()) {
1641        for (Map& m : maps_) {
1642#if defined(_WIN32)
1643            if (m.base != nullptr && !m.closed) UnmapViewOfFile((LPCVOID) m.base);
1644            if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping);
1645            if (m.file != nullptr) CloseHandle((HANDLE) m.file);
1646#else
1647            if (m.base != nullptr && !m.closed) munmap((void*) m.base, (size_t) m.bytes);
1648            if (m.fd >= 0) ::close(m.fd);
1649#endif
1650        }
1651        maps_.clear();
1652        base_ = nullptr;   // one of the views above
1653        unmapped_ = false;
1654    }
1655    role_ptr_.clear();
1656    role_bytes_.clear();
1657    role_file_.clear();
1658    paths_.clear();
1659    for (void* h : direct_) close_direct(h);
1660    direct_.clear();
1661    for (void* h : pdirect_) close_direct(h);
1662    pdirect_.clear();
1663    {
1664        std::lock_guard<std::mutex> lk(stage_mu_);
1665        // the buffers' last copies end before they are freed (#1237)
1666        if (!stage_ev_.empty()) (void) cudaDeviceSynchronize();
1667        stage_free_events();
1668        stage_buf_.clear();
1669        stage_key_.clear();
1670        stage_epoch_.clear();
1671        stage_used_.clear();
1672        stage_busy_.clear();
1673        stage_pf_.clear();
1674        stage_of_.clear();
1675        stage_blob_ = 0;
1676        stage_seq_ = 0;
1677        epoch_ = 0;
1678        last_layer_ = -1;
1679        stage_grew_ = false;
1680    }
1681    ram_reads_.store(0);
1682    warm_stamp_.reset();
1683    warm_hits_.store(0);
1684    warm_count_.store(0);
1685    file_read_bytes_.store(0);
1686    file_blob_bytes_.store(0);
1687    file_us_.store(0);
1688    io_cached_.store(0); io_uncached_.store(0); io_pread_bytes_.store(0); io_pread_us_.store(0); io_pread_n_.store(0);
1689    io_pf_jobs_.store(0); io_pf_blobs_.store(0); io_pf_skips_.store(0); io_pf_dropped_.store(0);
1690    io_pf_used_.store(0); io_pf_unused_.store(0); io_crit_us_.store(0); io_crit_n_.store(0);
1691#if defined(_WIN32)
1692    if (base_ != nullptr && !unmapped_) UnmapViewOfFile((LPCVOID) base_);
1693    unmapped_ = false;
1694    if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_);
1695    if (file_ != nullptr) CloseHandle((HANDLE) file_);
1696    mapping_ = nullptr;
1697    file_ = nullptr;
1698#else
1699    if (base_ != nullptr) munmap((void*) base_, (size_t) mapped_bytes_);
1700    if (fd_ >= 0) ::close(fd_);
1701    fd_ = -1;
1702#endif
1703    base_ = nullptr;
1704    blobs_ = 0;
1705    n_layers_ = 0;
1706    n_expert_ = 0;
1707    mapped_bytes_ = 0;
1708    layer_offsets_.clear();
1709    layer_blob_bytes_.clear();
1710    reads_ = 0;
1711}
1712
1713
1714bool ExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
1715    const uint8_t* b = blob(layer, expert);
1716    if (b == nullptr || dst == nullptr) return false;
1717    std::memcpy(dst, b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(layer));
1718    return true;
1719}
1720
1721bool ExpertSource::copy_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n) {
1722    for (size_t i = 0; i < n; ++i)
1723        if (!copy_blob(layers[i], experts[i], dst[i])) return false;
1724    return true;
1725}
1726
1727// ================================ CS-T: THE GGUF SHARDS IN PLACE ================================
1728//
1729// A native pack without experts.bin: every file native_experts.txt names is mapped (MapViewOfFile / mmap, no
1730// flag - the same retention argument as experts.bin above), and an expert's blob [gate rows | up rows | down rows]
1731// is three slices of three tensors, possibly in two shards (UD-Q4_K_XL's layer 11).  Nothing is read at open; a
1732// blob is assembled when it is asked for (`blob`, into a small pool of buffers) or copied where it is needed
1733// (`copy_blob`: the RAM copy, the prompt path's pinned stager buffers).
1734bool FileExpertSource::open_gguf(std::string& err) {
1735    const auto& lay = strata::kernels::cpu::expert_layout();
1736    if (!check_experts_gguf(gguf_, lay, err)) { err = "FileExpertSource: " + err; return false; }
1737    const size_t cut = gguf_.find_last_of("/\\");
1738    const std::string dir = cut == std::string::npos ? std::string() : gguf_.substr(0, cut + 1);
1739    std::map<std::string, size_t> index;
1740    role_ptr_.assign((size_t) (3 * n_layers_), nullptr);
1741    role_bytes_.assign((size_t) (3 * n_layers_), 0);
1742    role_file_.assign((size_t) (3 * n_layers_), 0);
1743    for (int64_t l = 0; l < n_layers_; ++l) {
1744        const auto& fm = lay.fmt[(size_t) l];
1745        const uint64_t per[3] = {fm.up_off, fm.up_off, lay.bytes[(size_t) l] - fm.down_off};
1746        for (int r = 0; r < 3; ++r) {
1747            const size_t i = (size_t) (3 * l + r);
1748            const std::string path = lay.gguf_file.size() > i && !lay.gguf_file[i].empty() ? dir + lay.gguf_file[i]
1749                                                                                            : gguf_;
1750            auto it = index.find(path);
1751            if (it == index.end()) {
1752                Map m;
1753#if defined(_WIN32)
1754                const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
1755                std::vector<wchar_t> wpath((size_t) (wide > 0 ? wide : 1));
1756                if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
1757                HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1758                                       FILE_ATTRIBUTE_NORMAL, nullptr);
1759                LARGE_INTEGER sz{};
1760                if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx(f, &sz)) {
1761                    if (f != INVALID_HANDLE_VALUE) CloseHandle(f);
1762                    err = "FileExpertSource: cannot open " + path;
1763                    return false;
1764                }
1765                HANDLE mh = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr);
1766                void* view = mh != nullptr ? MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0) : nullptr;
1767                if (view == nullptr) {
1768                    if (mh != nullptr) CloseHandle(mh);
1769                    CloseHandle(f);
1770                    err = "FileExpertSource: cannot map " + path;
1771                    return false;
1772                }
1773                m.file = f;
1774                m.mapping = mh;
1775                m.bytes = (uint64_t) sz.QuadPart;
1776                m.base = (const uint8_t*) view;
1777#else
1778                const int fd = ::open(path.c_str(), O_RDONLY);
1779                struct stat st{};
1780                if (fd < 0 || fstat(fd, &st) != 0 || st.st_size <= 0) {
1781                    if (fd >= 0) ::close(fd);
1782                    err = "FileExpertSource: cannot open " + path;
1783                    return false;
1784                }
1785                void* view = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_SHARED, fd, 0);
1786                if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: cannot map " + path; return false; }
1787                m.fd = fd;
1788                m.bytes = (uint64_t) st.st_size;
1789                m.base = (const uint8_t*) view;
1790#endif
1791                maps_.push_back(m);
1792                paths_.push_back(path);
1793                it = index.emplace(path, maps_.size() - 1).first;
1794            }
1795            const Map& m = maps_[it->second];
1796            role_file_[i] = (int) it->second;
1797            const uint64_t at = lay.gguf_off[i], bytes = per[r] * (uint64_t) n_expert_;
1798            if (at > m.bytes || bytes > m.bytes - at) {   // check_experts_gguf proved it; the mapping must agree
1799                err = "FileExpertSource: an expert span runs past the end of " + path;
1800                return false;
1801            }
1802            role_ptr_[i] = m.base + (size_t) at;
1803            role_bytes_[i] = per[r];
1804        }
1805    }
1806    base_ = maps_.front().base;       // "opened"; mapped_blob answers nullptr in this mode
1807    warm_stamp_.reset(new std::atomic<uint32_t>[(size_t) (n_layers_ * n_expert_)]());
1808    for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
1809    return true;
1810}
1811
1812bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const {
1813    if (dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
1814    if (!direct_.empty()) {   // #286: from the drive; a failed read falls back to the mapping below
1815        const Fill f{0, layer, expert, dst};
1816        if (read_direct(&f, 1)) return true;
1817        direct_fallbacks_.fetch_add(1, std::memory_order_relaxed);
1818    }
1819#if defined(__linux__)
1820    if (io_pf_ || io_stats_) {   // count what the page cache holds; with io prefetch, read what it does not with pread
1821        Span sp[3];
1822        const int ns = spans(layer, expert, sp);
1823        for (int i = 0; i < ns; ++i) {
1824            const uint64_t res = resident_in(sp[i].p, sp[i].n);
1825            io_cached_.fetch_add(res, std::memory_order_relaxed);
1826            io_uncached_.fetch_add(sp[i].n - res, std::memory_order_relaxed);
1827            const bool dec = in_decode();
1828            if (gate_on_ && dec) {
1829                gate_c_.fetch_add(res, std::memory_order_relaxed);
1830                gate_u_.fetch_add(sp[i].n - res, std::memory_order_relaxed);
1831            }
1832            if (io_pf_ && res < sp[i].n && sp[i].fd >= 0 && !(dec && !gate_open())) {
1833                const auto t0 = std::chrono::steady_clock::now();
1834                const bool ok = pread_full(sp[i].fd, dst + sp[i].at, sp[i].n, sp[i].off);
1835                io_pread_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
1836                                       std::memory_order_relaxed);
1837                io_pread_n_.fetch_add(1, std::memory_order_relaxed);
1838                if (ok) {
1839                    io_pread_bytes_.fetch_add(sp[i].n, std::memory_order_relaxed);
1840                    continue;
1841                }
1842            }
1843            std::memcpy(dst + sp[i].at, sp[i].p, (size_t) sp[i].n);
1844        }
1845        if (ns > 0) return true;
1846    }
1847#endif
1848    if (!role_ptr_.empty()) {
1849        if (unmapped_) return false;   // drop_mapping closed the GGUF views: only the unbuffered reads remain
1850        uint64_t at = 0;
1851        for (int r = 0; r < 3; ++r) {
1852            const size_t i = (size_t) (3 * layer + r);
1853            const uint64_t per = role_bytes_[i];
1854            std::memcpy(dst + at, role_ptr_[i] + (size_t) ((uint64_t) expert * per), (size_t) per);
1855            at += per;
1856        }
1857        return true;
1858    }
1859    const uint8_t* b = mapped_blob(layer, expert);
1860    if (b == nullptr) return false;
1861    std::memcpy(dst, b, (size_t) layer_blob_bytes_[(size_t) layer]);
1862    return true;
1863}
1864
1865// Pinned stage buffers (PR 1237): opt-in (STRATA_STAGE_PIN=1).  On by default they corrupted IQ3_S decode after a 4096-token
1866// prompt in the 0.1.41 release gate (48 tokens of id 0; off = identical to 0.1.40.4): with page-locked buffers the cache-fill
1867// copy is truly asynchronous, so a recycled stage buffer can be overwritten before its copy finishes.  Off until that is fixed.
1868#define STAGE_PIN_DEFAULT 0
1869constexpr uint64_t kStagePinFloor = 3ull << 30;   // RAM left available after a pinned stage buffer
1870void FileExpertSource::StageBufFree::operator()(uint8_t* p) const noexcept {
1871    if (pinned) (void) cudaFreeHost(p);
1872    else delete[] p;
1873}
1874
1875// A blob assembled from the three role slices.  The buffer of a (layer, expert) is reused for another only once
1876// its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes
1877// first, and never while it is being filled: the pool computes a layer's misses before it starts the next, and a
1878// fill (the GPU cache at startup, an adaptive swap, a helper GPU) copies the blob right away.
1879//
1880// `claim_stage` finds or reserves the buffer of `key` (stage_mu_ held): true when the blob is already there (or
1881// being filled by another thread - the caller then waits), false when the caller must fill buffer `v`.
1882bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill, bool ahead) {
1883    constexpr uint64_t kStageSeq = 256;
1884    const uint64_t seq = ++stage_seq_;
1885    auto it = stage_of_.find(key);
1886    fill = false;
1887    if (it != stage_of_.end()) {
1888        v = it->second;
1889        stage_epoch_[v] = epoch_;
1890        stage_used_[v] = seq;
1891        if (!ahead && stage_pf_[v]) {   // a layer asked for what was read ahead
1892            stage_pf_[v] = 0;
1893            io_pf_used_.fetch_add(1, std::memory_order_relaxed);
1894            io_pf_used_bytes_.fetch_add(layer_blob_bytes_[(size_t) (key / n_expert_)], std::memory_order_relaxed);
1895        }
1896        return true;
1897    }
1898    v = stage_buf_.size();
1899    uint64_t oldest = std::numeric_limits<uint64_t>::max();
1900    for (size_t i = 0; i < stage_buf_.size(); ++i)
1901        if (!stage_busy_[i] && (stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) &&
1902            stage_used_[i] < oldest) {
1903            oldest = stage_used_[i];
1904            v = i;
1905        }
1906    if (v == stage_buf_.size()) {
1907        // Pinned, where the driver allows: a stage buffer is the source of the cache fill's cudaMemcpyAsync,
1908        // and a pageable source is staged through the driver's bounce buffer - an extra copy at a fraction of
1909        // the transfer rate, on the calling thread.  A failure falls back to pageable for this buffer.
1910        // STRATA_STAGE_PIN: 0 keeps them pageable (as before 0.1.41), 1 always tries to pin, unset (the default) pins while
1911        // the host has kStagePinFloor of RAM to spare beside this buffer (the pool grows to ~257 buffers, 0.4-0.6 GiB):
1912        // a low-RAM box keeps pageable ones instead of paying for the pinning (recommend, never force).
1913        static const int pin_mode = [] { const char* v = std::getenv("STRATA_STAGE_PIN"); return v == nullptr ? -1 : (std::atoi(v) != 0 ? 1 : 0); }();
1914        bool want_pin = pin_mode != 0;
1915        if (pin_mode < 0) {
1916            uint64_t avail = 0;
1917            want_pin = STAGE_PIN_DEFAULT && available_memory_bytes(avail) && avail >= (uint64_t) stage_blob_ + kStagePinFloor;
1918        }
1919        void* p = nullptr;
1920        cudaError_t pin_err = cudaSuccess;
1921        if (want_pin) pin_err = cudaHostAlloc(&p, (size_t) stage_blob_, cudaHostAllocDefault);
1922        const bool pinned = want_pin && pin_err == cudaSuccess && p != nullptr;
1923        if (!pinned) (void) cudaGetLastError();   // the failed alloc's sticky error is ours, not the caller's
1924        uint8_t* raw = pinned ? (uint8_t*) p : new (std::nothrow) uint8_t[(size_t) stage_blob_];
1925        if (raw == nullptr) return false;
1926        stage_buf_.emplace_back(raw, StageBufFree{pinned});
1927        stage_idx_[raw] = stage_buf_.size() - 1;
1928        stage_ev_.push_back(nullptr);
1929        stage_ev_live_.push_back(0);
1930        if (pinned && !stage_pin_said_) {
1931            stage_pin_said_ = true;
1932            std::fprintf(stderr, "FileExpertSource: the stage buffers are pinned (cudaHostAlloc)\n");
1933        } else if (!pinned && want_pin && !stage_pin_failed_said_) {
1934            stage_pin_failed_said_ = true;
1935            std::fprintf(stderr, "FileExpertSource: cudaHostAlloc failed for a stage buffer (%s) - pageable it is\n",
1936                         cudaGetErrorString(pin_err));
1937        }
1938        stage_key_.push_back(-1);
1939        stage_epoch_.push_back(0);
1940        stage_used_.push_back(0);
1941        stage_busy_.push_back(0);
1942        stage_pf_.push_back(0);
1943        if (stage_buf_.size() == 512 && !stage_grew_) {
1944            stage_grew_ = true;
1945            std::fprintf(stderr, "FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n",
1946                         stage_buf_.size(), (double) stage_buf_.size() * (double) stage_blob_ / 1073741824.0);
1947        }
1948    } else {
1949        stage_of_.erase(stage_key_[v]);
1950        if (stage_pf_[v]) { stage_pf_[v] = 0; io_pf_unused_.fetch_add(1, std::memory_order_relaxed); }   // read ahead, never asked for
1951        // #1237: a page-locked buffer is read by the DMA after the copy call returned: it is refilled only once the
1952        // last copy queued out of it (note_async_read) has finished.  Rare: the pool is sized so that a buffer asked
1953        // for has long been consumed; a wait here means the stream is more than a pool behind.
1954        if (v < stage_ev_live_.size() && stage_ev_live_[v]) {
1955            stage_ev_live_[v] = 0;
1956            if (stage_ev_[v] != nullptr) {
1957                if (cudaEventQuery((cudaEvent_t) stage_ev_[v]) == cudaErrorNotReady) {
1958                    stage_fence_waits_.fetch_add(1, std::memory_order_relaxed);
1959                    (void) cudaEventSynchronize((cudaEvent_t) stage_ev_[v]);
1960                }
1961                (void) cudaGetLastError();
1962            }
1963        }
1964    }
1965    stage_key_[v] = key;
1966    stage_epoch_[v] = epoch_;
1967    stage_used_[v] = seq;
1968    stage_busy_[v] = 1;
1969    stage_of_[key] = v;
1970    fill = true;
1971    if (reuse_on() && in_decode()) reuse_note(key);
1972    return false;
1973}
1974
1975bool FileExpertSource::reuse_on() {
1976    static const bool on = [] { const char* v = std::getenv("STRATA_FILE_REUSE"); return v != nullptr && std::atoi(v) != 0; }();
1977    return on;
1978}
1979
1980void FileExpertSource::reuse_note(int64_t key) {
1981    const size_t pairs = (size_t) (n_layers_ * n_expert_);
1982    if (reuse_last_.size() != pairs) { reuse_last_.assign(pairs, 0); reuse_reads_.assign(pairs, 0); }
1983    if (key < 0 || (size_t) key >= pairs) return;
1984    const uint32_t last = reuse_last_[(size_t) key];
1985    size_t b = 7;   // never read before
1986    if (last != 0) {
1987        const uint32_t gap = reuse_window_ - (last - 1);
1988        b = gap == 0 ? 0 : gap == 1 ? 1 : gap == 2 ? 2 : gap <= 4 ? 3 : gap <= 8 ? 4 : gap <= 16 ? 5 : 6;
1989    }
1990    ++reuse_hist_[b];
1991    reuse_last_[(size_t) key] = reuse_window_ + 1;
1992    ++reuse_reads_[(size_t) key];
1993}
1994
1995std::string FileExpertSource::reuse_report() {
1996    if (!reuse_on()) return {};
1997    std::lock_guard<std::mutex> lk(stage_mu_);
1998    uint64_t reads = 0;
1999    for (const uint64_t h : reuse_hist_) reads += h;
2000    if (reads == 0 || n_layers_ <= 0 || n_expert_ <= 0) return {};
2001    const double gb = (double) expert_bytes() / (double) (n_layers_ * n_expert_) / 1e9;   // mean blob
2002    const uint32_t windows = reuse_window_ - reuse_window0_;
2003    std::vector<uint32_t> per;
2004    for (const uint32_t r : reuse_reads_) if (r != 0) per.push_back(r);
2005    std::sort(per.begin(), per.end(), std::greater<uint32_t>());
2006    auto top = [&](size_t n) {
2007        uint64_t s = 0;
2008        for (size_t i = 0; i < n && i < per.size(); ++i) s += per[i];
2009        return (double) s * gb;
2010    };
2011    const auto& h = reuse_hist_;
2012    char b[640];
2013    std::snprintf(b, sizeof b,
2014                  "file reuse: %llu decode reads (%.1f GB) over %u windows, %zu distinct pairs (%.1f GB); windows since "
2015                  "the same expert's last read: 0 %llu, 1 %llu, 2 %llu, 3-4 %llu, 5-8 %llu, 9-16 %llu, >16 %llu, first %llu; "
2016                  "re-reads within 1/2/4/8 windows %.1f/%.1f/%.1f/%.1f GB; most-read 240/480/960 pairs %.1f/%.1f/%.1f GB",
2017                  (unsigned long long) reads, (double) reads * gb, windows, per.size(), (double) per.size() * gb,
2018                  (unsigned long long) h[0], (unsigned long long) h[1], (unsigned long long) h[2], (unsigned long long) h[3],
2019                  (unsigned long long) h[4], (unsigned long long) h[5], (unsigned long long) h[6], (unsigned long long) h[7],
2020                  (double) (h[0] + h[1]) * gb, (double) (h[0] + h[1] + h[2]) * gb, (double) (h[0] + h[1] + h[2] + h[3]) * gb,
2021                  (double) (h[0] + h[1] + h[2] + h[3] + h[4]) * gb, top(240), top(480), top(960));
2022    reuse_hist_ = {};
2023    std::fill(reuse_reads_.begin(), reuse_reads_.end(), 0);
2024    reuse_window0_ = reuse_window_;
2025    return b;
2026}
2027
2028// 149 STRATA_IO_PF_GATE: whether this thread reads for the decode (the dispatch's thread, and the fetch threads it starts)
2029namespace { thread_local bool tl_decode = false; }
2030FileExpertSource::DecodeScope::DecodeScope() : prev(tl_decode) { tl_decode = true; }
2031FileExpertSource::DecodeScope::~DecodeScope() { tl_decode = prev; }
2032bool FileExpertSource::in_decode() { return tl_decode; }
2033
2034// once a decode window: the share of the window's demand bytes the page cache held, an EWMA, and the gate's state
2035void FileExpertSource::gate_tick() {
2036    if (!gate_on_) return;
2037    const uint64_t c = gate_c_.load(std::memory_order_relaxed), u = gate_u_.load(std::memory_order_relaxed);
2038    const uint64_t dc = c - gate_prev_c_, du = u - gate_prev_u_;
2039    gate_prev_c_ = c;
2040    gate_prev_u_ = u;
2041    if (dc + du < (64ull << 20)) {   // too few bytes read this window to judge; the state stays
2042        if (!gate_open_.load(std::memory_order_relaxed)) ++gate_closed_w_;
2043        return;
2044    }
2045    const double h = (double) dc / (double) (dc + du);
2046    gate_ewma_ = gate_ewma_ < 0.0 ? h : 0.8 * gate_ewma_ + 0.2 * h;   // reported only
2047    if (!gate_open_.load(std::memory_order_relaxed)) ++gate_closed_w_;
2048}
2049
2050namespace {
2051// The room the page cache has for the experts: in a memory-limited cgroup (v2; the tightest limit of the group and its
2052// ancestors) the limit less what is not page cache (the group's memory.current - its "file" pages); otherwise
2053// MemAvailable (free + reclaimable cache).  0 when unknown.
2054uint64_t gate_cache_room() {
2055#if defined(__linux__)
2056    auto read_u64 = [](const std::string& path, uint64_t& v) {
2057        std::ifstream f(path);
2058        std::string s;
2059        if (!(f >> s) || s == "max") return false;
2060        v = std::strtoull(s.c_str(), nullptr, 10);
2061        return v > 0;
2062    };
2063    std::string rel;
2064    {
2065        std::ifstream g("/proc/self/cgroup");
2066        std::string line;
2067        while (std::getline(g, line))
2068            if (line.rfind("0::", 0) == 0) { rel = line.substr(3); break; }
2069    }
2070    uint64_t best = 0;
2071    if (!rel.empty()) {
2072        const std::string base = "/sys/fs/cgroup";
2073        for (std::string at = rel;; ) {
2074            const std::string dir = base + (at == "/" ? std::string() : at);
2075            uint64_t mx = 0, cur = 0, file = 0;
2076            if (read_u64(dir + "/memory.max", mx) && read_u64(dir + "/memory.current", cur)) {
2077                std::ifstream st(dir + "/memory.stat");
2078                std::string k;
2079                uint64_t v = 0;
2080                while (st >> k >> v)
2081                    if (k == "file") { file = v; break; }
2082                const uint64_t used = cur > file ? cur - file : 0;
2083                const uint64_t room = mx > used ? mx - used : 0;
2084                if (best == 0 || room < best) best = room;
2085            }
2086            if (at.empty() || at == "/") break;
2087            const size_t cut = at.find_last_of('/');
2088            at = cut == 0 || cut == std::string::npos ? std::string("/") : at.substr(0, cut);
2089        }
2090    }
2091    if (best > 0) return best;
2092    std::ifstream info("/proc/meminfo");
2093    std::stringstream text;
2094    text << info.rdbuf();
2095    return detail::meminfo_bytes(text.str(), "MemAvailable");
2096#else
2097    return 0;
2098#endif
2099}
2100}
2101
2102double FileExpertSource::cache_room_ratio() const {
2103    const uint64_t total = expert_bytes(), room = gate_cache_room();
2104    return total == 0 || room == 0 ? 0.0 : (double) room / (double) total;
2105}
2106
2107void FileExpertSource::gate_capacity() {
2108    if (!gate_on_ || (gate_win_++ % 16) != 0) return;
2109    const uint64_t total = expert_bytes(), room = gate_cache_room();
2110    if (total == 0 || room == 0) return;   // unknown: the state stays
2111    gate_ratio_ = (double) room / (double) total;
2112    // and the read-ahead must pay: the share of its bytes a layer then used, over these 16 windows (64 MB at least read
2113    // ahead to judge).  Below STRATA_IO_PF_GATE_USEFUL (0.10) it closes (a RAM tier holds what it would read: an 18 GiB
2114    // RAM tier, 0% used, -9..-15% decode); closed for that reason, it opens again for a probe every 256 windows.
2115    const uint64_t pf = io_pf_bytes_.load(std::memory_order_relaxed), used = io_pf_used_bytes_.load(std::memory_order_relaxed);
2116    const uint64_t dpf = pf - gate_prev_pf_, dused = used - gate_prev_used_;
2117    gate_prev_pf_ = pf;
2118    gate_prev_used_ = used;
2119    if (dpf >= (64ull << 20)) gate_useful_ = (double) dused / (double) dpf;
2120    const bool open = gate_open_.load(std::memory_order_relaxed);
2121    const bool room_ok = open ? gate_ratio_ >= gate_lo_ : gate_ratio_ > gate_hi_;
2122    bool want = room_ok;
2123    // too little to read ahead (< 128 MB in 16 windows: the RAM and VRAM tiers hold what is predicted) costs the look-ahead's
2124    // second layer and the I/O threads for nothing (an 18 GiB RAM tier: 2.5 GB read ahead in a run, -9..-16% decode)
2125    if (room_ok && open && gate_win_ > 16 && (dpf < (128ull << 20) || gate_useful_ < gate_min_useful_)) {
2126        want = false;
2127        gate_useless_ = true;
2128        gate_useless_since_ = gate_win_;
2129    } else if (room_ok && !open && gate_useless_) {
2130        want = gate_win_ - gate_useless_since_ >= 256;   // the probe
2131        if (want) gate_useless_ = false;
2132    }
2133    if (!room_ok) gate_useless_ = false;
2134    if (want != open) { gate_open_.store(want, std::memory_order_relaxed); ++gate_flips_; }
2135}
2136
2137// Fills buffer `v` (reserved by claim_stage) outside the lock, then publishes it.
2138bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst) {
2139    const auto t0 = std::chrono::steady_clock::now();
2140    const bool ok = copy_from_files(layer, expert, dst);
2141    publish_stage(v, layer, ok, std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count());
2142    return ok;
2143}
2144
2145void FileExpertSource::publish_stage(size_t v, int64_t layer, bool ok, double us) {
2146    file_us_.fetch_add((uint64_t) us, std::memory_order_relaxed);
2147    if (ok) {
2148        file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
2149        file_blob_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
2150    }
2151    {
2152        std::lock_guard<std::mutex> lk(stage_mu_);
2153        stage_busy_[v] = 0;
2154        if (!ok) {
2155            stage_of_.erase(stage_key_[v]);
2156            stage_key_[v] = -1;
2157        }
2158    }
2159    stage_cv_.notify_all();
2160}
2161
2162void FileExpertSource::note_async_read(const uint8_t* blob, void* stream) {
2163    if (blob == nullptr) return;
2164    std::lock_guard<std::mutex> lk(stage_mu_);
2165    const auto it = stage_idx_.find(blob);
2166    if (it == stage_idx_.end()) return;                 // not a stage buffer: the mapping or the resident arena
2167    const size_t v = it->second;
2168    if (!stage_buf_[v].get_deleter().pinned) return;    // pageable: the driver copied it before the call returned
2169    if (stage_ev_[v] == nullptr) {
2170        cudaEvent_t ev = nullptr;
2171        if (cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) != cudaSuccess) {
2172            (void) cudaGetLastError();
2173            (void) cudaStreamSynchronize((cudaStream_t) stream);   // no event: wait for the copy itself
2174            return;
2175        }
2176        stage_ev_[v] = ev;
2177    }
2178    if (cudaEventRecord((cudaEvent_t) stage_ev_[v], (cudaStream_t) stream) != cudaSuccess) {
2179        (void) cudaGetLastError();
2180        (void) cudaStreamSynchronize((cudaStream_t) stream);
2181        return;
2182    }
2183    stage_ev_live_[v] = 1;
2184}
2185
2186void FileExpertSource::stage_free_events() {
2187    for (void*& e : stage_ev_)
2188        if (e != nullptr) { (void) cudaEventDestroy((cudaEvent_t) e); e = nullptr; }
2189    stage_ev_.clear();
2190    stage_ev_live_.clear();
2191    stage_idx_.clear();
2192}
2193
2194const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) {
2195    const int64_t key = layer * n_expert_ + expert;
2196    size_t v = 0;
2197    bool fill = false;
2198    uint8_t* dst = nullptr;
2199    const auto t0 = std::chrono::steady_clock::now();
2200    auto crit = [&] {
2201        if (!io_pf_) return;
2202        io_crit_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
2203                              std::memory_order_relaxed);
2204        io_crit_n_.fetch_add(1, std::memory_order_relaxed);
2205    };
2206    {
2207        std::unique_lock<std::mutex> lk(stage_mu_);
2208        const bool have = claim_stage(key, v, fill);
2209        if (!have && !fill) return nullptr;
2210        dst = stage_buf_[v].get();
2211        if (have) {
2212            // another thread (a prefetch, the adaptive tier) is filling it: wait for that
2213            stage_cv_.wait(lk, [&] { return !stage_busy_[v] || stage_key_[v] != key; });
2214            if (stage_key_[v] != key) return nullptr;   // its fill failed
2215            lk.unlock();
2216            crit();
2217            return dst;
2218        }
2219    }
2220    const bool ok = fill_stage(v, layer, expert, dst);
2221    crit();
2222    return ok ? dst : nullptr;
2223}
2224
2225void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n) {
2226    if (!staged() || n <= 0 || layer < 0 || layer >= n_layers_) return;
2227    if (io_fill_ && io_pf_ && direct_.empty()) {   // hand the layer's uncached blobs to the workers and go on: the kernels
2228        for (int64_t i = 0; i < n; ++i) {          // that reach one before it lands wait on its pages, the rest compute
2229            const int64_t e = experts[i];
2230            if (e < 0 || e >= n_expert_) continue;
2231            const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
2232            if (pf_mark_ && pf_mark_[index].exchange(0, std::memory_order_relaxed)) {   // 149-prefetch: read ahead, now asked for
2233                io_pf_used_.fetch_add(1, std::memory_order_relaxed);
2234                io_pf_used_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
2235            }
2236            if (complement_ready_ && resident_blob(index) != nullptr) continue;
2237            if (!override_.empty() && override_[index] != nullptr) continue;
2238            uint64_t total = 0;
2239            if (cached_bytes(layer, e, total, false) >= total) continue;
2240            io_pf_demand_.fetch_add(1, std::memory_order_relaxed);
2241            io_enqueue(layer, e);
2242        }
2243        return;
2244    }
2245    std::vector<Fill> todo;
2246    const auto t0 = std::chrono::steady_clock::now();
2247    claim_todo(layer, experts, n, todo, nullptr);
2248    fill_many(todo);
2249    if (io_pf_ && !todo.empty()) {
2250        io_crit_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
2251                              std::memory_order_relaxed);
2252        io_crit_n_.fetch_add(1, std::memory_order_relaxed);
2253    }
2254}
2255
2256void FileExpertSource::claim_todo(int64_t layer, const int64_t* experts, int64_t n, std::vector<Fill>& todo, uint8_t* pending,
2257                                  bool zc) {
2258    // 149-cold mode 3: the GGUF in place, mapped and buffered: an expert the page cache holds whole is computed from
2259    // the mapping (its three tensors' rows), not assembled into a stage buffer first.  Decided here, before the lock.
2260    zc_keys_.clear();
2261    std::vector<char> zc_ok;
2262    if (zc && !role_ptr_.empty() && !unmapped_ && direct_.empty() && strata::kernels::cpu::expert_layout().native &&
2263        strata::kernels::cpu::expert_layout().fmt[(size_t) layer].tail_off == 0) {
2264        zc_ok.assign((size_t) n, 0);
2265        for (int64_t i = 0; i < n; ++i) {
2266            const int64_t e = experts[i];
2267            if (e < 0 || e >= n_expert_) continue;
2268            const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
2269            if (complement_ready_ && resident_blob(index) != nullptr) continue;   // in the RAM copy: no residency query
2270            if (!override_.empty() && override_[index] != nullptr) continue;
2271            uint64_t total = 0;
2272            const uint64_t c = cached_bytes(layer, e, total, true);
2273            zc_ok[(size_t) i] = total > 0 && c >= total ? 1 : 0;   // no residency query (not Linux): never
2274        }
2275    }
2276    // experts.bin with io prefetch: a blob whose pages are cached is handed out as the mapping (io_blob); only the
2277    // uncached ones are read here, together, on the fetch threads
2278    const bool only_uncached = io_pf_ && role_ptr_.empty() && direct_.empty();
2279    std::vector<char> cold;
2280    if (only_uncached) {
2281        cold.assign((size_t) n, 0);
2282        for (int64_t i = 0; i < n; ++i) {
2283            const int64_t e = experts[i];
2284            if (e < 0 || e >= n_expert_) continue;
2285            uint64_t total = 0;
2286            cold[(size_t) i] = cached_bytes(layer, e, total, false) < total ? 1 : 0;
2287        }
2288    }
2289    {
2290        std::lock_guard<std::mutex> lk(stage_mu_);
2291        for (int64_t i = 0; i < n; ++i) {
2292            const int64_t e = experts[i];
2293            if (e < 0 || e >= n_expert_) continue;
2294            const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
2295            if (complement_ready_ && resident_blob(index) != nullptr)
2296                continue;                                     // in the RAM copy
2297            if (!override_.empty() && override_[index] != nullptr) continue;
2298            if (only_uncached && !cold[(size_t) i] && stage_of_.find(layer * n_expert_ + e) == stage_of_.end()) continue;
2299            if (!zc_ok.empty() && zc_ok[(size_t) i] && stage_of_.find(layer * n_expert_ + e) == stage_of_.end()) {
2300                zc_keys_.push_back(layer * n_expert_ + e);   // read from the mapping by the kernels themselves
2301                continue;
2302            }
2303            size_t v = 0;
2304            bool fill = false;
2305            if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) {
2306                todo.push_back({v, layer, e, stage_buf_[v].get()});
2307                if (pending != nullptr) pending[i] = 1;
2308                if (warm_stamp_) {
2309                    const uint32_t s = warm_stamp_[index].load(std::memory_order_relaxed);
2310                    if (s != 0 && (uint64_t) s + 3 >= epoch_ + 1) warm_hits_.fetch_add(1, std::memory_order_relaxed);
2311                }
2312            } else if (pending != nullptr && fill == false) {
2313                // being filled by another thread (a read ahead, the adaptive tier): not ready yet either
2314                const auto it = stage_of_.find(layer * n_expert_ + e);
2315                if (it != stage_of_.end() && stage_busy_[it->second]) pending[i] = 1;
2316            }
2317        }
2318    }
2319}
2320
2321// 149-cold STRATA_COLD_OVERLAP=1: the claimed blobs are read on background threads (the decode thread computes the
2322// ready experts meanwhile); the same reads as fill_many, on as many threads, each blob published as it lands.
2323int64_t FileExpertSource::prefetch_begin(int64_t layer, const int64_t* experts, int64_t n, uint8_t* pending) {
2324    for (int64_t i = 0; i < n; ++i) pending[i] = 0;
2325    if (!staged() || n <= 0 || layer < 0 || layer >= n_layers_) return 0;
2326    if (io_fill_ && io_pf_ && direct_.empty()) {   // the page-fill mode: nothing is staged here, the kernels wait on pages
2327        prefetch(layer, experts, n);
2328        return 0;
2329    }
2330    prefetch_end();
2331    async_todo_.clear();
2332    async_fill_us_ = 0;
2333    static const int mode_env = [] {   // as the dispatch reads it (0.2.0: unset = 4 for the GGUF read in place on Linux)
2334        const char* v = std::getenv("STRATA_COLD_OVERLAP");
2335        return v == nullptr || v[0] == '\0' ? -1 : std::atoi(v);
2336    }();
2337    const int mode = mode_env >= 0 ? mode_env : (linux_file_defaults() ? 4 : 0);
2338    claim_todo(layer, experts, n, async_todo_, pending, mode >= 3);
2339    if (mode == 4) {   // zero-copy only: the blobs that must be read are read here, as `prefetch` reads them
2340        const auto t0 = std::chrono::steady_clock::now();
2341        fill_many(async_todo_);
2342        if (io_pf_ && !async_todo_.empty()) {
2343            io_crit_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
2344                                  std::memory_order_relaxed);
2345            io_crit_n_.fetch_add(1, std::memory_order_relaxed);
2346        }
2347        async_todo_.clear();
2348        for (int64_t i = 0; i < n; ++i) pending[i] = 0;   // one another thread still fills: `blob` waits for it
2349        return 0;
2350    }
2351    int64_t np = 0;
2352    for (int64_t i = 0; i < n; ++i) np += pending[i] ? 1 : 0;
2353    if (async_todo_.empty()) return np;
2354    async_t0_ = std::chrono::steady_clock::now();
2355    async_next_.store(0, std::memory_order_relaxed);
2356    async_end_ns_.store(0, std::memory_order_relaxed);
2357    const bool direct = !direct_.empty();
2358    const bool dec = tl_decode;
2359    auto work = [this, direct, dec] {
2360        tl_decode = dec;
2361        const std::vector<Fill>& todo = async_todo_;
2362        if (direct) {
2363            for (size_t at; (at = async_next_.fetch_add(16)) < todo.size();) {
2364                const size_t k = std::min<size_t>(16, todo.size() - at);
2365                const auto t0 = std::chrono::steady_clock::now();
2366                const bool ok = read_direct(todo.data() + at, k);
2367                const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
2368                for (size_t i = at; i < at + k; ++i) {
2369                    const Fill& f = todo[i];
2370                    if (ok) publish_stage(f.v, f.layer, true, us / (double) k);
2371                    else (void) fill_stage(f.v, f.layer, f.e, f.dst);
2372                }
2373            }
2374        } else {
2375            for (size_t i; (i = async_next_.fetch_add(1)) < todo.size();)
2376                (void) fill_stage(todo[i].v, todo[i].layer, todo[i].e, todo[i].dst);
2377        }
2378        const int64_t ns = (int64_t) std::chrono::duration_cast<std::chrono::nanoseconds>(
2379                               std::chrono::steady_clock::now() - async_t0_).count();
2380        int64_t cur = async_end_ns_.load(std::memory_order_relaxed);
2381        while (ns > cur && !async_end_ns_.compare_exchange_weak(cur, ns, std::memory_order_relaxed)) {}
2382    };
2383    const size_t nt = direct ? std::min<size_t>(4, (async_todo_.size() + 15) / 16)
2384                             : std::min<size_t>(async_todo_.size(), (size_t) std::max(1, fetch_threads_));
2385    for (size_t t = 0; t < nt; ++t) async_th_.emplace_back(work);
2386    return np;
2387}
2388
2389int64_t FileExpertSource::wait_landed(int64_t layer, const int64_t* experts, int64_t n, uint8_t* state) {
2390    std::unique_lock<std::mutex> lk(stage_mu_);
2391    int64_t got = 0;
2392    stage_cv_.wait(lk, [&] {
2393        bool left = false;
2394        for (int64_t i = 0; i < n; ++i) {
2395            if (state[i] != 1) continue;
2396            const auto it = stage_of_.find(layer * n_expert_ + experts[i]);
2397            // published (or failed: then `blob` reads it again on this thread, as before)
2398            if (it == stage_of_.end() || !stage_busy_[it->second]) { state[i] = 2; ++got; }
2399            else left = true;
2400        }
2401        return got > 0 || !left;
2402    });
2403    return got;
2404}
2405
2406bool FileExpertSource::zc_roles(int64_t layer, int64_t expert, const uint8_t** p) {
2407    const int64_t key = layer * n_expert_ + expert;
2408    if (std::find(zc_keys_.begin(), zc_keys_.end(), key) == zc_keys_.end()) return false;
2409    for (int r = 0; r < 3; ++r) {
2410        const size_t i = (size_t) (3 * layer + r);
2411        p[r] = role_ptr_[i] + (size_t) ((uint64_t) expert * role_bytes_[i]);
2412    }
2413    file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
2414    if (complement_ready_) file_reads_.fetch_add(1, std::memory_order_relaxed);
2415    reads_.fetch_add(1, std::memory_order_relaxed);
2416    if (io_stats_) io_cached_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
2417    if (gate_on_ && tl_decode) gate_c_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
2418    return true;
2419}
2420
2421void FileExpertSource::prefetch_end() {
2422    if (async_th_.empty()) return;
2423    for (std::thread& t : async_th_) t.join();
2424    async_th_.clear();
2425    async_fill_us_ = (double) async_end_ns_.load(std::memory_order_relaxed) / 1e3;
2426    if (io_pf_ && !async_todo_.empty()) {   // the reads' wall time, as the synchronous fill counts it
2427        io_crit_us_.fetch_add((uint64_t) async_fill_us_, std::memory_order_relaxed);
2428        io_crit_n_.fetch_add(1, std::memory_order_relaxed);
2429    }
2430    async_todo_.clear();
2431}
2432
2433bool FileExpertSource::latent_fetch_begin(int64_t layer, const int64_t* experts, int64_t n) {
2434    if (direct_.empty() || experts == nullptr || layer < 0 || layer >= n_layers_ ||
2435        n < 1 || n > 16 || !latent_fetch_wait()) return false;
2436    {
2437        std::lock_guard<std::mutex> lk(latent_io_mu_);
2438        if (!latent_io_thread_.joinable())
2439            latent_io_thread_ = std::thread([this] { latent_io_worker(); });
2440    }
2441    std::vector<Fill> todo;
2442    todo.reserve((size_t) n);
2443    try {
2444        claim_todo(layer, experts, n, todo, nullptr);
2445    } catch (...) {
2446        for (const Fill& f : todo) publish_stage(f.v, f.layer, false, 0);
2447        throw;
2448    }
2449    if (todo.empty()) return true;
2450    {
2451        std::lock_guard<std::mutex> lk(latent_io_mu_);
2452        latent_io_todo_ = std::move(todo);
2453        latent_io_ok_ = true;
2454        latent_io_busy_ = true;
2455    }
2456    latent_io_cv_.notify_one();
2457    return true;
2458}
2459
2460bool FileExpertSource::latent_fetch_wait() {
2461    std::unique_lock<std::mutex> lk(latent_io_mu_);
2462    latent_io_cv_.wait(lk, [&] { return !latent_io_busy_; });
2463    return latent_io_ok_;
2464}
2465
2466void FileExpertSource::latent_io_worker() {
2467    strata::platform::name_this_thread("strata-lat-io");
2468    for (;;) {
2469        std::vector<Fill> todo;
2470        {
2471            std::unique_lock<std::mutex> lk(latent_io_mu_);
2472            latent_io_cv_.wait(lk, [&] { return latent_io_quit_ || latent_io_busy_; });
2473            if (latent_io_quit_ && !latent_io_busy_) return;
2474            todo = std::move(latent_io_todo_);
2475        }
2476        bool ok = true;
2477        size_t published = 0;
2478        try {
2479            const auto t0 = std::chrono::steady_clock::now();
2480            const bool direct_ok = read_direct(todo.data(), todo.size());
2481            const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
2482            for (; published < todo.size(); ++published) {
2483                const Fill& f = todo[published];
2484                if (direct_ok) publish_stage(f.v, f.layer, true, us / (double) todo.size());
2485                else if (!fill_stage(f.v, f.layer, f.e, f.dst)) ok = false;
2486            }
2487        } catch (...) {
2488            ok = false;
2489            for (; published < todo.size(); ++published)
2490                publish_stage(todo[published].v, todo[published].layer, false, 0);
2491        }
2492        {
2493            std::lock_guard<std::mutex> lk(latent_io_mu_);
2494            latent_io_ok_ = ok;
2495            latent_io_busy_ = false;
2496        }
2497        latent_io_cv_.notify_all();
2498    }
2499}
2500
2501void FileExpertSource::latent_io_stop() {
2502    {
2503        std::lock_guard<std::mutex> lk(latent_io_mu_);
2504        latent_io_quit_ = true;
2505    }
2506    latent_io_cv_.notify_all();
2507    if (latent_io_thread_.joinable()) latent_io_thread_.join();
2508    std::lock_guard<std::mutex> lk(latent_io_mu_);
2509    latent_io_todo_.clear();
2510    latent_io_quit_ = latent_io_busy_ = false;
2511    latent_io_ok_ = true;
2512}
2513
2514void FileExpertSource::prefetch_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) {
2515    if (direct_.empty() || pairs == nullptr || n <= 0) return;   // unbuffered only: the mapped fill stays as it was
2516    std::vector<Fill> todo;
2517    {
2518        std::lock_guard<std::mutex> lk(stage_mu_);
2519        for (int64_t i = 0; i < std::min<int64_t>(n, 64); ++i) {
2520            const int64_t l = pairs[i].first, e = pairs[i].second;
2521            if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue;
2522            size_t v = 0;
2523            bool fill = false;
2524            if (!claim_stage(l * n_expert_ + e, v, fill) && fill) todo.push_back({v, l, e, stage_buf_[v].get()});
2525        }
2526    }
2527    fill_many(todo);
2528}
2529
2530bool FileExpertSource::advise_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) const {
2531    if (base_ == nullptr || unmapped_ || !direct_.empty() || !strata::platform::read_ahead_enabled()) return false;
2532    for (int64_t i = 0; pairs != nullptr && i < n; ++i) {
2533        const int64_t l = pairs[i].first, e = pairs[i].second;
2534        if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue;
2535        if (role_ptr_.empty()) {   // experts.bin: the blob is one contiguous range
2536            if (const uint8_t* b = mapped_blob(l, e)) strata::platform::advise_willneed(b, layer_blob_bytes_[(size_t) l]);
2537            continue;
2538        }
2539        for (int r = 0; r < 3; ++r) {
2540            const size_t k = (size_t) (3 * l + r);
2541            strata::platform::advise_willneed(role_ptr_[k] + (size_t) ((uint64_t) e * role_bytes_[k]), role_bytes_[k]);
2542        }
2543    }
2544    return true;
2545}
2546
2547void FileExpertSource::fill_many(const std::vector<Fill>& todo) {
2548    if (todo.empty()) return;
2549    if (!direct_.empty()) {
2550        // #286: overlapped batches - every role window of 16 blobs in flight at once; a big batch (the profile
2551        // fill) on up to 4 threads, a decode layer's few misses on this one
2552        std::atomic<size_t> next{0};
2553        auto work = [&] {
2554            for (size_t at; (at = next.fetch_add(16)) < todo.size();) {
2555                const size_t k = std::min<size_t>(16, todo.size() - at);
2556                const auto t0 = std::chrono::steady_clock::now();
2557                const bool ok = read_direct(todo.data() + at, k);
2558                const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
2559                for (size_t i = at; i < at + k; ++i) {
2560                    const Fill& f = todo[i];
2561                    // a failed batch: each blob again on its own (copy_from_files falls back to the mapping)
2562                    if (ok) publish_stage(f.v, f.layer, true, us / (double) k);
2563                    else (void) fill_stage(f.v, f.layer, f.e, f.dst);
2564                }
2565            }
2566        };
2567        const size_t nt = std::min<size_t>(4, (todo.size() + 15) / 16);
2568        std::vector<std::thread> th;
2569        for (size_t t = 1; t < nt; ++t) th.emplace_back(work);
2570        work();
2571        for (auto& t : th) t.join();
2572        return;
2573    }
2574#if defined(_WIN32)
2575    // One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large
2576    // requests, all queued at once, where the copies' page faults would read a few clusters each.  The copies below
2577    // then find the pages resident (or in flight).  STRATA_FETCH_PVM=0 is the A/B arm.
2578    {
2579        using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
2580        static const Pvm pvm = [] {
2581            const char* v = std::getenv("STRATA_FETCH_PVM");
2582            if (v != nullptr && std::atoi(v) == 0) return (Pvm) nullptr;
2583            return (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory");
2584        }();
2585        if (pvm != nullptr) {
2586            std::vector<WIN32_MEMORY_RANGE_ENTRY> ranges;
2587            ranges.reserve(todo.size() * 3);
2588            for (const Fill& f : todo)
2589                for (int r = 0; r < 3; ++r) {
2590                    const size_t i = (size_t) (3 * f.layer + r);
2591                    ranges.push_back({(PVOID) (role_ptr_[i] + (size_t) ((uint64_t) f.e * role_bytes_[i])),
2592                                      (SIZE_T) role_bytes_[i]});
2593                }
2594            (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0);
2595        }
2596    }
2597#endif
2598    // the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full
2599    std::atomic<size_t> next{0};
2600    const bool dec = tl_decode;
2601    auto work = [&] {
2602        tl_decode = dec;
2603        for (size_t i; (i = next.fetch_add(1)) < todo.size();)
2604            (void) fill_stage(todo[i].v, todo[i].layer, todo[i].e, todo[i].dst);
2605    };
2606    const size_t nt = std::min<size_t>(todo.size(), (size_t) fetch_threads_);
2607    std::vector<std::thread> th;
2608    for (size_t t = 1; t < nt; ++t) th.emplace_back(work);
2609    work();
2610    for (auto& t : th) t.join();
2611}
2612
2613uint64_t FileExpertSource::expert_bytes() const {
2614    uint64_t total = 0;
2615    for (uint64_t b : layer_blob_bytes_) total += b * (uint64_t) n_expert_;
2616    return total;
2617}
2618
2619bool FileExpertSource::open_direct(std::string& why) {
2620#if defined(_WIN32)
2621    for (const std::string& path : paths_) {
2622        const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
2623        std::vector<wchar_t> w((size_t) (wide > 0 ? wide : 1), L'\0');
2624        if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, w.data(), wide);
2625        HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
2626                               FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, nullptr);
2627        if (h == INVALID_HANDLE_VALUE) {
2628            why += "; cannot open " + path + " unbuffered (error " + std::to_string((unsigned long long) GetLastError()) +
2629                   "), read through the file cache";
2630            for (void* d : direct_) CloseHandle((HANDLE) d);
2631            direct_.clear();
2632            return false;
2633        }
2634        direct_.push_back(h);
2635    }
2636    if (role_ptr_.empty()) {   // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob
2637        std::lock_guard<std::mutex> lk(stage_mu_);
2638        for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
2639    }
2640    return true;
2641#elif defined(__linux__)
2642    // O_DIRECT: the reads bypass the page cache, as FILE_FLAG_NO_BUFFERING does (4 KiB-aligned windows, read_direct)
2643    for (const std::string& path : paths_) {
2644        const int fd = ::open(path.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC);
2645        if (fd < 0) {
2646            why += "; cannot open " + path + " with O_DIRECT (" + std::strerror(errno) + "), read through the file cache";
2647            for (void* d : direct_) close_direct(d);
2648            direct_.clear();
2649            return false;
2650        }
2651        direct_.push_back((void*) (intptr_t) fd);
2652    }
2653    if (role_ptr_.empty()) {   // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob
2654        std::lock_guard<std::mutex> lk(stage_mu_);
2655        for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
2656    }
2657    return true;
2658#else
2659    (void) why;
2660    return false;
2661#endif
2662}
2663
2664bool FileExpertSource::open_prompt_direct(std::string& why) {
2665#if defined(__linux__)
2666    if (base_ == nullptr || paths_.empty()) { why = "no expert files open"; return false; }
2667    if (!direct_.empty()) { why = "the file tier reads unbuffered already"; return false; }
2668    if (!pdirect_.empty()) return true;
2669    for (const std::string& path : paths_) {
2670        const int fd = ::open(path.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC);
2671        if (fd < 0) {
2672            why = "cannot open " + path + " with O_DIRECT (" + std::strerror(errno) + ")";
2673            for (void* d : pdirect_) close_direct(d);
2674            pdirect_.clear();
2675            return false;
2676        }
2677        pdirect_.push_back((void*) (intptr_t) fd);
2678    }
2679    return true;
2680#else
2681    why = "Linux only (NTFS serves unbuffered reads of a mapped file one at a time)";
2682    return false;
2683#endif
2684}
2685
2686bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) {
2687#if defined(_WIN32) || defined(__linux__)
2688    if (base_ == nullptr || paths_.empty() || !direct_.empty()) {
2689        why = !direct_.empty() ? "already unbuffered" : "no expert files open";
2690        return !direct_.empty();
2691    }
2692    // #577: the file tier reads the experts outside the RAM copy, not every byte of the shards (dense weights, the
2693    // PLE table), and the copy holds at most every expert - the budget asked for can be more than that
2694    const uint64_t experts = expert_bytes();
2695    const uint64_t arena = std::min(ram_bytes, experts);
2696    if (!file_tier_unbuffered(paths_, arena, experts - arena, why)) return false;
2697    return open_direct(why);
2698#else
2699    (void) ram_bytes;
2700    why = "through the file cache (no unbuffered reads on this platform)";
2701    return false;
2702#endif
2703}
2704
2705bool FileExpertSource::recheck_unbuffered(std::string& why) {
2706#if defined(_WIN32) || defined(__linux__)
2707    if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') {
2708        why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
2709        return !direct_.empty();
2710    }
2711    if (base_ == nullptr || paths_.empty()) {
2712        why = "no expert files open";
2713        return false;
2714    }
2715    // #577: the RAM copy is built (and already out of the available RAM), so what the file cache would have to keep
2716    // is exactly the experts outside it - the GPU cache's (refilled after a prompt borrowed their slots) and the
2717    // ones neither holds
2718    const uint64_t experts = expert_bytes();
2719    const uint64_t read = experts > complement_bytes_ ? experts - complement_bytes_ : 0;
2720    std::string w;
2721    const bool ub = file_tier_unbuffered(paths_, 0, read, w);
2722    char head[96];
2723    std::snprintf(head, sizeof head, "re-checked with the RAM copy built (%.2f GiB): ",
2724                  (double) complement_bytes_ / 1073741824.0);
2725    why = head + w;
2726    if (ub == !direct_.empty()) return ub;
2727    if (ub) return open_direct(why);
2728    // through the file cache after all: the mapped reads take over (staged() stays true for the GGUF in place)
2729    for (void* d : direct_) close_direct(d);
2730    direct_.clear();
2731    return false;
2732#else
2733    why = "through the file cache (no unbuffered reads on this platform)";
2734    return false;
2735#endif
2736}
2737
2738bool FileExpertSource::drop_mapping(std::string& why) {
2739#if defined(_WIN32)
2740    if (direct_.empty()) { why = "the reads are not unbuffered"; return false; }
2741    if (!role_ptr_.empty() || !maps_.empty()) {
2742        // the GGUF in place: nothing in the engine reads the shards through these views any more (the token embedding is
2743        // copied into pinned host memory at load, the dense weights and the head into VRAM, the PLE table has its own
2744        // reader), so every shard goes: with one mapped, NTFS runs the unbuffered reads of that file one at a time
2745        if (unmapped_) { why = "already closed"; return true; }
2746        for (Map& m : maps_) {
2747            if (m.closed) continue;
2748            if (m.base != nullptr && !UnmapViewOfFile((LPCVOID) m.base)) { why = "UnmapViewOfFile failed"; return false; }
2749            m.closed = true;   // m.base stays: the read offsets are taken from it
2750            if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping);
2751            m.mapping = nullptr;
2752            if (m.file != nullptr) CloseHandle((HANDLE) m.file);
2753            m.file = nullptr;
2754        }
2755        unmapped_ = true;
2756        char note[160];
2757        std::snprintf(note, sizeof note, "%zu GGUF shard%s unmapped; every expert outside RAM and VRAM is read unbuffered",
2758                      maps_.size(), maps_.size() == 1 ? "" : "s");
2759        why = note;
2760        return true;
2761    }
2762    if (base_ == nullptr || unmapped_) { why = base_ == nullptr ? "not open" : "already closed"; return unmapped_; }
2763    if (!UnmapViewOfFile((LPCVOID) base_)) { why = "UnmapViewOfFile failed"; return false; }
2764    unmapped_ = true;
2765    if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_);
2766    mapping_ = nullptr;
2767    // the cached handle too: only the unbuffered handles (direct_) read the file from here on
2768    if (file_ != nullptr) CloseHandle((HANDLE) file_);
2769    file_ = nullptr;
2770    why = "every expert outside RAM and VRAM is read unbuffered";
2771    return true;
2772#else
2773    // Linux's page cache has no such lock: only the tests close the GGUF views (STRATA_TEST_UNMAP_GGUF=1), to run the
2774    // unmapped path the Windows file tier takes
2775    const char* t = std::getenv("STRATA_TEST_UNMAP_GGUF");
2776    if (t == nullptr || t[0] == '\0' || std::atoi(t) == 0 || role_ptr_.empty()) { why = "not Windows"; return false; }
2777    if (direct_.empty()) { why = "the reads are not unbuffered"; return false; }
2778    if (unmapped_) { why = "already closed"; return true; }
2779    for (Map& m : maps_) {
2780        if (m.closed) continue;
2781        if (m.base != nullptr && munmap((void*) m.base, (size_t) m.bytes) != 0) { why = "munmap failed"; return false; }
2782        m.closed = true;
2783        if (m.fd >= 0) ::close(m.fd);
2784        m.fd = -1;
2785    }
2786    unmapped_ = true;
2787    why = std::to_string(maps_.size()) + " GGUF shard(s) unmapped (STRATA_TEST_UNMAP_GGUF); every expert outside RAM and VRAM is read unbuffered";
2788    return true;
2789#endif
2790}
2791
2792uint64_t FileExpertSource::drop_cached_pages(const std::function<bool(int64_t, int64_t)>& keep) {
2793#if defined(__linux__)
2794    if (unmapped_) return 0;
2795    const uint64_t page = (uint64_t) sysconf(_SC_PAGESIZE);
2796    uint64_t released = 0;
2797    // the whole pages of [p, p + n): a page that also holds a neighbouring blob stays (that neighbour may be kept)
2798    auto drop = [&](const uint8_t* p, uint64_t n, int fd, uint64_t off) {
2799        const uint64_t a = ((uint64_t) (uintptr_t) p + page - 1) & ~(page - 1);
2800        const uint64_t b = ((uint64_t) (uintptr_t) p + n) & ~(page - 1);
2801        if (p == nullptr || b <= a) return;
2802        if (madvise((void*) (uintptr_t) a, (size_t) (b - a), MADV_DONTNEED) != 0) return;
2803        if (fd >= 0) (void) posix_fadvise(fd, (off_t) (off + (a - (uint64_t) (uintptr_t) p)), (off_t) (b - a), POSIX_FADV_DONTNEED);
2804        released += b - a;
2805    };
2806    for (int64_t l = 0; l < n_layers_; ++l)
2807        for (int64_t e = 0; e < n_expert_; ++e) {
2808            if (keep && keep(l, e)) continue;
2809            if (!role_ptr_.empty()) {
2810                for (int r = 0; r < 3; ++r) {
2811                    const size_t i = (size_t) (3 * l + r);
2812                    const uint64_t per = role_bytes_[i];
2813                    const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) e * per);
2814                    const size_t f = (size_t) role_file_[i];
2815                    if (f >= maps_.size() || maps_[f].closed) continue;
2816                    drop(p, per, maps_[f].fd, (uint64_t) (p - maps_[f].base));
2817                }
2818            } else if (const uint8_t* b = mapped_blob(l, e)) {
2819                drop(b, layer_blob_bytes_[(size_t) l], fd_, (uint64_t) (b - base_));
2820            }
2821        }
2822    return released;
2823#else
2824    (void) keep;
2825    return 0;
2826#endif
2827}
2828
2829bool FileExpertSource::begin_startup_unbuffered(std::string& why) {
2830#if defined(_WIN32)
2831    if (const char* v = std::getenv("STRATA_STARTUP_UNBUFFERED"); v != nullptr && v[0] != '\0' && std::atoi(v) == 0) {
2832        why = "STRATA_STARTUP_UNBUFFERED=0";
2833        return false;
2834    }
2835    if (base_ == nullptr || unmapped_ || startup_ub_ || !role_ptr_.empty() || !maps_.empty() || paths_.size() != 1 ||
2836        layer_blob_bytes_.empty()) {
2837        why = "experts.bin only";
2838        return false;
2839    }
2840    if (!direct_.empty()) { why = "the file tier reads unbuffered already"; return false; }
2841    const auto t0 = std::chrono::steady_clock::now();
2842    const uint8_t* m = mapped_blob(0, 0);   // the first blob as the mapping reads it, for the check below
2843    if (m == nullptr) { why = "the first blob is not mapped"; return false; }
2844    const std::vector<uint8_t> ref(m, m + (size_t) layer_blob_bytes_[0]);
2845    // NTFS runs the unbuffered reads of a file one at a time while it is mapped or open buffered (drop_mapping), so
2846    // the view, the section and the handle all go.  The first unbuffered open with no buffered handle left purges the
2847    // file's cached pages: 1.2-2.5 s after a mapped start had left IQ2_XS's 33 GiB experts.bin on the standby list,
2848    // 3 ms after an unbuffered start.  A buffered handle held open instead keeps the cache and serializes the reads
2849    UnmapViewOfFile((LPCVOID) base_);
2850    unmapped_ = true;
2851    if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_);
2852    mapping_ = nullptr;
2853    if (file_ != nullptr) CloseHandle((HANDLE) file_);
2854    file_ = nullptr;
2855    std::string fail;
2856    if (open_direct(fail)) {
2857        // the first blob both ways: a drive that does not read it unbuffered keeps the mapped copy
2858        std::vector<uint8_t> probe(ref.size());
2859        const Fill f{0, 0, 0, probe.data()};
2860        if (read_direct(&f, 1) && std::memcmp(probe.data(), ref.data(), ref.size()) == 0) {
2861            startup_ub_ = true;
2862            startup_blob_bytes_ = file_blob_bytes_.load();
2863            startup_us_ = file_us_.load();
2864            char note[96];
2865            std::snprintf(note, sizeof note, "the view closed until the RAM copy is built; %.0f ms",
2866                          std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count());
2867            why = note;
2868            return true;
2869        }
2870        fail = "an unbuffered read of the first blob failed or differed from the mapping";
2871        for (void* d : direct_) close_direct(d);
2872        direct_.clear();
2873        std::lock_guard<std::mutex> lk(stage_mu_);
2874        stage_blob_ = 0;
2875    }
2876    std::string again;
2877    why = map_view(again) ? fail : fail + "; " + again;
2878    return false;
2879#else
2880    why = "Windows only";
2881    return false;
2882#endif
2883}
2884
2885bool FileExpertSource::end_startup_unbuffered(std::string& why) {
2886    if (!startup_ub_) return true;
2887    startup_ub_ = false;
2888    // the view first: closing the unbuffered handles beside a buffered one purges nothing
2889    if (!map_view(why)) {
2890        why += ": the file tier reads it unbuffered";
2891        return false;   // as after drop_mapping: every read goes through read_direct
2892    }
2893    for (void* d : direct_) close_direct(d);
2894    direct_.clear();
2895    {   // the mapped tier hands out the mapping: the startup's stage buffers go
2896        std::lock_guard<std::mutex> lk(stage_mu_);
2897        stage_buf_.clear();
2898        stage_key_.clear();
2899        stage_epoch_.clear();
2900        stage_used_.clear();
2901        stage_busy_.clear();
2902        stage_pf_.clear();
2903        stage_of_.clear();
2904        stage_blob_ = 0;
2905    }
2906    file_blob_bytes_.store(startup_blob_bytes_);
2907    file_us_.store(startup_us_);
2908    return true;
2909}
2910
2911bool FileExpertSource::map_view(std::string& why) {
2912#if defined(_WIN32)
2913    // open's mapping of experts.bin, again
2914    const std::string& path = paths_.front();
2915    const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
2916    std::vector<wchar_t> wpath((size_t) (wide > 0 ? wide : 1), L'\0');
2917    if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
2918    HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL,
2919                           nullptr);
2920    LARGE_INTEGER sz{};
2921    const bool same = f != INVALID_HANDLE_VALUE && GetFileSizeEx(f, &sz) && (uint64_t) sz.QuadPart == mapped_bytes_;
2922    HANDLE m = same ? CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr) : nullptr;
2923    void* view = m != nullptr ? MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0) : nullptr;
2924    if (view == nullptr) {
2925        why = f != INVALID_HANDLE_VALUE && !same
2926                  ? std::string("experts.bin changed size since it was opened")
2927                  : "experts.bin could not be mapped again (error " + std::to_string((unsigned long long) GetLastError()) + ")";
2928        if (m != nullptr) CloseHandle(m);
2929        if (f != INVALID_HANDLE_VALUE) CloseHandle(f);
2930        return false;
2931    }
2932    file_ = f;
2933    mapping_ = m;
2934    base_ = (const uint8_t*) view;
2935    unmapped_ = false;
2936    return true;
2937#else
2938    why = "Windows only";
2939    return false;
2940#endif
2941}
2942
2943bool FileExpertSource::read_direct(const Fill* fills, size_t n) const {
2944#if defined(_WIN32)
2945    // NTFS runs the unbuffered reads of a file one at a time while the file is mapped or cached anywhere (the engine
2946    // maps the GGUF shards for the token embedding and the PLE table): measured on a PCIe 5 drive, 512 KiB reads at
2947    // queue depth 48 make 10.4 GB/s on a file nobody maps and 3.4 GB/s on a mapped one, 8 MiB reads 8.6 GB/s.  So
2948    // windows less than kGap apart (the same role of nearby experts) are merged into requests of up to kMerge bytes.
2949    constexpr uint64_t kSector = 4096, kGap = 1ull << 20, kMerge = 32ull << 20;
2950    struct Window { int file; uint64_t a0, size, skip, n, at; uint8_t* dst; size_t req; uint64_t in_req; };
2951    struct Req { HANDLE h; uint64_t a0, size, pos; };
2952    // this thread's aligned buffer and events, kept for its next batch
2953    struct Scratch {
2954        uint8_t* buf = nullptr;
2955        size_t cap = 0;
2956        std::vector<HANDLE> ev;
2957        std::vector<OVERLAPPED> ov;
2958        std::vector<Window> win;
2959        std::vector<size_t> order;
2960        std::vector<Req> req;
2961        std::vector<DWORD> got;
2962        ~Scratch() {
2963            if (buf != nullptr) VirtualFree(buf, 0, MEM_RELEASE);
2964            for (HANDLE e : ev) CloseHandle(e);
2965        }
2966    };
2967    thread_local Scratch sc;
2968    sc.win.clear();
2969    for (size_t k = 0; k < n; ++k) {
2970        const Fill& f = fills[k];
2971        if (f.dst == nullptr || f.layer < 0 || f.e < 0 || f.layer >= n_layers_ || f.e >= n_expert_) return false;
2972        if (role_ptr_.empty()) {   // experts.bin: the blob is one contiguous range
2973            const uint64_t per = layer_blob_bytes_[(size_t) f.layer];
2974            const uint64_t off = layer_offsets_[(size_t) f.layer] + (uint64_t) f.e * per;
2975            const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
2976            sc.win.push_back({0, a0, a1 - a0, off - a0, per, 0, f.dst, 0, 0});
2977            continue;
2978        }
2979        uint64_t at = 0;
2980        for (int r = 0; r < 3; ++r) {
2981            const size_t i = (size_t) (3 * f.layer + r);
2982            const uint64_t per = role_bytes_[i];
2983            const Map& m = maps_[(size_t) role_file_[i]];
2984            const uint64_t off = (uint64_t) (role_ptr_[i] - m.base) + (uint64_t) f.e * per;
2985            const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
2986            sc.win.push_back({role_file_[i], a0, a1 - a0, off - a0, per, at, f.dst, 0, 0});
2987            at += per;
2988        }
2989    }
2990    sc.order.resize(sc.win.size());
2991    for (size_t w = 0; w < sc.win.size(); ++w) sc.order[w] = w;
2992    std::sort(sc.order.begin(), sc.order.end(), [&](size_t a, size_t b) {
2993        return sc.win[a].file != sc.win[b].file ? sc.win[a].file < sc.win[b].file : sc.win[a].a0 < sc.win[b].a0;
2994    });
2995    sc.req.clear();
2996    uint64_t total = 0;
2997    int last_file = -1;
2998    for (size_t w : sc.order) {
2999        Window& x = sc.win[w];
3000        if (!sc.req.empty() && x.file == last_file) {
3001            Req& q = sc.req.back();
3002            const uint64_t end = q.a0 + q.size, xend = x.a0 + x.size;
3003            if (x.a0 <= end + kGap && std::max(end, xend) - q.a0 <= kMerge) {
3004                if (xend > end) {
3005                    total += xend - end;
3006                    q.size = xend - q.a0;
3007                }
3008                x.req = sc.req.size() - 1;
3009                x.in_req = x.a0 - q.a0;
3010                continue;
3011            }
3012        }
3013        sc.req.push_back({(HANDLE) direct_[(size_t) x.file], x.a0, x.size, total});
3014        total += x.size;
3015        last_file = x.file;
3016        x.req = sc.req.size() - 1;
3017        x.in_req = 0;
3018    }
3019    if (total > sc.cap) {
3020        if (sc.buf != nullptr) VirtualFree(sc.buf, 0, MEM_RELEASE);
3021        sc.cap = (size_t) ((total + (1u << 20) - 1) >> 20 << 20);
3022        sc.buf = (uint8_t*) VirtualAlloc(nullptr, sc.cap, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
3023        if (sc.buf == nullptr) { sc.cap = 0; return false; }
3024    }
3025    while (sc.ev.size() < sc.req.size()) {
3026        HANDLE e = CreateEventW(nullptr, TRUE, FALSE, nullptr);
3027        if (e == nullptr) return false;
3028        sc.ev.push_back(e);
3029    }
3030    sc.ov.assign(sc.req.size(), OVERLAPPED{});
3031    // every request in flight before the first wait: the drive sees the whole batch as one queue
3032    size_t issued = 0;
3033    bool ok = true;
3034    for (size_t q = 0; q < sc.req.size(); ++q) {
3035        const Req& r = sc.req[q];
3036        OVERLAPPED& o = sc.ov[q];
3037        o.Offset = (DWORD) r.a0;
3038        o.OffsetHigh = (DWORD) (r.a0 >> 32);
3039        o.hEvent = sc.ev[q];
3040        if (!ReadFile(r.h, sc.buf + r.pos, (DWORD) r.size, nullptr, &o) && GetLastError() != ERROR_IO_PENDING) {
3041            ok = false;
3042            break;
3043        }
3044        ++issued;
3045    }
3046    std::vector<DWORD>& got = sc.got;
3047    got.assign(sc.req.size(), 0);
3048    for (size_t q = 0; q < issued; ++q)
3049        if (!GetOverlappedResult(sc.req[q].h, &sc.ov[q], &got[q], TRUE)) ok = false;
3050    if (!ok || issued < sc.req.size()) return false;
3051    for (const Window& x : sc.win) {
3052        // a request may run past the end of the file: only the role's own bytes have to arrive
3053        if ((uint64_t) got[x.req] < x.in_req + x.skip + x.n) return false;
3054        std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n);
3055    }
3056    return true;
3057#elif defined(__linux__)
3058    // Linux: O_DIRECT descriptors (open_direct) and the kernel's asynchronous reads - every window of the batch is
3059    // queued with one io_submit before the first wait, so the drive sees the batch as one queue, as the overlapped
3060    // ReadFiles above do.  No NTFS here: windows are merged only where they touch (the 4 KiB rounding of adjacent
3061    // slices, consecutive experts of a role), never across a gap that would be read for nothing.  Each thread has its
3062    // own context and aligned buffer, kept for its next batch, so concurrent batches never see each other's events.
3063    constexpr uint64_t kSector = 4096, kMerge = 32ull << 20;
3064    constexpr long kDepth = 256;   // requests in flight per thread; a larger batch is read in waves of this many
3065    struct Window { int file; uint64_t a0, size, skip, n, at; uint8_t* dst; size_t req; uint64_t in_req; };
3066    struct Req { int fd; uint64_t a0, size, pos; };
3067    struct Scratch {
3068        uint8_t* buf = nullptr;
3069        size_t cap = 0;
3070        aio_context_t ctx = 0;
3071        std::vector<Window> win;
3072        std::vector<size_t> order;
3073        std::vector<Req> req;
3074        std::vector<int64_t> got;
3075        std::vector<iocb> cb;
3076        std::vector<iocb*> cbp;
3077        std::vector<io_event> ev;
3078        ~Scratch() {
3079            std::free(buf);
3080            if (ctx != 0) (void) syscall(SYS_io_destroy, ctx);
3081        }
3082    };
3083    thread_local Scratch sc;
3084    if (sc.ctx == 0 && syscall(SYS_io_setup, kDepth, &sc.ctx) != 0) {
3085        sc.ctx = 0;
3086        return false;   // no AIO (a seccomp profile, aio-max-nr): the caller falls back to the mapped copy
3087    }
3088    sc.win.clear();
3089    for (size_t k = 0; k < n; ++k) {
3090        const Fill& f = fills[k];
3091        if (f.dst == nullptr || f.layer < 0 || f.e < 0 || f.layer >= n_layers_ || f.e >= n_expert_) return false;
3092        if (role_ptr_.empty()) {   // experts.bin: the blob is one contiguous range
3093            const uint64_t per = layer_blob_bytes_[(size_t) f.layer];
3094            const uint64_t off = layer_offsets_[(size_t) f.layer] + (uint64_t) f.e * per;
3095            const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
3096            sc.win.push_back({0, a0, a1 - a0, off - a0, per, 0, f.dst, 0, 0});
3097            continue;
3098        }
3099        uint64_t at = 0;
3100        for (int r = 0; r < 3; ++r) {
3101            const size_t i = (size_t) (3 * f.layer + r);
3102            const uint64_t per = role_bytes_[i];
3103            const Map& m = maps_[(size_t) role_file_[i]];
3104            const uint64_t off = (uint64_t) (role_ptr_[i] - m.base) + (uint64_t) f.e * per;
3105            const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
3106            sc.win.push_back({role_file_[i], a0, a1 - a0, off - a0, per, at, f.dst, 0, 0});
3107            at += per;
3108        }
3109    }
3110    sc.order.resize(sc.win.size());
3111    for (size_t w = 0; w < sc.win.size(); ++w) sc.order[w] = w;
3112    std::sort(sc.order.begin(), sc.order.end(), [&](size_t a, size_t b) {
3113        return sc.win[a].file != sc.win[b].file ? sc.win[a].file < sc.win[b].file : sc.win[a].a0 < sc.win[b].a0;
3114    });
3115    sc.req.clear();
3116    uint64_t total = 0;
3117    int last_file = -1;
3118    for (size_t w : sc.order) {
3119        Window& x = sc.win[w];
3120        if (!sc.req.empty() && x.file == last_file) {
3121            Req& q = sc.req.back();
3122            const uint64_t end = q.a0 + q.size, xend = x.a0 + x.size;
3123            if (x.a0 <= end && std::max(end, xend) - q.a0 <= kMerge) {
3124                if (xend > end) {
3125                    total += xend - end;
3126                    q.size = xend - q.a0;
3127                }
3128                x.req = sc.req.size() - 1;
3129                x.in_req = x.a0 - q.a0;
3130                continue;
3131            }
3132        }
3133        sc.req.push_back({(int) (intptr_t) (direct_.empty() ? pdirect_ : direct_)[(size_t) x.file], x.a0, x.size, total});
3134        total += x.size;
3135        last_file = x.file;
3136        x.req = sc.req.size() - 1;
3137        x.in_req = 0;
3138    }
3139    if (total > sc.cap) {
3140        std::free(sc.buf);
3141        sc.cap = (size_t) ((total + (1u << 20) - 1) >> 20 << 20);
3142        void* p = nullptr;
3143        sc.buf = posix_memalign(&p, (size_t) kSector, sc.cap) == 0 ? (uint8_t*) p : nullptr;
3144        if (sc.buf == nullptr) { sc.cap = 0; return false; }
3145    }
3146    sc.got.assign(sc.req.size(), -1);
3147    sc.cb.resize(std::min<size_t>(sc.req.size(), (size_t) kDepth));
3148    sc.cbp.resize(sc.cb.size());
3149    sc.ev.resize(sc.cb.size());
3150    bool ok = true;
3151    for (size_t w0 = 0; ok && w0 < sc.req.size(); w0 += (size_t) kDepth) {
3152        const size_t wn = std::min<size_t>((size_t) kDepth, sc.req.size() - w0);
3153        for (size_t j = 0; j < wn; ++j) {
3154            const Req& r = sc.req[w0 + j];
3155            iocb& c = sc.cb[j];
3156            std::memset(&c, 0, sizeof c);
3157            c.aio_lio_opcode = IOCB_CMD_PREAD;
3158            c.aio_fildes = (uint32_t) r.fd;
3159            c.aio_buf = (uint64_t) (uintptr_t) (sc.buf + r.pos);
3160            c.aio_nbytes = r.size;
3161            c.aio_offset = (int64_t) r.a0;
3162            c.aio_data = (uint64_t) (w0 + j);
3163            sc.cbp[j] = &c;
3164        }
3165        // every request of the wave queued; a refused submit ends the batch once what was queued has completed
3166        // (the kernel still writes into the buffer until then)
3167        size_t queued = 0;
3168        while (queued < wn) {
3169            const long r = syscall(SYS_io_submit, sc.ctx, (long) (wn - queued), sc.cbp.data() + queued);
3170            if (r > 0) { queued += (size_t) r; continue; }
3171            if (r < 0 && errno == EINTR) continue;
3172            ok = false;
3173            break;
3174        }
3175        for (size_t done = 0; done < queued;) {
3176            const long r = syscall(SYS_io_getevents, sc.ctx, 1L, (long) (queued - done), sc.ev.data(), nullptr);
3177            if (r < 0) {
3178                if (errno == EINTR) continue;
3179                // the context is in an unknown state: drop it (io_destroy waits for what is still in flight)
3180                (void) syscall(SYS_io_destroy, sc.ctx);
3181                sc.ctx = 0;
3182                return false;
3183            }
3184            for (long j = 0; j < r; ++j) {
3185                const io_event& e = sc.ev[(size_t) j];
3186                sc.got[(size_t) e.data] = e.res;
3187                if (e.res < 0) ok = false;
3188            }
3189            done += (size_t) r;
3190        }
3191    }
3192    if (!ok) return false;
3193    for (const Window& x : sc.win) {
3194        // a request may run past the end of the file: only the role's own bytes have to arrive
3195        if (sc.got[x.req] < 0 || (uint64_t) sc.got[x.req] < x.in_req + x.skip + x.n) return false;
3196        std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n);
3197    }
3198    return true;
3199#else
3200    (void) fills; (void) n;
3201    return false;
3202#endif
3203}
3204
3205void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) {
3206    if ((role_ptr_.empty() && !io_pf_) || n <= 0 || layer < 0 || layer >= n_layers_) return;
3207    uint32_t stamp;
3208    {
3209        std::lock_guard<std::mutex> lk(stage_mu_);
3210        stamp = (uint32_t) epoch_ + 1;
3211    }
3212#if defined(_WIN32)
3213    using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
3214    static const Pvm pvm = (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory");
3215    std::vector<WIN32_MEMORY_RANGE_ENTRY> ranges;
3216#endif
3217    for (int64_t j = 0; j < n; ++j) {
3218        const int64_t e = experts[j];
3219        if (e < 0 || e >= n_expert_) continue;
3220        const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
3221        if (complement_ready_ && resident_blob(index) != nullptr)
3222            continue;                                                    // in the RAM copy
3223        if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed);
3224        warm_count_.fetch_add(1, std::memory_order_relaxed);
3225        if (io_pf_ && direct_.empty() && gate_open()) {   // read it ahead with pread on the I/O threads (instead of an madvise hint)
3226            if (io_ahead_) io_enqueue(layer, e, true);
3227            continue;
3228        }
3229        if (role_ptr_.empty() || unmapped_) continue;
3230        for (int r = 0; r < 3; ++r) {
3231            const size_t i = (size_t) (3 * layer + r);
3232            const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) e * role_bytes_[i]);
3233#if defined(_WIN32)
3234            ranges.push_back({(PVOID) p, (SIZE_T) role_bytes_[i]});
3235#else
3236            const uintptr_t pg = 4096, a = (uintptr_t) p & ~(pg - 1);
3237            (void) madvise((void*) a, (size_t) ((uintptr_t) p + role_bytes_[i] - a), MADV_WILLNEED);
3238#endif
3239        }
3240    }
3241#if defined(_WIN32)
3242    if (pvm != nullptr && !ranges.empty()) (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0);
3243#endif
3244}
3245
3246static inline int la_pc64(uint64_t x) {   // (portable: no compiler builtin)
3247    int n = 0;
3248    for (; x != 0; x &= x - 1) ++n;
3249    return n;
3250}
3251
3252RouterLookahead::~RouterLookahead() {
3253    {
3254        std::lock_guard<std::mutex> lk(mu_);
3255        quit_ = true;
3256    }
3257    cv_.notify_all();
3258    if (thread_.joinable()) thread_.join();
3259}
3260
3261void RouterLookahead::set_foresight(ForesightSwap* fs) {
3262    for (;;) {
3263        {
3264            std::lock_guard<std::mutex> lk(mu_);
3265            if (fs != nullptr || !busy_) { fs_ = fs; return; }
3266        }
3267        // detaching: a prediction in progress finishes first (the swap space is about to go away)
3268        std::this_thread::sleep_for(std::chrono::milliseconds(1));
3269    }
3270}
3271
3272bool RouterLookahead::start(std::vector<std::vector<uint16_t>> routers, int64_t n_embd, int64_t n_expert, int k,
3273                            ExpertSource* src, std::string& err, bool allow_cold_source) {
3274    if (src == nullptr || (!allow_cold_source && !src->warms())) { err = "RouterLookahead: the expert source does not warm"; return false; }
3275    if (n_embd % 8 != 0) { err = "RouterLookahead: n_embd is not a multiple of 8"; return false; }
3276    for (const auto& r : routers)
3277        if (r.size() != (size_t) (n_embd * n_expert)) { err = "RouterLookahead: a router of another shape"; return false; }
3278    routers_ = std::move(routers);
3279    n_embd_ = n_embd;
3280    n_expert_ = n_expert;
3281    k_ = k < 1 ? 1 : k > (int) n_expert ? (int) n_expert : k;
3282    src_ = src;
3283    x_.assign((size_t) (8 * n_embd), 0.f);
3284    thread_ = std::thread([this] {
3285        strata::platform::name_this_thread("strata-lookahead");
3286        strata::aux_cpus::pin_current_thread();
3287        run();
3288    });
3289    return true;
3290}
3291
3292void RouterLookahead::submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res) {
3293    if (layer + 1 >= (int64_t) routers_.size() || n_tok <= 0 || x == nullptr) return;
3294    {
3295        std::lock_guard<std::mutex> lk(mu_);
3296        if (busy_ || pending_) { skipped_.fetch_add(1, std::memory_order_relaxed); return; }
3297        n_tok_ = std::min<int64_t>(n_tok, 8);
3298        std::memcpy(x_.data(), x, (size_t) (n_tok_ * n_embd_) * sizeof(float));
3299        layer_ = layer + 1;
3300        has_res_ = host_res != nullptr;
3301        if (has_res_) {   // the rows of layer + 1 .. + depth, as they are now: the table changes while this runs
3302            const int64_t l1 = std::min<int64_t>(layer_ + depth_, (int64_t) routers_.size());
3303            res_.assign(host_res + (size_t) (layer_ * n_expert_), host_res + (size_t) (l1 * n_expert_));
3304        }
3305        sub_gen_ = gen_.load(std::memory_order_relaxed);
3306        pending_ = true;
3307    }
3308    cv_.notify_one();
3309}
3310
3311void RouterLookahead::enable_stats(int64_t n_layers) {
3312    words_ = (n_expert_ + 63) / 64;
3313    pmask_.reset(new std::atomic<uint64_t>[(size_t) (n_layers * 3 * words_)]);
3314    pstamp_.reset(new std::atomic<uint64_t>[(size_t) n_layers]);
3315    for (int64_t i = 0; i < n_layers * 3 * words_; ++i) pmask_[(size_t) i].store(0, std::memory_order_relaxed);
3316    for (int64_t i = 0; i < n_layers; ++i) pstamp_[(size_t) i].store(0, std::memory_order_relaxed);
3317    pvote_.reset(new std::atomic<int32_t>[(size_t) (n_layers * kVoteN)]);
3318    for (int64_t i = 0; i < n_layers * kVoteN; ++i) pvote_[(size_t) i].store(0, std::memory_order_relaxed);
3319    stats_on_ = true;
3320}
3321
3322// the dispatch thread: score the prediction made for `layer` against the experts it routes outside the GPU cache
3323void RouterLookahead::stats_score(int64_t layer, const int32_t* ids, int64_t n, const int32_t* host_res, int pcie_num) {
3324    if (!stats_on_ || layer < 1 || layer >= (int64_t) routers_.size()) return;
3325    ++st_layers_;
3326    if (pstamp_[(size_t) layer].load(std::memory_order_acquire) != gen_.load(std::memory_order_relaxed) + 1) {
3327        ++st_nopred_;
3328        return;
3329    }
3330    std::vector<uint64_t> act((size_t) words_, 0);
3331    for (int64_t i = 0; i < n; ++i) {
3332        const int32_t e = ids[i];
3333        if (e < 0 || e >= n_expert_) continue;
3334        if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue;
3335        act[(size_t) (e >> 6)] |= 1ull << (e & 63);
3336    }
3337    uint64_t na = 0;
3338    for (int64_t w = 0; w < words_; ++w) na += (uint64_t) la_pc64(act[(size_t) w]);
3339    st_actual_ += na;
3340    {   // the vote-ranked top M (the experts most tokens predict) against the misses, and against the PCIe share
3341        static const int vm[3] = {4, 8, 12};
3342        int32_t vt[kVoteN];
3343        int nv = 0;
3344        for (int i = 0; i < kVoteN; ++i) {
3345            const int32_t v = pvote_[(size_t) (layer * kVoteN + i)].load(std::memory_order_relaxed);
3346            if (v == 0) break;
3347            vt[nv++] = v - 1;
3348        }
3349        // the misses in routing order (first appearance), the PCIe share = the last (n_miss * pcie_num / 256) of them
3350        std::vector<int32_t> order_miss;
3351        for (int64_t i = 0; i < n; ++i) {
3352            const int32_t e = ids[i];
3353            if (e < 0 || e >= n_expert_) continue;
3354            if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue;
3355            if (std::find(order_miss.begin(), order_miss.end(), e) == order_miss.end()) order_miss.push_back(e);
3356        }
3357        const int m = ((int) order_miss.size() * pcie_num) >> 8;
3358        st_pch_ += (uint64_t) m;
3359        for (int s = 0; s < 3; ++s) {
3360            const int top = std::min(vm[s], nv);
3361            st_vpred_[s] += (uint64_t) top;
3362            for (int j = 0; j < top; ++j) {
3363                if ((act[(size_t) (vt[j] >> 6)] >> (vt[j] & 63)) & 1ull) ++st_vhit_[s];
3364                const auto it = std::find(order_miss.begin(), order_miss.end(), vt[j]);
3365                if (it != order_miss.end() && (int) (it - order_miss.begin()) >= (int) order_miss.size() - m) ++st_pcov_[s];
3366            }
3367        }
3368    }
3369    for (int s = 0; s < 3; ++s) {
3370        uint64_t hit = 0, np = 0;
3371        for (int64_t w = 0; w < words_; ++w) {
3372            const uint64_t pm = pmask_[(size_t) ((layer * 3 + s) * words_ + w)].load(std::memory_order_relaxed);
3373            hit += (uint64_t) la_pc64(pm & act[(size_t) w]);
3374            np += (uint64_t) la_pc64(pm);
3375        }
3376        st_hit_[s] += hit;
3377        st_pred_[s] += np;
3378    }
3379    if (layer == (int64_t) routers_.size() - 1 && (++st_windows_ % 100) == 0) {
3380        const uint64_t scored = st_layers_ - st_nopred_;
3381        std::fprintf(stderr, "strata lookahead stats: %llu windows, %llu layers scored, %llu without a prediction (%.1f%%); "
3382                     "%.2f actual non-resident experts/layer;",
3383                     (unsigned long long) st_windows_, (unsigned long long) scored, (unsigned long long) st_nopred_,
3384                     st_layers_ ? 100.0 * (double) st_nopred_ / (double) st_layers_ : 0.0,
3385                     scored ? (double) st_actual_ / (double) scored : 0.0);
3386        std::fprintf(stderr, " predictor thread %.2f ms/window;",
3387                     (double) busy_us_.load(std::memory_order_relaxed) / 1000.0 / (double) st_windows_);
3388        static const int add[3] = {0, 4, 10};
3389        for (int s = 0; s < 3; ++s)
3390            std::fprintf(stderr, " k=%d: recall %.3f precision %.3f (%.2f predicted/layer);", k_ + add[s],
3391                         st_actual_ ? (double) st_hit_[s] / (double) st_actual_ : 0.0,
3392                         st_pred_[s] ? (double) st_hit_[s] / (double) st_pred_[s] : 0.0,
3393                         scored ? (double) st_pred_[s] / (double) scored : 0.0);
3394        static const int vm[3] = {4, 8, 12};
3395        for (int s = 0; s < 3; ++s)
3396            std::fprintf(stderr, " votes top%d: %.2f/layer, covers %.3f of the misses (precision %.3f), %.3f of the PCIe share (%.2f/layer);",
3397                         vm[s], scored ? (double) st_vpred_[s] / (double) scored : 0.0,
3398                         st_actual_ ? (double) st_vhit_[s] / (double) st_actual_ : 0.0,
3399                         st_vpred_[s] ? (double) st_vhit_[s] / (double) st_vpred_[s] : 0.0,
3400                         st_pch_ ? (double) st_pcov_[s] / (double) st_pch_ : 0.0,
3401                         scored ? (double) st_pch_ / (double) scored : 0.0);
3402        std::fprintf(stderr, "\n");
3403    }
3404}
3405
3406void RouterLookahead::run() {
3407    std::vector<float> logits((size_t) (8 * n_expert_));
3408    std::vector<int32_t> order((size_t) n_expert_);
3409    std::vector<int64_t> want;
3410    std::vector<float> wconf;   // 149-prefetch: per wanted expert, its best rank's confidence (warm_scored)
3411    for (;;) {
3412        int64_t layer, nt;
3413        const int32_t* host_res;   // res_: layer_'s row first (submit leaves it alone while busy_)
3414        ForesightSwap* fs;
3415        uint64_t sgen;
3416        {
3417            std::unique_lock<std::mutex> lk(mu_);
3418            cv_.wait(lk, [&] { return quit_ || pending_; });
3419            if (quit_) return;
3420            pending_ = false;
3421            busy_ = true;
3422            layer = layer_;
3423            nt = n_tok_;
3424            host_res = has_res_ ? res_.data() : nullptr;
3425            fs = fs_;
3426            sgen = sub_gen_;
3427        }
3428        const auto t0 = std::chrono::steady_clock::now();
3429        const int64_t layer0 = layer;
3430        const int depth = src_ != nullptr && !src_->read_ahead_open() ? 1 : depth_;   // 149: the gate closed
3431        for (int dj = 0; dj < depth && layer0 + dj < (int64_t) routers_.size(); ++dj) {
3432        layer = layer0 + dj;
3433        want.clear();
3434        wconf.clear();
3435        const bool scored = src_->wants_scores();
3436        // The router dot is AVX2 (kq_avx2.cpp); a CPU without AVX2 (the experimental older-CPU builds) takes the AVX1
3437        // one (kq_avx1.cpp) or, without AVX, the same sums in plain C++.  From the Strata_Dirigo fork (rwkeyes): an
3438        // AVX-only Xeon E5-2687W died here (vpmovzxwd) on its first request.  An estimate only (which experts to
3439        // prefetch); the order of the additions differs between the three, the output does not depend on it.
3440#if defined(__aarch64__) && !defined(STRATA_GPU_METAL)   // Metal (Apple silicon) keeps the plain loop below: its bf16_rows_dot_multi is a stub
3441        strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_,
3442                                                  x_.data(), (int) nt, logits.data());
3443#else
3444        if (strata::kernels::cpu::cpu_avx2_ok()) {
3445            strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_,
3446                                                      x_.data(), (int) nt, logits.data());
3447        } else if (strata::kernels::cpu::cpu_avx1_ok()) {
3448            strata::kernels::cpu::bf16_rows_dot_multi_avx1(routers_[(size_t) layer].data(), (int) n_expert_,
3449                                                           (int) n_embd_, x_.data(), (int) nt, logits.data());
3450        } else {
3451            // a mul and an add, not std::fma: without an FMA instruction that is a libm call per element (74x
3452            // slower on a Xeon E5-2665, measured by the fork)
3453            const uint16_t* rw = routers_[(size_t) layer].data();
3454            for (int64_t r = 0; r < n_expert_; ++r) {
3455                const uint16_t* wr = rw + (size_t) r * (size_t) n_embd_;
3456                for (int64_t t = 0; t < nt; ++t) {
3457                    const float* xr = x_.data() + (size_t) t * (size_t) n_embd_;
3458                    float acc = 0.0f;
3459                    for (int64_t c = 0; c < n_embd_; ++c) {
3460                        const uint32_t bits = (uint32_t) wr[c] << 16;
3461                        float wf;
3462                        std::memcpy(&wf, &bits, sizeof wf);
3463                        acc += wf * xr[c];
3464                    }
3465                    logits[(size_t) t * (size_t) n_expert_ + (size_t) r] = acc;
3466                }
3467            }
3468        }
3469#endif
3470        const int kmax = stats_on_ ? (int) std::min<int64_t>(k_ + 10, n_expert_) : k_;
3471        const int ks[3] = {k_, (int) std::min<int64_t>(k_ + 4, n_expert_), kmax};
3472        std::vector<uint64_t> sm;
3473        if (stats_on_) sm.assign((size_t) (3 * words_), 0);
3474        for (int64_t t = 0; t < nt; ++t) {
3475            const float* lt = logits.data() + (size_t) (t * n_expert_);
3476            for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e;
3477            std::partial_sort(order.begin(), order.begin() + kmax, order.end(),
3478                              [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; });
3479            for (int j = 0; j < kmax; ++j) {
3480                const int64_t e = order[(size_t) j];
3481                if (host_res != nullptr && host_res[(size_t) ((layer - layer0) * n_expert_ + e)] >= 0) continue;   // on the GPU
3482                if (j < k_) {
3483                    const auto it = std::find(want.begin(), want.end(), e);
3484                    // confidence: 1 for a token's top pick down to 1/k_ for its k_-th, the best over the window's tokens,
3485                    // halved for every layer further ahead than the next (a deeper guess is less often right)
3486                    const float c = (float) (k_ - j) / (float) k_ * (dj == 0 ? 1.0f : std::pow(0.5f, (float) dj));
3487                    if (it == want.end()) { want.push_back(e); wconf.push_back(c); }
3488                    else if (scored && c > wconf[(size_t) (it - want.begin())]) wconf[(size_t) (it - want.begin())] = c;
3489                }
3490                if (stats_on_ && dj == 0)
3491                    for (int s = 0; s < 3; ++s)
3492                        if (j < ks[s]) sm[(size_t) (s * words_ + (e >> 6))] |= 1ull << (e & 63);
3493            }
3494        }
3495        if (stats_on_ && dj == 0) {
3496            // votes: how many tokens put each non-resident expert in their top k_
3497            std::vector<std::pair<int, int32_t>> votes;   // (sum of 64 - rank, expert)
3498            for (int64_t t = 0; t < nt; ++t) {
3499                const float* lt = logits.data() + (size_t) (t * n_expert_);
3500                for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e;
3501                std::partial_sort(order.begin(), order.begin() + k_, order.end(),
3502                                  [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; });
3503                for (int j = 0; j < k_; ++j) {
3504                    const int32_t e = order[(size_t) j];
3505                    if (host_res != nullptr && host_res[(size_t) ((layer - layer0) * n_expert_ + e)] >= 0) continue;
3506                    auto it = std::find_if(votes.begin(), votes.end(), [&](const auto& v) { return v.second == e; });
3507                    if (it == votes.end()) votes.emplace_back(64 - j, e);
3508                    else it->first += 64 - j;
3509                }
3510            }
3511            std::sort(votes.begin(), votes.end(), [](const auto& a, const auto& b) { return a.first > b.first; });
3512            for (int i = 0; i < kVoteN; ++i)
3513                pvote_[(size_t) (layer * kVoteN + i)].store(i < (int) votes.size() ? votes[(size_t) i].second + 1 : 0,
3514                                                            std::memory_order_relaxed);
3515            for (int64_t i = 0; i < 3 * words_; ++i)
3516                pmask_[(size_t) (layer * 3 * words_ + i)].store(sm[(size_t) i], std::memory_order_relaxed);
3517            pstamp_[(size_t) layer].store(sgen + 1, std::memory_order_release);
3518        }
3519        if (scored) src_->warm_scored(layer, want.data(), wconf.data(), (int64_t) want.size(), dj + 1);
3520        else src_->warm(layer, want.data(), (int64_t) want.size());
3521        if (fs != nullptr && dj == 0)   // the next layer only: a deeper guess is too often wrong to spend a copy on
3522            for (const int64_t e : want) fs->predict(src_, layer, (int32_t) e);
3523        predicted_.fetch_add((int64_t) want.size(), std::memory_order_relaxed);
3524        }
3525        busy_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
3526                           std::memory_order_relaxed);
3527        {
3528            std::lock_guard<std::mutex> lk(mu_);
3529            busy_ = false;
3530        }
3531    }
3532}
3533
3534void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) {
3535    (void) ids;
3536    (void) k;
3537    if (!staged()) return;
3538    bool new_window = false;
3539    {
3540        std::lock_guard<std::mutex> lk(stage_mu_);
3541        if (layer != last_layer_) {
3542            ++epoch_;
3543            new_window = layer < last_layer_;
3544            if (new_window) ++reuse_window_;
3545            last_layer_ = layer;
3546            io_epoch_.store(epoch_, std::memory_order_relaxed);   // 149-prefetch: the workers' deadline clock
3547        }
3548    }
3549    if (new_window && io_sched_) io_window_tick();
3550    if (new_window && gate_on_ && tl_decode) { gate_capacity(); gate_tick(); }
3551}
3552
3553bool FileExpertSource::transient(int64_t layer, int64_t expert) const {
3554    // the io-prefetch staging of the experts.bin tier is the decode's: the prompt path keeps reading the mapping
3555    // (its own read-ahead hints), so this answers as it did without io prefetch - unless STRATA_PROMPT_DIRECT=1
3556    // opened the prompt path's own unbuffered descriptors, which only copy_blobs (the stager) reads through
3557    if ((role_ptr_.empty() && direct_.empty() && pdirect_.empty()) || layer < 0 || expert < 0 || layer >= n_layers_ ||
3558        expert >= n_expert_) return false;
3559    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
3560    if (complement_ready_ && resident_blob(index) != nullptr)
3561        return false;
3562    return override_.empty() || override_[index] == nullptr;
3563}
3564
3565double FileExpertSource::cached_share(int64_t samples) const {
3566#if defined(__linux__)
3567    if (role_ptr_.empty() || unmapped_ || samples <= 0 || n_layers_ <= 0 || n_expert_ <= 0) return -1.0;
3568    // an even spread over the (layer, expert) grid, every page of each of the expert's three slices through mincore
3569    const int64_t total = (int64_t) n_layers_ * (int64_t) n_expert_;
3570    const int64_t n = std::min<int64_t>(samples, total);
3571    uint64_t pages = 0, resident = 0;
3572    std::vector<unsigned char> vec;
3573    for (int64_t s = 0; s < n; ++s) {
3574        const int64_t idx = std::min<int64_t>(total - 1, (s * total) / n + (s * 7919) % std::max<int64_t>(1, total / n));
3575        const int64_t layer = idx / n_expert_, expert = idx % n_expert_;
3576        if (!transient(layer, expert)) continue;
3577        for (int r = 0; r < 3; ++r) {
3578            const size_t i = (size_t) (3 * layer + r);
3579            if (role_ptr_[i] == nullptr || role_bytes_[i] == 0) continue;
3580            const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) expert * role_bytes_[i]);
3581            const uintptr_t pg = 4096, a = (uintptr_t) p & ~(pg - 1);
3582            const size_t len = (size_t) ((uintptr_t) p + role_bytes_[i] - a), np = (len + pg - 1) / pg;
3583            vec.assign(np, 0);
3584            if (mincore((void*) a, len, vec.data()) != 0) return -1.0;
3585            pages += np;
3586            for (unsigned char v : vec) resident += v & 1;
3587        }
3588    }
3589    return pages ? (double) resident / (double) pages : -1.0;
3590#else
3591    (void) samples;
3592    return -1.0;   // no cheap residency query for a file mapping here: the caller keeps its SSD assumption
3593#endif
3594}
3595
3596bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
3597    if (base_ == nullptr || dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_)
3598        return false;
3599    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
3600    const uint64_t bytes = layer_blob_bytes_[(size_t) layer];
3601    if (complement_ready_) {
3602        const uint8_t* held =
3603            resident_blob(index);
3604        if (held == nullptr && !override_.empty()) held = override_[index];
3605        if (held != nullptr) {
3606            std::memcpy(dst, held, (size_t) bytes);
3607            return true;
3608        }
3609    }
3610    const auto t0 = std::chrono::steady_clock::now();
3611    if (!copy_from_files(layer, expert, dst)) return false;
3612    file_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
3613                       std::memory_order_relaxed);
3614    file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed);
3615    return true;
3616}
3617
3618// pp-opt: the prompt path streams a chunk's experts in file order, so a stager thread's run of jobs is mostly
3619// neighbouring blobs of experts.bin.  One read_direct batch merges them into requests of up to 32 MiB (kMerge) where
3620// copy_blob made one ~2 MB request each - and NTFS serves the unbuffered reads of a mapped file one at a time, so the
3621// request size is what sets the rate (see read_direct).  The blobs the RAM copy holds are copied as before.
3622bool FileExpertSource::copy_blobs(const int32_t* layers, const int32_t* experts, uint8_t* const* dst, size_t n) {
3623    if ((direct_.empty() && pdirect_.empty()) || n <= 1) return ExpertSource::copy_blobs(layers, experts, dst, n);
3624    thread_local std::vector<Fill> fills;
3625    fills.clear();
3626    uint64_t bytes = 0;
3627    for (size_t i = 0; i < n; ++i) {
3628        const int64_t l = layers[i], e = experts[i];
3629        if (base_ == nullptr || dst[i] == nullptr || l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) return false;
3630        const size_t index = (size_t) l * (size_t) n_expert_ + (size_t) e;
3631        if (complement_ready_ &&
3632            (resident_blob(index) != nullptr || (!override_.empty() && override_[index] != nullptr))) {
3633            if (!copy_blob(l, e, dst[i])) return false;
3634            continue;
3635        }
3636        fills.push_back({0, l, e, dst[i]});
3637        bytes += layer_blob_bytes_[(size_t) l];
3638    }
3639    if (fills.empty()) return true;
3640    const auto t0 = std::chrono::steady_clock::now();
3641    if (!read_direct(fills.data(), fills.size()))
3642        for (const Fill& f : fills)   // a failed batch: each blob on its own (copy_from_files falls back to the mapping)
3643            if (!copy_from_files(f.layer, f.e, f.dst)) return false;
3644    file_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
3645                       std::memory_order_relaxed);
3646    file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed);
3647    return true;
3648}
3649
3650const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) const {
3651    if (!role_ptr_.empty()) return nullptr;   // the GGUF in place: no contiguous blob in any file
3652    if (unmapped_) return nullptr;            // pp-opt: drop_mapping closed the view; read_direct reads them
3653    if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr;
3654    const size_t i = (size_t) layer;
3655    if (i >= layer_offsets_.size() || i >= layer_blob_bytes_.size()) return nullptr;
3656    const uint64_t blob_bytes = layer_blob_bytes_[i];
3657    if (blob_bytes == 0 || (uint64_t) expert > std::numeric_limits<uint64_t>::max() / blob_bytes) return nullptr;
3658    const uint64_t expert_offset = (uint64_t) expert * blob_bytes;
3659    const uint64_t layer_offset = layer_offsets_[i];
3660    if (layer_offset > mapped_bytes_ || expert_offset > mapped_bytes_ - layer_offset) return nullptr;
3661    const uint64_t offset = layer_offset + expert_offset;
3662    if (blob_bytes > mapped_bytes_ - offset) return nullptr;
3663    return base_ + (size_t) offset;
3664}
3665
3666uint64_t FileExpertSource::release(int64_t layer, int64_t expert) {
3667#if defined(_WIN32)
3668    static const bool enabled = [] {
3669        const char* v = std::getenv("STRATA_FILE_RELEASE");
3670        return v != nullptr && std::strcmp(v, "1") == 0;
3671    }();
3672    if (!enabled || base_ == nullptr || unmapped_ || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_)
3673        return 0;
3674    static const uint64_t page = [] {
3675        SYSTEM_INFO info{};
3676        GetSystemInfo(&info);
3677        return (uint64_t) info.dwPageSize;
3678    }();
3679    // These read-only file views are not CUDA-registered. blob() may instead return pinned RAM or an exchange
3680    // buffer, so resolve the file spans directly. A shared boundary page stays for the neighboring expert.
3681    auto trim = [&](const uint8_t* p, uint64_t bytes) -> uint64_t {
3682        const uint64_t misalignment = (uintptr_t) p % page;
3683        const uint64_t skip = misalignment == 0 ? 0 : page - misalignment;
3684        if (bytes <= skip) return 0;
3685        const uint64_t whole = (bytes - skip) / page * page;
3686        if (whole == 0) return 0;
3687        SetLastError(ERROR_SUCCESS);
3688        if (!VirtualUnlock((LPVOID) (p + (size_t) skip), (SIZE_T) whole)) {
3689            const DWORD error = GetLastError();
3690            // VirtualUnlock trims an unlocked range and reports FALSE / ERROR_NOT_LOCKED for that success.
3691            if (error != ERROR_NOT_LOCKED) {
3692                std::fprintf(stderr, "FileExpertSource: cannot trim mapped pages for layer %lld expert %lld "
3693                                     "(%llu bytes, Windows error %lu)\n",
3694                             (long long) layer, (long long) expert, (unsigned long long) whole,
3695                             (unsigned long) error);
3696                std::fflush(stderr);
3697                return 0;
3698            }
3699        }
3700        return whole;   // bytes advised, not a measurement of physical RAM reclaimed
3701    };
3702    if (role_ptr_.empty()) {
3703        const uint8_t* p = mapped_blob(layer, expert);
3704        return p == nullptr ? 0 : trim(p, layer_blob_bytes_[(size_t) layer]);
3705    }
3706    uint64_t bytes = 0;
3707    for (int r = 0; r < 3; ++r) {
3708        const size_t i = (size_t) (3 * layer + r);
3709        bytes += trim(role_ptr_[i] + (size_t) ((uint64_t) expert * role_bytes_[i]), role_bytes_[i]);
3710    }
3711    return bytes;
3712#else
3713    (void) layer; (void) expert;
3714    return 0;
3715#endif
3716}
3717
3718bool FileExpertSource::pin_cache_complement(
3719    const ExpertCache& cache, std::string& err, bool pin,
3720    const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs, int64_t lend_from_slot,
3721    uint64_t headroom_bytes, uint64_t budget_bytes, const std::vector<std::pair<int32_t, int32_t>>* rank) {
3722    err.clear();
3723    const auto pin_t0 = std::chrono::steady_clock::now();
3724    if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; }
3725    if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; }
3726    if (!cache.valid()) { err = "FileExpertSource: the GPU expert cache is not open"; return false; }
3727    if (cache.fills() != cache.resident()) {
3728        err = "FileExpertSource: the GPU expert cache is not fully filled";
3729        return false;
3730    }
3731    const cudaError_t sync = cudaDeviceSynchronize();
3732    if (sync != cudaSuccess) {
3733        err = std::string("FileExpertSource: GPU expert cache is not ready: ") + cudaGetErrorString(sync);
3734        (void) cudaGetLastError();
3735        return false;
3736    }
3737
3738    // The GPU cache's experts, and the bytes each slot's expert takes here (for the lend region below).
3739    const int64_t n_slots = cache.slots();
3740    std::vector<std::pair<int32_t, int32_t>> primary_gpu_pairs;
3741    std::vector<int32_t> pair_slot;
3742    std::vector<uint64_t> slot_bytes((size_t) std::max<int64_t>(n_slots, 0), 0);
3743    primary_gpu_pairs.reserve((size_t) cache.resident());
3744    pair_slot.reserve((size_t) cache.resident());
3745    for (int64_t layer = 0; layer < n_layers_; ++layer) {
3746        for (int64_t expert = 0; expert < n_expert_; ++expert) {
3747            const int32_t slot = cache.slot_of(layer, expert);
3748            if (slot == kNotResident) continue;
3749            primary_gpu_pairs.emplace_back((int32_t) layer, (int32_t) expert);
3750            pair_slot.push_back(slot);
3751            if (slot >= 0 && slot < n_slots) slot_bytes[(size_t) slot] = layer_blob_bytes_[(size_t) layer];
3752        }
3753    }
3754    std::vector<uint64_t> offsets;
3755    uint64_t bytes = 0;
3756    if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, primary_gpu_pairs,
3757                                            additional_gpu_pairs, offsets, bytes, err)) return false;
3758#if defined(_WIN32)
3759    // #467: the GPU cache's pre-fill touched its experts through the mapping (~19 GiB on a 24 GB card), and Windows
3760    // counts those file pages in this process's working set, not as available: a 32 GB PC read 0.44 GiB here
3761    // (20.7 GiB before the start).  Trimmed, they move to the standby list (still cached, counted as available).
3762    // Resident mode only: nothing else calls this function.  Locked/pinned pages stay; the rest fault back softly.
3763    {
3764        uint64_t before = 0, after = 0;
3765        const bool read_before = available_memory_bytes(before);
3766        (void) SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T) -1, (SIZE_T) -1);
3767        if (read_before && available_memory_bytes(after))
3768            std::fprintf(stderr, "FileExpertSource: available RAM %.2f GiB, %.2f GiB after the mapped experts left the "
3769                                 "process working set (#467)\n",
3770                         (double) before / 1073741824.0, (double) after / 1073741824.0);
3771    }
3772#endif
3773    const bool what_fits = budget_bytes == kResidentWhatFits;   // #467: the soft mode's second try
3774    int64_t budget_lent = 0, budget_lendable = 0;   // the lend region's slots kept by a budget (below), and its size
3775    uint64_t budget_physical = 0;   // #403: reuse the memory snapshot a budget was sized from
3776    uint64_t budget_commit = std::numeric_limits<uint64_t>::max();
3777    if (budget_bytes > 0) {
3778        // CS-T: a RAM budget.  The complement's experts in `rank` order (the expert profile, hottest first) while
3779        // they fit, the rest left on the mapped files; Windows commit capacity also limits the allocation (#730).
3780        uint64_t physical = 0;
3781        if (!available_memory_bytes(physical, &budget_commit)) {
3782            err = budget_automatic_ ? "FileExpertSource: cannot determine available memory for the automatic RAM copy"
3783                                    : "FileExpertSource: cannot determine available memory for --resident-budget-gib";
3784            return false;
3785        }
3786        budget_physical = physical;
3787        const uint64_t available = std::min(physical, budget_commit);
3788        const char* limit = budget_commit < physical ? "commit" : "RAM";
3789        const uint64_t clamped = detail::clamp_resident_budget(budget_bytes, physical, budget_commit, headroom_bytes);
3790        if (budget_bytes > clamped) {
3791            // #403: 256 MiB under the room, so the engine's own allocations after this reading still leave the
3792            // headroom (a budget clamped to exactly the room failed the safety check below on a reading a few MB
3793            // lower).  An unclamped budget is unchanged.
3794            // the automatic RAM copy names no flag: none was given (its line used to say --resident-budget-gib)
3795            const ResidentBudgetFrom from = what_fits ? ResidentBudgetFrom::WhatFits
3796                                          : budget_automatic_ ? ResidentBudgetFrom::Automatic : ResidentBudgetFrom::Flag;
3797            std::fputs(resident_clamp_line(from, budget_bytes, limit, available, headroom_bytes, clamped).c_str(), stderr);
3798            budget_bytes = clamped;
3799        }
3800        std::vector<uint64_t> ranked(offsets.size(), kNoComplement);
3801        uint64_t at = 0;
3802        int64_t held = 0;
3803        if (rank != nullptr)
3804            for (const auto& pr : *rank) {
3805                if (pr.first < 0 || pr.second < 0 || pr.first >= n_layers_ || pr.second >= n_expert_) continue;
3806                const size_t i = (size_t) pr.first * (size_t) n_expert_ + (size_t) pr.second;
3807                if (offsets[i] == kNoComplement || ranked[i] != kNoComplement) continue;   // on a GPU, or twice
3808                const uint64_t b = layer_blob_bytes_[(size_t) pr.first];
3809                if (b > budget_bytes - at) continue;
3810                ranked[i] = at;
3811                at += b;
3812                ++held;
3813            }
3814        if (what_fits && held == 0) {   // #467: nothing to keep - the caller's plain mmap fallback, not an empty copy
3815            err = "FileExpertSource: available memory cannot hold any expert of the complement";
3816            return false;
3817        }
3818        std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does "
3819                             "not hold, by profile rank; the rest are read from the files\n",
3820                     (double) budget_bytes / 1073741824.0, (long long) held, (double) bytes / 1073741824.0);
3821        // The prompt path's lend region under a budget.  Until now a budget turned the loan off (`lend_from_slot = -1`
3822        // below), so every lent slot's expert was read from the pack during every prompt chunk and again when the slot
3823        // was refilled after the prompt - even with room left in the budget.  Measured on an RX 6900 XT 16 GB with
3824        // --resident-budget-gib 71 and UD-Q4_K_XL: the copy kept all 63.47 GiB of the experts outside the cache, 7.5
3825        // GiB of the budget stayed unused, and every agent turn read 0.5-2.6 GB of the 1,231 lent slots' experts (3.6
3826        // GiB) from the GGUF (a fresh 17K-token prompt 24 GB).  As the unbudgeted path does, take the lend region's
3827        // experts from the last slot down (the order the borrowing takes them) while they fit in what the budget has
3828        // left; the ones past it keep the file fallback, and `rank` keeps its precedence (the hottest experts first).
3829        if (lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty()) {
3830            budget_lendable = n_slots - lend_from_slot;
3831            std::vector<size_t> order;   // the pairs in the lend region, highest slot first
3832            for (size_t i = 0; i < primary_gpu_pairs.size(); ++i)
3833                if (pair_slot[i] >= lend_from_slot && pair_slot[i] < n_slots) order.push_back(i);
3834            std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return pair_slot[a] > pair_slot[b]; });
3835            const uint64_t at0 = at;
3836            for (size_t i : order) {
3837                const auto& pr = primary_gpu_pairs[i];
3838                const size_t idx = (size_t) pr.first * (size_t) n_expert_ + (size_t) pr.second;
3839                const uint64_t b = layer_blob_bytes_[(size_t) pr.first];
3840                if (b > budget_bytes - at) break;   // a contiguous tail of the region: a short prompt lends only the last few
3841                if (ranked[idx] != kNoComplement) continue;
3842                ranked[idx] = at;
3843                at += b;
3844                ++budget_lent;
3845            }
3846            std::fprintf(stderr, "FileExpertSource: the prompt path's lend region: %lld of its %lld slots keep their experts "
3847                                 "in RAM too (%.2f GiB of the budget's remaining %.2f GiB)\n",
3848                         (long long) budget_lent, (long long) budget_lendable, (double) (at - at0) / 1073741824.0,
3849                         (double) (budget_bytes - at0) / 1073741824.0);
3850        }
3851        offsets.swap(ranked);
3852        bytes = at;
3853        lend_from_slot = -1;
3854    }
3855
3856    const bool lend = lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty();
3857    uint64_t budget = std::numeric_limits<uint64_t>::max();
3858    if (bytes > 0 || lend) {
3859        // #403: with a budget, the reading it was sized from - a second reading a few MB lower (the engine's own
3860        // allocations, the file cache) failed a budget the first one had clamped.  (A budget turns `lend` off.)
3861        uint64_t physical = budget_physical;
3862        uint64_t commit = budget_commit;
3863        if (physical == 0 && !available_memory_bytes(physical, &commit)) {
3864            err = "FileExpertSource: cannot determine available memory for the resident-memory safety check";
3865            return false;
3866        }
3867        const uint64_t available = std::min(physical, commit);
3868        budget = available > headroom_bytes ? available - headroom_bytes : 0;
3869        if (bytes > budget) {
3870            char message[320];
3871            std::snprintf(message, sizeof message,
3872                          "FileExpertSource: resident complement %.2f GiB exceeds available %s (%.2f GiB) minus the "
3873                          "%.0f GiB safety headroom",
3874                          (double) bytes / 1073741824.0, commit < physical ? "commit" : "RAM",
3875                          (double) available / 1073741824.0, (double) headroom_bytes / 1073741824.0);
3876            err = message;
3877#if defined(__linux__)
3878            if (std::ifstream mi("/proc/meminfo"); mi) {
3879                std::stringstream mt;
3880                mt << mi.rdbuf();
3881                err += detail::page_cache_hint(mt.str());
3882            }
3883#endif
3884            return false;
3885        }
3886    }
3887    // The prompt path's lend region: its slots' experts are streamed from here during a prompt and copied back into
3888    // their slots after it, so the ones that fit are kept here too (from the last slot down: a short prompt lends
3889    // only the last few).  The rest keep the mapped-file fallback.
3890    int64_t keep_from = n_slots;
3891    if (lend) {
3892        keep_from = detail::choose_resident_keep_from(slot_bytes, bytes, budget, lend_from_slot);
3893        if (keep_from < 0) keep_from = n_slots;
3894        if (keep_from < n_slots) {
3895            std::vector<std::pair<int32_t, int32_t>> core;
3896            core.reserve(primary_gpu_pairs.size());
3897            for (size_t i = 0; i < primary_gpu_pairs.size(); ++i)
3898                if (pair_slot[i] < keep_from) core.push_back(primary_gpu_pairs[i]);
3899            if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, core,
3900                                                    additional_gpu_pairs, offsets, bytes, err)) return false;
3901        }
3902    }
3903
3904    // A layer split: generate hands the copy every stage's lend region (`stage_lend_regions`, set before the
3905    // call).  The prompt path borrows the tail slots of EVERY part's cache, and with `additional_gpu_pairs`
3906    // non-empty the single lend region above is off - so without this the borrowed experts sat in neither
3907    // VRAM nor RAM during a prompt and came back through page faults from the mapped shards: measured
3908    // 2026-10-06 on an RTX 2000 Ada + 5060 Ti rig (17/48 split, IQ3_S mapped from the GGUF, --prefill auto,
3909    // one 73K-token prompt) 3.7 GiB read from the NVMe for the one prompt (arena mode reads 1.1 GiB), and one
3910    // 8192-token chunk spent 1.5 s of its 3.9 s on host staging (arena: 0.37 s).  The regions walk each
3911    // stage's highest slots first, as the borrowing does; the whole copy - complement and regions
3912    // together - stays within one budget, and experts past it keep the file fallback they had.
3913    int64_t stage_lent = 0;
3914    uint64_t stage_lent_bytes = 0;
3915    if (!stage_lend_regions_.empty()) {
3916        if (budget == std::numeric_limits<uint64_t>::max()) {   // #403: the one reading, taken now
3917            uint64_t physical = budget_physical, commit = budget_commit;
3918            if (physical == 0 && !available_memory_bytes(physical, &commit)) {
3919                err = "FileExpertSource: cannot determine available memory for the stage lend regions";
3920                return false;
3921            }
3922            const uint64_t available = std::min(physical, commit);
3923            budget = available > headroom_bytes ? available - headroom_bytes : 0;
3924        }
3925        uint64_t cap = budget;   // an explicit --resident-budget-gib caps the whole copy, regions included
3926        if (budget_bytes > 0 && budget_bytes != kResidentWhatFits && budget_bytes < cap) cap = budget_bytes;
3927        const uint64_t before = bytes;
3928        stage_lent = detail::append_stage_lend_regions(n_layers_, n_expert_, layer_blob_bytes_, offsets, bytes, cap,
3929                                                       stage_lend_regions_, err);
3930        if (stage_lent < 0) return false;
3931        stage_lent_bytes = bytes - before;
3932    }
3933
3934    void* arena = nullptr;
3935    const uint8_t* host = nullptr;
3936    const uint8_t* device = nullptr;
3937    bool pinned_ok = false;
3938    bool paced = false;         ///< #1250: the pages are taken in steps and page-locked afterwards
3939    uint64_t locked = 0;
3940    uint64_t partial_pin = 0;   ///< CS-T: a registered prefix of a locked arena
3941    uint64_t lock_off = 0;      ///< where the working-set lock starts (after the registered prefix)
3942    std::string note;
3943#if defined(__linux__)
3944    NumaComplementPlacement numa;   ///< STRATA_NUMA_SPLIT step B; inert unless the live pool split on real nodes
3945#endif
3946    auto release = [&]() {
3947        if (arena == nullptr) return;
3948        if (pinned_ok) (void) cudaFreeHost(arena);
3949        else {
3950            if (partial_pin > 0) (void) cudaHostUnregister(arena);
3951            if (locked > 0) strata::platform::unlock_resident((uint8_t*) arena + lock_off, locked);
3952            std::free(arena);
3953        }
3954        arena = nullptr;
3955    };
3956#if defined(__linux__)
3957    // #1250: the cached pages of the model files this source maps (the engine read them itself), given back
3958    auto drop_file_cache = [&]() {
3959        auto drop = [](const uint8_t* at, uint64_t len, int fd) {
3960            if (at != nullptr && len > 0) (void) madvise((void*) at, (size_t) len, MADV_DONTNEED);
3961            if (fd >= 0) (void) posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
3962        };
3963        if (maps_.empty()) drop(base_, mapped_bytes_, fd_);
3964        else for (const Map& m : maps_) drop(m.closed ? nullptr : m.base, m.bytes, m.fd);
3965        // the files read at start outside this source (set_extra_drop_files): their pages are already copied to VRAM
3966        // or RAM, and they sat on whichever node read them (~2.2 GiB on node 0 measured on the 3090 box)
3967        // CBA: whole files by path; a file read at start but not listed stays cached (the per-node free line shows
3968        // it), a registry of the files the loaders open if that ever bites
3969        for (const std::string& p : extra_drop_files_) {
3970            const int fd = ::open(p.c_str(), O_RDONLY | O_CLOEXEC);
3971            if (fd >= 0) {
3972                (void) posix_fadvise(fd, 0, 0, POSIX_FADV_DONTNEED);
3973                ::close(fd);
3974            }
3975        }
3976    };
3977#endif
3978    if (bytes > 0) {
3979        std::fprintf(stderr, "FileExpertSource: allocating %.2f GiB %s cache complement\n",
3980                     (double) bytes / 1073741824.0, pin ? "page-locked" : "pageable resident");
3981        log_complement_memory("before complement allocation", bytes);
3982        std::fflush(stderr);
3983        // #1250: the driver takes page-locked pages in one go and cannot wait for the kernel to reclaim file cache: with
3984        // the cache of the model files the engine read itself in the way (MemFree low, MemAvailable high) a host was
3985        // OOM-killed here.  First give those pages back (the engine's own mappings); when what is really free still
3986        // does not cover the complement, register it in steps, each only while the RAM left stays above the reserve.
3987        // STRATA_PIN_GUARD=0 pages-locks in one go as before, =2 always registers in steps (a test); STRATA_PIN_RESERVE_GIB
3988        // is the RAM that must stay above every step (default: the resident headroom, at least 2 GiB)
3989        // STRATA_NUMA_SPLIT placement forces the drop and the paced path whatever the guard (STRATA_PIN_GUARD=0 included)
3990        const uint64_t pace_reserve = [&] {
3991            const char* v = std::getenv("STRATA_PIN_RESERVE_GIB");
3992            return v != nullptr && std::atof(v) > 0 ? (uint64_t) (std::atof(v) * 1073741824.0)
3993                                                     : std::max<uint64_t>(headroom_bytes, 2ull << 30);
3994        }();
3995#if defined(__linux__)
3996        if (pin) {
3997            static const int guard = [] {
3998                const char* v = std::getenv("STRATA_PIN_GUARD");
3999                return v == nullptr ? 1 : std::atoi(v);
4000            }();
4001            uint64_t free_now = 0;
4002            numa.init(offsets, n_expert_, layer_blob_bytes_, role_bytes_);   // STRATA_NUMA_SPLIT: placed by the paced loop
4003            if (numa.place) {
4004                // the engine's own mapped model pages sit on whichever node read them, and a toucher on a full node
4005                // gets its pages from the other one (no local reclaim): give them back first, as the guard=1 path does
4006                drop_file_cache();
4007                numa.free_after = NumaComplementPlacement::node_free();
4008                std::fprintf(stderr, "FileExpertSource: NUMA placement: the model files' cached pages were released; "
4009                                     "free after the drop: %s\n",
4010                             NumaComplementPlacement::free_text(numa.free_after).c_str());
4011                // CBA: half the pace reserve as each node's share of the headroom; a per-node reserve if one node
4012                // carries the host's other allocations
4013                numa.check_room(pace_reserve / 2);
4014                if (guard == 0)
4015                    std::fprintf(stderr, "FileExpertSource: STRATA_PIN_GUARD=0 overridden: NUMA placement needs the "
4016                                         "paced path\n");
4017            }
4018            if (guard == 2 || numa.place) {
4019                paced = true;
4020                std::fprintf(stderr, "FileExpertSource: %s: page-locking the complement in steps\n",
4021                             guard == 2 ? "STRATA_PIN_GUARD=2" : "STRATA_NUMA_SPLIT");
4022            } else if (guard != 0 && free_memory_bytes(free_now) &&
4023                       detail::pin_depends_on_reclaim(free_now, bytes, pace_reserve)) {
4024                drop_file_cache();
4025                const uint64_t before = free_now;
4026                if (free_memory_bytes(free_now))
4027                    std::fprintf(stderr, "FileExpertSource: %.2f GiB really free for a %.2f GiB page-locked complement; "
4028                                         "the model files' cached pages were released: %.2f GiB free\n",
4029                                 (double) before / 1073741824.0, (double) bytes / 1073741824.0,
4030                                 (double) free_now / 1073741824.0);
4031                paced = detail::pin_depends_on_reclaim(free_now, bytes, pace_reserve);
4032                if (paced)
4033                    std::fprintf(stderr, "FileExpertSource: the rest comes from reclaimed cache of other files: "
4034                                         "page-locking it in steps, as far as the RAM allows (#1250)\n");
4035            }
4036        } else if (strata::kernels::cpu::active_numa_split().on && !strata::kernels::cpu::active_numa_split().test) {
4037            std::fprintf(stderr, "FileExpertSource: WARNING: NUMA placement FAILED: the complement is not page-locked, "
4038                                 "nothing placed\n");
4039        }
4040#endif
4041        if (pin && !paced) {
4042            const cudaError_t allocated = cudaHostAlloc(&arena, (size_t) bytes,
4043                                                         cudaHostAllocMapped | cudaHostAllocPortable);
4044            if (allocated == cudaSuccess) {
4045                void* alias = nullptr;
4046                const cudaError_t aliased = cudaHostGetDevicePointer(&alias, arena, 0);
4047                if (aliased == cudaSuccess && alias != nullptr) {
4048                    device = (const uint8_t*) alias;
4049                    pinned_ok = true;
4050                    note = "page-locked and mapped";
4051                } else {
4052                    note = std::string("no device alias (") + cudaGetErrorString(aliased) + ")";
4053                    (void) cudaGetLastError();
4054                    (void) cudaFreeHost(arena);
4055                    arena = nullptr;
4056                }
4057            } else {
4058                // Refused (the driver's page-locked limit): the same bytes in ordinary memory, locked in the working
4059                // set instead, as the arena does - resident either way, only copied by the CPU instead of by DMA.
4060                note = std::string("page-locking refused (") + cudaGetErrorString(allocated) + ")";
4061                (void) cudaGetLastError();
4062                arena = nullptr;
4063            }
4064        }
4065        if (arena == nullptr) {
4066            if (!note.empty()) {
4067                std::fprintf(stderr, "FileExpertSource: %s; trying pageable memory\n", note.c_str());
4068                log_complement_memory("before pageable allocation", bytes);
4069                std::fflush(stderr);
4070            }
4071            errno = 0;
4072            if (paced) {   // page-aligned: the steps are registered on page boundaries
4073#if !defined(_WIN32)
4074                void* aligned = nullptr;
4075                const uint64_t page = 4096;
4076                if (posix_memalign(&aligned, (size_t) page, (size_t) ((bytes + page - 1) / page * page)) == 0) arena = aligned;
4077#endif
4078#if defined(__linux__)
4079                // STRATA_NUMA_SPLIT: a 2 MiB huge page would put several slices on its toucher's node, so the arena
4080                // takes 4 KiB pages (one call, no VMA split)
4081                if (arena != nullptr && numa.place) {
4082                    if (madvise(arena, (size_t) ((bytes + page - 1) / page * page), MADV_NOHUGEPAGE) != 0)
4083                        std::fprintf(stderr, "FileExpertSource: WARNING: madvise(MADV_NOHUGEPAGE) on the complement "
4084                                             "failed (errno %d)\n", errno);
4085                }
4086#endif
4087            } else {
4088                arena = std::malloc((size_t) bytes);
4089            }
4090            if (arena == nullptr) {
4091                const int allocation_errno = errno;
4092                err = "FileExpertSource: pageable resident complement allocation failed (malloc errno " +
4093                      std::to_string(allocation_errno) + ": " + std::strerror(allocation_errno) + ")";
4094                if (!note.empty()) err += "; " + note;
4095                log_complement_memory("after pageable allocation failure", bytes);
4096                return false;
4097            }
4098            if (pin) {
4099                // CS-T, a RAM budget: its bytes are in profile order, hottest first, so the driver is asked to
4100                // register the largest prefix it takes (from the cap down in 2 GiB steps).  Those experts can be
4101                // read by the GPU over PCIe (--pcie-frac) and copied by DMA; only the rest is locked in the working
4102                // set (the registered prefix is page-locked by the driver already - locking it twice made the next
4103                // device allocation fail).
4104                // opt-in (STRATA_PARTIAL_PIN=1): on the RTX 5070 PC the GPU's PCIe share of the misses measured no
4105                // faster than the CPU computing them (7.30 / 7.44 tok/s with 24 / 16 GiB registered against 7.05-7.74
4106                // unpinned at a 40 GiB budget), and registering adds startup time and driver memory pressure
4107                static const bool partial_on = [] {
4108                    const char* v = std::getenv("STRATA_PARTIAL_PIN");
4109                    return v != nullptr && std::atoi(v) != 0;
4110                }();
4111                // at most STRATA_PARTIAL_PIN_GIB (default 24): registering 30 GiB of a 40 GiB arena left the driver
4112                // unable to page-lock the prompt path's small buffers afterwards (RTX 5070, WDDM)
4113                static const uint64_t pin_cap = [] {
4114                    const char* v = std::getenv("STRATA_PARTIAL_PIN_GIB");
4115                    return (uint64_t) ((v != nullptr && std::atof(v) > 0 ? std::atof(v) : 24.0) * 1073741824.0);
4116                }();
4117                if (paced) {
4118                    // #1250: the pages are taken in 1 GiB steps by ordinary page faults (which reclaim file cache as
4119                    // they need to), each only while the RAM available (the cgroup's room included) stays above the
4120                    // reserve; then the pages that are there are page-locked in ONE registration (nothing is
4121                    // allocated then, the driver only pins them), so a blob never straddles two registrations.  The
4122                    // hottest experts come first in the arena: they are the pinned ones; the rest is locked pageable
4123                    // memory, as when the driver refuses the page-locking.
4124                    constexpr uint64_t kStep = 1ull << 30, kPage = 4096;
4125                    uint64_t got = 0;
4126                    const char* stop = nullptr;
4127                    while (got < bytes) {
4128                        const uint64_t step = std::min<uint64_t>(kStep, bytes - got);
4129                        uint64_t avail_now = 0;
4130                        if (!available_memory_bytes(avail_now) || !detail::pin_step_fits(avail_now, step, pace_reserve)) {
4131                            stop = "the RAM left would fall under the reserve";
4132                            break;
4133                        }
4134#if defined(__linux__)
4135                        if (numa.place) numa.touch_step((uint8_t*) arena, got, got + step);   // slices on their nodes
4136                        else
4137#endif
4138                            for (uint64_t at = got; at < got + step; at += kPage) ((volatile uint8_t*) arena)[at] = 0;
4139                        got += step;
4140                    }
4141                    // cut at an expert boundary: a blob that runs past the registered range would be refused by a
4142                    // cudaMemcpyAsync as not page-locked
4143                    uint64_t w = got;
4144                    for (size_t i = 0; i < offsets.size() && w < bytes; ++i) {
4145                        if (offsets[i] == kNoComplement) continue;
4146                        const uint64_t b = layer_blob_bytes_[i / (size_t) n_expert_];
4147                        if (offsets[i] < got && offsets[i] + b > got) { w = offsets[i]; break; }
4148                    }
4149                    if (w > 0) {
4150                        if (cudaHostRegister(arena, (size_t) w, cudaHostRegisterMapped | cudaHostRegisterPortable) ==
4151                            cudaSuccess) {
4152                            void* alias = nullptr;
4153                            if (cudaHostGetDevicePointer(&alias, arena, 0) == cudaSuccess && alias != nullptr) {
4154                                device = (const uint8_t*) alias;
4155                                partial_pin = w;
4156                            } else {
4157                                (void) cudaGetLastError();
4158                                (void) cudaHostUnregister(arena);
4159                                if (stop == nullptr) stop = "no device alias";
4160                            }
4161                        } else {
4162                            (void) cudaGetLastError();
4163                            if (stop == nullptr) stop = "the driver refused to page-lock it";
4164                        }
4165                    }
4166                    lock_off = partial_pin;
4167                    char msg[240];
4168                    if (stop != nullptr)
4169                        std::snprintf(msg, sizeof msg, "WARNING: only %.2f of %.2f GiB could be page-locked (%s); the rest is "
4170                                      "resident but pageable, so its copies to the GPU go through the CPU (#1250)",
4171                                      (double) partial_pin / 1073741824.0, (double) bytes / 1073741824.0, stop);
4172                    else
4173                        std::snprintf(msg, sizeof msg, "%.2f GiB page-locked after taking the pages in steps",
4174                                      (double) partial_pin / 1073741824.0);
4175                    note += std::string(note.empty() ? "" : "; ") + msg;
4176                    if (stop != nullptr) std::fprintf(stderr, "FileExpertSource: %s\n", msg);
4177#if defined(__linux__)
4178                    // judged on the final state: registered pages no longer move; before the copy fills them
4179                    if (numa.place) numa.report((const uint8_t*) arena, got, partial_pin, bytes, stop);
4180#endif
4181                } else if (budget_bytes > 0 && partial_on) {
4182                    const uint64_t step = 2ull << 30;
4183                    for (uint64_t want = std::min(bytes, pin_cap); want >= step; want = want > step ? want - step : 0) {
4184                        // cut at an expert boundary: a blob that started inside the registered range and ran past it
4185                        // would be taken as page-locked by a cudaMemcpyAsync and refused ("adaptive refill failed")
4186                        uint64_t w = want;
4187                        for (size_t i = 0; i < offsets.size(); ++i) {
4188                            if (offsets[i] == kNoComplement) continue;
4189                            const uint64_t b = layer_blob_bytes_[i / (size_t) n_expert_];
4190                            if (offsets[i] < want && offsets[i] + b > want) { w = offsets[i]; break; }
4191                        }
4192                        if (w == 0) break;
4193                        if (cudaHostRegister(arena, (size_t) w, cudaHostRegisterMapped | cudaHostRegisterPortable) ==
4194                            cudaSuccess) {
4195                            void* alias = nullptr;
4196                            if (cudaHostGetDevicePointer(&alias, arena, 0) == cudaSuccess && alias != nullptr) {
4197                                device = (const uint8_t*) alias;
4198                                partial_pin = w;
4199                            } else {
4200                                (void) cudaGetLastError();
4201                                (void) cudaHostUnregister(arena);
4202                            }
4203                            break;
4204                        }
4205                        (void) cudaGetLastError();
4206                        if (want <= step) break;
4207                    }
4208                    char msg[160];
4209                    std::snprintf(msg, sizeof msg, "%.2f GiB of it registered for the GPU (the hottest)",
4210                                  (double) partial_pin / 1073741824.0);
4211                    note += std::string("; ") + msg;
4212                }
4213                if (!paced) lock_off = partial_pin;
4214                // (paced: lock_off was set above)
4215                const strata::platform::LockResult lr =
4216                    lock_off < bytes ? strata::platform::lock_resident((uint8_t*) arena + lock_off, bytes - lock_off)
4217                                     : strata::platform::LockResult{true, 0, ""};
4218                locked = lr.locked_bytes;
4219                note += (note.empty() ? "" : "; ") + lr.note;
4220            }
4221        }
4222        host = (const uint8_t*) arena;
4223    }
4224
4225    // Copied layer by layer on a few threads: the page faults of the mapped file are the cost, and they overlap.
4226#if !defined(_WIN32)
4227    const long page_size = sysconf(_SC_PAGESIZE);
4228    if (page_size <= 0) {
4229        err = "FileExpertSource: cannot determine page size for mapped-page release";
4230        release();
4231        return false;
4232    }
4233#endif
4234    std::atomic<int64_t> next_layer{0}, layers_done{0};
4235    std::atomic<uint64_t> copied{0};
4236    std::atomic<bool> failed{false};
4237    std::mutex fail_mu;
4238    const auto copy_t0 = std::chrono::steady_clock::now();
4239    std::string fail_msg;
4240    auto fail = [&](const std::string& m) {
4241        std::lock_guard<std::mutex> lock(fail_mu);
4242        if (fail_msg.empty()) fail_msg = m;
4243        failed.store(true);
4244    };
4245    auto worker = [&]() {
4246        for (;;) {
4247            const int64_t layer = next_layer.fetch_add(1);
4248            if (layer >= n_layers_ || failed.load()) return;
4249            const uint64_t blob_bytes = layer_blob_bytes_[(size_t) layer];
4250            std::vector<Fill> batch;   // #286, unbuffered: 32 blobs' reads in flight at once, merged where near
4251            auto flush = [&]() {
4252                if (batch.empty()) return true;
4253                bool ok = read_direct(batch.data(), batch.size());
4254                for (size_t i = 0; !ok && i < batch.size(); ++i)
4255                    if (!copy_from_files(batch[i].layer, batch[i].e, batch[i].dst)) return false;
4256                copied.fetch_add(blob_bytes * (uint64_t) batch.size());
4257                batch.clear();
4258                return true;
4259            };
4260            if (direct_.empty()) {   // mapped reads: ask for the layer's blobs before copying them
4261                std::vector<std::pair<int32_t, int32_t>> ahead;
4262                for (int64_t expert = 0; expert < n_expert_; ++expert)
4263                    if (offsets[(size_t) layer * (size_t) n_expert_ + (size_t) expert] != kNoComplement)
4264                        ahead.emplace_back((int32_t) layer, (int32_t) expert);
4265                (void) advise_pairs(ahead.data(), (int64_t) ahead.size());
4266            }
4267            for (int64_t expert = 0; expert < n_expert_; ++expert) {
4268                const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
4269                const uint64_t offset = offsets[index];
4270                if (offset == kNoComplement) continue;
4271                if (offset > bytes || blob_bytes > bytes - offset) {
4272                    fail("FileExpertSource: invalid blob bounds while building the cache complement");
4273                    return;
4274                }
4275                uint8_t* dst = (uint8_t*) host + (size_t) offset;
4276                if (!direct_.empty()) {
4277                    batch.push_back({0, layer, expert, dst});
4278                    if (batch.size() == 32 && !flush()) {
4279                        fail("FileExpertSource: an expert could not be read while building the cache complement");
4280                        return;
4281                    }
4282                    continue;
4283                }
4284                if (!copy_from_files(layer, expert, dst)) {
4285                    fail("FileExpertSource: invalid blob bounds while building the cache complement");
4286                    return;
4287                }
4288                copied.fetch_add(blob_bytes);
4289            }
4290            if (!flush()) {
4291                fail("FileExpertSource: an expert could not be read while building the cache complement");
4292                return;
4293            }
4294#if !defined(_WIN32)
4295            if (role_ptr_.empty()) {   // experts.bin; the GGUF in place leaves its pages to the OS
4296            const uint64_t layer_offset = layer_offsets_[(size_t) layer];
4297            const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_;
4298            const uint64_t layer_end = layer_offset + layer_bytes;
4299            const uint64_t page = (uint64_t) page_size;
4300            const uint64_t advice_start = layer_offset - layer_offset % page;
4301            const uint64_t end_remainder = layer_end % page;
4302            const uint64_t extra = end_remainder == 0 ? 0 : page - end_remainder;
4303            const uint64_t advice_end = extra > mapped_bytes_ - layer_end ? mapped_bytes_ : layer_end + extra;
4304            if (advice_end > advice_start &&
4305                madvise((void*) (base_ + (size_t) advice_start), (size_t) (advice_end - advice_start), MADV_DONTNEED) != 0) {
4306                fail("FileExpertSource: madvise could not release mapped expert layer " + std::to_string(layer));
4307                return;
4308            }
4309#if !defined(__APPLE__)   // macOS has no posix_fadvise; the madvise above already released the mapping
4310            if (posix_fadvise(fd_, (off_t) layer_offset, (off_t) layer_bytes, POSIX_FADV_DONTNEED) != 0) {
4311                fail("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer));
4312                return;
4313            }
4314#endif
4315            }
4316#endif
4317            const int64_t done = layers_done.fetch_add(1) + 1;
4318#if defined(_WIN32)
4319            // R5070: the copy reads through the mapped view, and Windows counts those file pages in this process's working
4320            // set, not as available: on the owner's 64 GB PC (8 GiB headroom asked for) available RAM fell to 0.9 GiB for
4321            // ~10 s during the copy.  Every 4 layers the mapped pages go to the standby list (VirtualUnlock on pages that
4322            // are not locked does exactly that; the same call runs once after the copy below).  No data changes.
4323            if (done % 4 == 0 && direct_.empty() && maps_.empty() && !unmapped_) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_);
4324            if (done % 4 == 0 && direct_.empty()) for (const Map& m : maps_) if (!m.closed) (void) VirtualUnlock((LPVOID) m.base, (SIZE_T) m.bytes);
4325#endif
4326            if (done % 8 == 0 || done == n_layers_)
4327                std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB, %.0f s)\n",
4328                             (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0,
4329                             std::chrono::duration<double>(std::chrono::steady_clock::now() - copy_t0).count());
4330        }
4331    };
4332    {
4333        const int threads = (int) std::max<int64_t>(1, std::min<int64_t>(6, n_layers_));
4334        std::vector<std::thread> pool;
4335        for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
4336        worker();
4337        for (auto& t : pool) t.join();
4338    }
4339    std::fflush(stderr);
4340    if (failed.load()) {
4341        err = fail_msg;
4342        release();
4343        return false;
4344    }
4345#if defined(_WIN32)
4346    // The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the
4347    // standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED).
4348    // Not with the view closed (begin_startup_unbuffered): its range may hold other memory by now.
4349    if (maps_.empty() && !unmapped_) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_);
4350    for (const Map& m : maps_) if (!m.closed) (void) VirtualUnlock((LPVOID) m.base, (SIZE_T) m.bytes);
4351#endif
4352    if (std::getenv("STRATA_VERIFY_COMPLEMENT") != nullptr && host != nullptr && bytes > 0) {
4353        // tests: the copy's checksum (FNV-1a of each 1 GiB piece on its own thread, then of those), any reader
4354        constexpr uint64_t kPiece = 1ull << 30;
4355        const size_t pieces = (size_t) ((bytes + kPiece - 1) / kPiece);
4356        std::vector<uint64_t> ph(pieces, 0);
4357        std::atomic<size_t> next_piece{0};
4358        auto hash_work = [&] {
4359            for (size_t i; (i = next_piece.fetch_add(1)) < pieces;)
4360                ph[i] = fnv1a64(host + (size_t) (i * kPiece), std::min<uint64_t>(kPiece, bytes - i * kPiece));
4361        };
4362        std::vector<std::thread> hth;
4363        for (int t = 1; t < 8; ++t) hth.emplace_back(hash_work);
4364        hash_work();
4365        for (auto& t : hth) t.join();
4366        uint64_t h = fnv1a64((const uint8_t*) offsets.data(), (uint64_t) (offsets.size() * sizeof(uint64_t)));
4367        h = fnv1a64((const uint8_t*) ph.data(), (uint64_t) (ph.size() * sizeof(uint64_t)), h);
4368        std::fprintf(stderr, "FileExpertSource: cache complement checksum %016llx (%.2f GiB, its offsets included)\n",
4369                     (unsigned long long) h, (double) bytes / 1073741824.0);
4370    }
4371
4372    complement_arena_ = arena;
4373    complement_host_ = host;
4374    complement_device_ = device;
4375    complement_bytes_ = bytes;
4376    complement_offsets_ = std::move(offsets);
4377    complement_pinned_ = (pinned_ok || partial_pin > 0) && bytes > 0;
4378    complement_pin_limit_ = pinned_ok ? bytes : partial_pin;
4379    complement_registered_ = !pinned_ok && partial_pin > 0;
4380    // a paced registration that covers the whole arena is as good as a cudaHostAlloc'd one
4381    complement_partial_ = complement_registered_ && !(paced && partial_pin >= bytes);
4382    complement_locked_ = locked;
4383    complement_lock_off_ = lock_off;
4384    complement_lent_slots_ = lend ? n_slots - keep_from : budget_lent;   // a budget keeps its own tail of the region
4385    complement_lent_slots_ += stage_lent;   // and the split stages' regions: pairs the copy kept of them
4386    complement_ready_ = true;
4387    std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB in %.0f s%s%s\n",
4388                 complement_pinned_ ? "mapped pinned" : pin ? "locked resident" : "pageable resident",
4389                 (double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0,
4390                 std::chrono::duration<double>(std::chrono::steady_clock::now() - pin_t0).count(),
4391                 note.empty() ? "" : "; ", note.c_str());
4392    const int64_t lendable_all = lend ? n_slots - lend_from_slot : budget_lendable;   // 0: no lend region at all
4393    if (lendable_all > 0)
4394        std::fprintf(stderr, "FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM "
4395                             "too%s\n", (long long) (lend ? n_slots - keep_from : budget_lent), (long long) lendable_all,
4396                     (lend ? n_slots - keep_from : budget_lent) < lendable_all
4397                         ? " (the others are read from the file when lent: not enough RAM for them)" : "");
4398    if (lendable_all > 0 && (lend ? n_slots - keep_from : budget_lent) < lendable_all) {
4399        // #1389: below full coverage the uncovered experts are read from the pack during a long prompt (a 74K prompt
4400        // routes through nearly all experts, so the misses repeat). The reporter measured 18% uncovered = -26% prompt
4401        // speed on a gfx1100; short prompts barely touch them. A warning, not a refusal.
4402        const long long lendable = (long long) lendable_all;
4403        const long long missing = lendable - (long long) (lend ? n_slots - keep_from : budget_lent);
4404        std::fprintf(stderr, "FileExpertSource: WARNING: %lld of %lld lendable slots (%.0f%%) will read their experts from the pack "
4405                             "during a long prompt; expect a slower prompt read on 50K+ token prompts (one measurement: 18%% uncovered "
4406                             "cost 26%%). %s and restart; the line above should read N of N.\n", missing, lendable,
4407                     100.0 * (double) missing / (double) std::max<long long>(1, lendable),
4408                     lend ? "Free RAM or lower STRATA_RESIDENT_HEADROOM_GIB (now the RAM left free at start)"
4409                          : budget_automatic_ ? "Free more RAM for the automatic RAM copy (the lend region comes after the ranked experts)"
4410                                              : "Raise --resident-budget-gib (the lend region comes after the ranked experts)");
4411    }
4412    if (!stage_lend_regions_.empty()) {
4413        int64_t offered = 0;
4414        for (const auto& region : stage_lend_regions_) offered += (int64_t) region.size();
4415        std::fprintf(stderr, "FileExpertSource: the split stages lend %lld slots to the prompt path: %lld keep "
4416                             "their experts in RAM too (%.2f GiB)%s\n",
4417                     (long long) offered, (long long) stage_lent, (double) stage_lent_bytes / 1073741824.0,
4418                     stage_lent < offered ? " (the rest are read from the file when lent: not enough RAM for them)" : "");
4419    }
4420    if (!additional_gpu_pairs.empty()) {
4421        std::fprintf(stderr, "FileExpertSource: %zu verified additional-GPU experts remain on the mmap fallback\n",
4422                     additional_gpu_pairs.size());
4423    }
4424    std::fflush(stderr);
4425    return true;
4426}
4427
4428const uint8_t* FileExpertSource::resident_blob(size_t index) const {
4429    if (exchange_storage_.active()) return exchange_storage_.resident(index).host;
4430    return detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);
4431}
4432
4433bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const {
4434    if (!complement_ready_ || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
4435    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
4436    return resident_blob(index) != nullptr;
4437}
4438
4439bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err, int64_t bounce) {
4440    err.clear();
4441    if (n <= xstage_cap_) return true;
4442    if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; }
4443    if (exchange_storage_.active()) {
4444        err = "FileExpertSource: reserve maximum exchange capacity before enabling rotation";
4445        return false; // the original exchange allocation can now contain live resident experts
4446    }
4447    uint64_t blob = 0;
4448    for (const uint64_t b : layer_blob_bytes_) blob = std::max(blob, b);
4449    if (blob == 0 || n <= 0) { err = "FileExpertSource: no expert geometry for the exchange buffers"; return false; }
4450    if (xstage_ != nullptr) {
4451        if (xstage_pinned_) (void) cudaFreeHost(xstage_);
4452        else std::free(xstage_);
4453        xstage_ = nullptr;
4454        xstage_cap_ = 0;
4455    }
4456    if ((uint64_t)n > std::numeric_limits<size_t>::max() / blob) {
4457        err = "FileExpertSource: exchange allocation size overflow"; return false;
4458    }
4459    const char* rotate_env = std::getenv("STRATA_EXCHANGE_ROTATE");
4460    const bool requested = rotate_env && std::strcmp(rotate_env, "1") == 0;
4461    // layers of several block sizes (a GGUF's mixed i-quants): spares of every size, see ExchangeStorage
4462    bounce = std::max<int64_t>(0, std::min(bounce, n));
4463    const uint64_t rotate_total = detail::ExchangeStorage::exchange_bytes_needed(layer_blob_bytes_, (size_t) n, (size_t) bounce);
4464    const bool eligible = requested && rotate_total != 0 && rotate_total <= std::numeric_limits<size_t>::max() &&
4465                          complement_pinned_ && !complement_partial_ &&
4466                          complement_host_ && complement_device_ && complement_bytes_ > 0;
4467    const size_t total = eligible ? (size_t) rotate_total : (size_t) n * (size_t) blob;
4468    void* p = nullptr;
4469    if (cudaHostAlloc(&p, total, eligible ? cudaHostAllocMapped : cudaHostAllocDefault) == cudaSuccess && p != nullptr) {
4470        xstage_pinned_ = true;
4471    } else {
4472        (void) cudaGetLastError();
4473        p = std::malloc(total);
4474        xstage_pinned_ = false;
4475        if (p == nullptr) { err = "FileExpertSource: cannot allocate the exchange buffers"; return false; }
4476    }
4477    xstage_ = (uint8_t*) p;
4478    xstage_cap_ = n;
4479    xstage_blob_ = blob;
4480    if (requested) {
4481        std::string reason = "requires a fully mapped/pinned RAM complement";
4482        void* device = nullptr;
4483        if (eligible && xstage_pinned_ && cudaHostGetDevicePointer(&device, p, 0) == cudaSuccess && device) {
4484            try {
4485                std::vector<uint64_t> sizes(complement_offsets_.size(), 0);
4486                for (size_t i = 0; i < sizes.size(); ++i) {
4487                    const size_t layer = n_expert_ > 0 ? i / (size_t) n_expert_ : 0;
4488                    sizes[i] = layer < layer_blob_bytes_.size() ? layer_blob_bytes_[layer] : 0;
4489                }
4490                if (exchange_storage_.initialize_sized(complement_offsets_, sizes, (uint8_t*)complement_host_, complement_device_,
4491                        complement_bytes_, xstage_, (const uint8_t*)device, (uint64_t)total, (size_t)n, (size_t)bounce, reason)) {
4492                    std::fprintf(stderr, "FileExpertSource: exchange buffer rotation enabled: %lld buffers in %zu block sizes "
4493                                         "(largest %llu bytes, %.2f GiB page-locked); no host commit memcpy\n",
4494                                 (long long)n, exchange_storage_.block_sizes(), (unsigned long long)blob,
4495                                 (double)total / 1073741824.0);
4496                }
4497            } catch (const std::bad_alloc&) { reason = "buffer metadata allocation failed"; }
4498        } else if (eligible) {
4499            (void) cudaGetLastError();
4500            reason = "exchange buffers could not be pinned and mapped";
4501        }
4502        if (!exchange_storage_.active())
4503            std::fprintf(stderr, "FileExpertSource: exchange rotation unavailable; retaining copy path: %s\n", reason.c_str());
4504    }
4505    return true;
4506}
4507
4508uint8_t* FileExpertSource::exchange_buffer(int64_t q, int64_t layer) const {
4509    if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr;
4510    if (exchange_storage_.active())
4511        return layer >= 0 && layer < n_layers_ ? exchange_storage_.spare((size_t)q, (size_t)layer_blob_bytes_[(size_t)layer]).host
4512                                             : exchange_storage_.spare((size_t)q).host;
4513    return xstage_ + (size_t) q * (size_t) xstage_blob_;
4514}
4515
4516bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q) {
4517    if (out < 0 || out >= n_expert_ || !has_resident(layer, in) || has_resident(layer, out) ||
4518        exchange_buffer(q, layer) == nullptr) return false;
4519    const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in;
4520    const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out;
4521    if (override_.empty()) override_.assign((size_t) blobs_, nullptr);
4522    if (override_[i_out] != nullptr) return false;
4523    for (const Exchange& x : staged_)
4524        if (x.in == i_in || x.q == q) return false;
4525    override_[i_out] = exchange_buffer(q, layer);
4526    staged_.push_back({i_in, i_out, q, layer_blob_bytes_[(size_t) layer]});
4527    return true;
4528}
4529
4530bool FileExpertSource::soft_commit_exchanges() {
4531    if (staged_.empty()) return true;
4532    if (exchange_storage_.active() || !xstage_pinned_ || xstage_ == nullptr || !complement_pinned_ || complement_device_ == nullptr)
4533        return false;
4534    if (xstage_dev_ == nullptr) {
4535        void* d = nullptr;
4536        if (cudaHostGetDevicePointer(&d, xstage_, 0) != cudaSuccess || d == nullptr) { (void) cudaGetLastError(); return false; }
4537        xstage_dev_ = (const uint8_t*) d;
4538    }
4539    if (soft_in_.empty()) soft_in_.assign((size_t) blobs_, SIZE_MAX);
4540    for (const Exchange& x : staged_) soft_in_[x.out] = x.in;
4541    return true;
4542}
4543
4544void FileExpertSource::fs_hold_staged(bool hold) {
4545    ForesightSwap* fs = fs_swap_.load(std::memory_order_acquire);
4546    if (fs == nullptr || n_expert_ <= 0) return;
4547    for (const Exchange& x : staged_)
4548        for (const size_t i : {x.in, x.out}) {
4549            const int64_t layer = (int64_t) (i / (size_t) n_expert_);
4550            const int32_t expert = (int32_t) (i % (size_t) n_expert_);
4551            if (hold) fs->hold(layer, expert);
4552            else fs->unhold(layer, expert);
4553        }
4554}
4555
4556int64_t FileExpertSource::commit_exchanges() {
4557    int64_t n = 0;
4558    fs_hold_staged(true);   // #2134: both experts' bytes move (in's place takes out's bytes, out leaves its buffer)
4559    for (const Exchange& x : staged_)
4560        if (!soft_in_.empty()) soft_in_[x.out] = SIZE_MAX;
4561    for (const Exchange& x : staged_) {
4562        const uint8_t* src = override_[x.out];
4563        if (exchange_storage_.active()) {
4564            if (!exchange_storage_.commit(x.in, x.out, (size_t)x.q, src, (size_t)x.bytes)) {
4565                // Admitting the GPU swap after a failed RAM ownership update would lose an expert.
4566                std::fprintf(stderr, "FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n");
4567                std::abort();
4568            }
4569            ++n;
4570            override_[x.out] = nullptr;
4571            continue;
4572        }
4573        const uint64_t at = complement_offsets_[x.in];
4574        if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&
4575            complement_host_ != nullptr) {
4576            std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes);
4577            if (detail::exchange_cache_complement(complement_offsets_, x.in, x.out)) ++n;
4578        }
4579        override_[x.out] = nullptr;
4580    }
4581    fs_hold_staged(false);
4582    staged_.clear();
4583    exchanges_ += n;
4584    return n;
4585}
4586
4587bool FileExpertSource::replace_resident(int64_t layer, int64_t in, int64_t out) {
4588    if (!complement_ready_ || complement_host_ == nullptr || exchange_storage_.active() || !staged_.empty() ||
4589        layer < 0 || layer >= n_layers_ || in < 0 || out < 0 || in >= n_expert_ || out >= n_expert_ || in == out)
4590        return false;
4591    const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in;
4592    const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out;
4593    if (i_in >= complement_offsets_.size() || i_out >= complement_offsets_.size()) return false;
4594    if (!override_.empty() && (override_[i_in] != nullptr || override_[i_out] != nullptr)) return false;
4595    const uint64_t at = complement_offsets_[i_out], bytes = layer_blob_bytes_[(size_t) layer];
4596    if (at == kNoComplement || complement_offsets_[i_in] != kNoComplement || at > complement_bytes_ ||
4597        bytes > complement_bytes_ - at) return false;
4598    (void) at;
4599    // read beside the copy first: a failed read leaves `out` where it was
4600    if (ram_adapt_buf_.size() < (size_t) bytes) ram_adapt_buf_.resize((size_t) bytes);
4601    const auto t0 = std::chrono::steady_clock::now();
4602    if (!copy_from_files(layer, in, ram_adapt_buf_.data())) return false;
4603    file_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
4604                       std::memory_order_relaxed);
4605    file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed);
4606    return install_resident(layer, in, out, ram_adapt_buf_.data());
4607}
4608
4609bool FileExpertSource::replace_resident_staged(int64_t layer, int64_t in, int64_t out) {
4610    if (!complement_ready_ || complement_host_ == nullptr || exchange_storage_.active() || !staged_.empty() ||
4611        layer < 0 || layer >= n_layers_ || in < 0 || out < 0 || in >= n_expert_ || out >= n_expert_ || in == out)
4612        return false;
4613    const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in;
4614    const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out;
4615    if (i_in >= complement_offsets_.size() || i_out >= complement_offsets_.size()) return false;
4616    if (!override_.empty() && (override_[i_in] != nullptr || override_[i_out] != nullptr)) return false;
4617    const uint64_t at = complement_offsets_[i_out], bytes = layer_blob_bytes_[(size_t) layer];
4618    if (at == kNoComplement || complement_offsets_[i_in] != kNoComplement || at > complement_bytes_ ||
4619        bytes > complement_bytes_ - at || bytes > stage_blob_) return false;
4620    ForesightSwap* fs = fs_swap_.load(std::memory_order_acquire);
4621    bool moved = false;
4622    {
4623        // held across the copy: claim_stage cannot hand the buffer to another blob meanwhile
4624        std::lock_guard<std::mutex> lk(stage_mu_);
4625        const auto it = stage_of_.find((int64_t) i_in);
4626        if (it == stage_of_.end() || stage_busy_[it->second] || stage_key_[it->second] != (int64_t) i_in) return false;
4627        if (fs != nullptr) fs->hold(layer, (int32_t) out);
4628        std::memcpy((uint8_t*) complement_host_ + (size_t) at, stage_buf_[it->second].get(), (size_t) bytes);
4629        moved = detail::exchange_cache_complement(complement_offsets_, i_out, i_in);
4630        if (fs != nullptr) fs->unhold(layer, (int32_t) out);
4631    }
4632    if (moved) { ++ram_adapts_; ++ram_staged_; }
4633    return moved;
4634}
4635
4636// `in`'s bytes (src) into `out`'s place of the compact copy, and the two offsets swapped - the checks again, as the caller
4637// may have read `src` a while ago (149-prefetch: ram_install)
4638bool FileExpertSource::install_resident(int64_t layer, int64_t in, int64_t out, const uint8_t* src) {
4639    if (!complement_ready_ || complement_host_ == nullptr || exchange_storage_.active() || !staged_.empty() ||
4640        layer < 0 || layer >= n_layers_ || in < 0 || out < 0 || in >= n_expert_ || out >= n_expert_ || in == out || src == nullptr)
4641        return false;
4642    const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in;
4643    const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out;
4644    if (i_in >= complement_offsets_.size() || i_out >= complement_offsets_.size()) return false;
4645    if (!override_.empty() && (override_[i_in] != nullptr || override_[i_out] != nullptr)) return false;
4646    const uint64_t at = complement_offsets_[i_out], bytes = layer_blob_bytes_[(size_t) layer];
4647    if (at == kNoComplement || complement_offsets_[i_in] != kNoComplement || at > complement_bytes_ ||
4648        bytes > complement_bytes_ - at) return false;
4649    // #2134: a Foresight slot may be copying out of `out`'s place right now; it is dropped (never served) before the place is rewritten
4650    ForesightSwap* fs = fs_swap_.load(std::memory_order_acquire);
4651    if (fs != nullptr) fs->hold(layer, (int32_t) out);
4652    std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) bytes);
4653    const bool moved = detail::exchange_cache_complement(complement_offsets_, i_out, i_in);
4654    if (fs != nullptr) fs->unhold(layer, (int32_t) out);
4655    if (!moved) return false;
4656    ++ram_adapts_;
4657    return true;
4658}
4659
4660// ---- 149-prefetch: staged promotions.  The read of `in` runs on this source's own thread (one at a time: the drive's
4661// queue stays the decode's first); the install is the decode thread's (ram_install, at a window boundary).
4662bool FileExpertSource::ram_stage(int64_t layer, int64_t in, int64_t out) {
4663    if (!complement_ready_ || complement_host_ == nullptr || layer < 0 || layer >= n_layers_ || in < 0 || out < 0 ||
4664        in >= n_expert_ || out >= n_expert_ || in == out)
4665        return false;
4666    {
4667        std::lock_guard<std::mutex> lk(ram_mu_);
4668        static const size_t cap = [] {
4669            const char* v = std::getenv("STRATA_RAM_ADAPT_QUEUE");
4670            return v != nullptr ? (size_t) std::max(1, std::atoi(v)) : (size_t) 64;
4671        }();
4672        if (ram_jobs_.size() >= cap) return false;
4673        for (const auto& j : ram_jobs_)
4674            if (j->layer == layer && (j->in == in || j->out == out || j->in == out || j->out == in)) return false;
4675        auto j = std::make_unique<RamJob>();
4676        j->layer = layer; j->in = in; j->out = out; j->state = 0;
4677        ram_jobs_.push_back(std::move(j));
4678        if (!ram_thread_.joinable()) {
4679            ram_quit_ = false;
4680            ram_thread_ = std::thread([this] { ram_worker(); });
4681        }
4682    }
4683    ram_cv_.notify_one();
4684    return true;
4685}
4686
4687bool FileExpertSource::ram_queued(int64_t layer, int64_t expert) const {
4688    std::lock_guard<std::mutex> lk(ram_mu_);
4689    for (const auto& j : ram_jobs_)
4690        if (j->layer == layer && (j->in == expert || j->out == expert)) return true;
4691    return false;
4692}
4693
4694void FileExpertSource::ram_worker() {
4695    strata::platform::name_this_thread("strata-ram");
4696    for (;;) {
4697        RamJob* job = nullptr;
4698        {
4699            std::unique_lock<std::mutex> lk(ram_mu_);
4700            ram_cv_.wait(lk, [&] {
4701                if (ram_quit_) return true;
4702                for (const auto& j : ram_jobs_)
4703                    if (j->state == 0) return true;
4704                return false;
4705            });
4706            if (ram_quit_) return;
4707            for (const auto& j : ram_jobs_)
4708                if (j->state == 0) { job = j.get(); break; }
4709            job->state = 1;
4710        }
4711        const uint64_t bytes = layer_blob_bytes_[(size_t) job->layer];
4712        job->buf.resize((size_t) bytes);
4713        const auto t0 = std::chrono::steady_clock::now();
4714        const bool ok = copy_from_files(job->layer, job->in, job->buf.data());
4715        file_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
4716                           std::memory_order_relaxed);
4717        if (ok) {
4718            file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed);
4719            ram_staged_reads_.fetch_add(1, std::memory_order_relaxed);
4720        }
4721        std::lock_guard<std::mutex> lk(ram_mu_);
4722        job->state = ok ? 2 : 3;
4723    }
4724}
4725
4726int64_t FileExpertSource::ram_install(const int32_t* host_res, int64_t n_expert) {
4727    std::vector<std::unique_ptr<RamJob>> done;
4728    {
4729        std::lock_guard<std::mutex> lk(ram_mu_);
4730        for (auto it = ram_jobs_.begin(); it != ram_jobs_.end();) {
4731            if ((*it)->state >= 2) { done.push_back(std::move(*it)); it = ram_jobs_.erase(it); }
4732            else ++it;
4733        }
4734    }
4735    int64_t n = 0;
4736    for (const auto& j : done) {
4737        if (j->state != 2) { ram_install_skips_.fetch_add(1, std::memory_order_relaxed); continue; }
4738        if (host_res != nullptr && (host_res[(size_t) (j->layer * n_expert + j->in)] >= 0 ||
4739                                    host_res[(size_t) (j->layer * n_expert + j->out)] >= 0)) {
4740            ram_install_gpu_.fetch_add(1, std::memory_order_relaxed);   // the GPU tier took one of them meanwhile
4741            continue;
4742        }
4743        if (install_resident(j->layer, j->in, j->out, j->buf.data())) ++n;
4744        else ram_install_skips_.fetch_add(1, std::memory_order_relaxed);
4745    }
4746    return n;
4747}
4748
4749void FileExpertSource::ram_stop() {
4750    {
4751        std::lock_guard<std::mutex> lk(ram_mu_);
4752        ram_quit_ = true;
4753    }
4754    ram_cv_.notify_all();
4755    if (ram_thread_.joinable()) ram_thread_.join();
4756    std::lock_guard<std::mutex> lk(ram_mu_);
4757    ram_jobs_.clear();
4758    ram_quit_ = false;
4759}
4760
4761int FileExpertSource::tier_of(int64_t layer, int64_t expert) const {
4762    if (layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return 2;
4763    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
4764    if (complement_ready_ && resident_blob(index) != nullptr) return 0;
4765#if defined(__linux__)
4766    uint64_t total = 0;
4767    const uint64_t c = cached_bytes(layer, expert, total, false);
4768    return total > 0 && c >= total ? 1 : 2;
4769#else
4770    return 2;
4771#endif
4772}
4773
4774void FileExpertSource::commit_copies() {
4775    fs_hold_staged(true);   // #2134: held until commit_flip has pointed `out` at its new place
4776    if (exchange_storage_.active()) return;   // STRATA_EXCHANGE_ROTATE: ownership moves in commit_flip, nothing to copy
4777    for (const Exchange& x : staged_) {
4778        const uint8_t* src = override_.empty() ? nullptr : override_[x.out];
4779        const uint64_t at = complement_offsets_[x.in];
4780        if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&
4781            complement_host_ != nullptr)
4782            std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes);
4783    }
4784}
4785
4786int64_t FileExpertSource::commit_flip() {
4787    int64_t n = 0;
4788    fs_hold_staged(true);   // (already held by commit_copies; idempotent)
4789    for (const Exchange& x : staged_) {
4790        const uint8_t* src = override_[x.out];
4791        if (exchange_storage_.active()) {   // STRATA_EXCHANGE_ROTATE: the same ownership transfer as commit_exchanges
4792            if (!exchange_storage_.commit(x.in, x.out, (size_t) x.q, src, (size_t) x.bytes)) {
4793                std::fprintf(stderr, "FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n");
4794                std::abort();
4795            }
4796            ++n;
4797            override_[x.out] = nullptr;
4798            continue;
4799        }
4800        const uint64_t at = complement_offsets_[x.in];
4801        // the same test as commit_copies: an exchange whose bytes were copied is the one that flips
4802        if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&
4803            complement_host_ != nullptr && detail::exchange_cache_complement(complement_offsets_, x.in, x.out))
4804            ++n;
4805        override_[x.out] = nullptr;
4806    }
4807    fs_hold_staged(false);
4808    staged_.clear();
4809    exchanges_ += n;
4810    return n;
4811}
4812
4813const uint8_t* FileExpertSource::resident_blob(int64_t layer, int64_t expert) const {
4814    if (!complement_ready_ || complement_host_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ ||
4815        expert >= n_expert_) return nullptr;
4816    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
4817    if (index >= complement_offsets_.size()) return nullptr;
4818    return resident_blob(index);   // through the rotation's ownership table when STRATA_EXCHANGE_ROTATE is on
4819}
4820
4821const uint8_t* FileExpertSource::blob_stable(int64_t layer, int64_t expert) {
4822    if (io_pf_ && role_ptr_.empty() && direct_.empty()) {
4823        if (complement_ready_ && layer >= 0 && expert >= 0 && layer < n_layers_ && expert < n_expert_) {
4824            const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
4825            if (resident_blob(index) != nullptr || (!override_.empty() && override_[index] != nullptr)) return blob(layer, expert);
4826        }
4827        const uint8_t* b = mapped_blob(layer, expert);
4828        if (b != nullptr) file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
4829        return b;
4830    }
4831    return blob(layer, expert);
4832}
4833
4834int FileExpertSource::blob_parts(int64_t layer, int64_t expert, BlobPart* out) {
4835    // the GGUF mapped in place only (three tensors per expert); the RAM copy, an exchange override, the unbuffered
4836    // reads, a closed mapping and the I/O prefetch (STRATA_IO_PREFETCH: it preads the ranges the page cache lacks, which a copy out
4837    // of the mapping would fault in one page at a time) keep going through blob(), which knows them
4838    if (role_ptr_.empty() || !direct_.empty() || io_pf_ || unmapped_ || base_ == nullptr || layer < 0 || expert < 0 ||
4839        layer >= n_layers_ || expert >= n_expert_)
4840        return 0;
4841    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
4842    if (complement_ready_ && (resident_blob(index) != nullptr || (!override_.empty() && override_[index] != nullptr))) return 0;
4843    Span sp[3];
4844    const int ns = spans(layer, expert, sp);
4845    for (int i = 0; i < ns; ++i) out[i] = {sp[i].p, sp[i].n, sp[i].at};
4846    if (ns > 0) {
4847        file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
4848        ++reads_;
4849    }
4850    return ns;
4851}
4852
4853const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {
4854    if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr;
4855    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
4856    const uint8_t* result = nullptr;
4857    bool from_files = true;
4858    if (complement_ready_) {
4859        result = resident_blob(index);
4860        if (result != nullptr) {
4861            ram_reads_.fetch_add(1, std::memory_order_relaxed);
4862            from_files = false;
4863        } else if (!override_.empty() && override_[index] != nullptr) {
4864            result = override_[index];
4865            from_files = false;
4866        }
4867    }
4868    if (from_files) {
4869        if (io_pf_ && role_ptr_.empty() && direct_.empty()) {
4870            result = io_blob(layer, expert);              // staged when it had to be read, the mapping when cached
4871        } else if (staged()) {
4872            result = staged_blob(layer, expert);          // counts its bytes
4873        } else {
4874            result = mapped_blob(layer, expert);
4875            if (result != nullptr) {
4876                file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
4877#if defined(__linux__)
4878                if (io_stats_) {   // STRATA_IO_STATS=1: what the page cache held when the kernels were handed the blob
4879                    uint64_t total = 0;
4880                    const uint64_t c = cached_bytes(layer, expert, total);
4881                    io_cached_.fetch_add(c, std::memory_order_relaxed);
4882                    io_uncached_.fetch_add(total - c, std::memory_order_relaxed);
4883                }
4884#endif
4885            }
4886        }
4887        if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed);
4888    }
4889    if (result != nullptr) reads_.fetch_add(1, std::memory_order_relaxed);
4890    return result;
4891}
4892
4893bool FileExpertSource::pinned(int64_t layer, int64_t expert) const {
4894    if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 ||
4895        layer >= n_layers_ || expert >= n_expert_) return false;
4896    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
4897    if (exchange_storage_.active()) return exchange_storage_.resident(index).host != nullptr;
4898    // soft_commit_exchanges: a staged `out` is judged by the place it will take (`in`'s), as after the commit
4899    const size_t at_index = !soft_in_.empty() && soft_in_[index] != SIZE_MAX ? soft_in_[index] : index;
4900    if (at_index >= complement_offsets_.size() || complement_offsets_[at_index] == kNoComplement) return false;
4901    // a partial pin (CS-T): only the registered prefix
4902    return !complement_partial_ ||
4903           complement_offsets_[at_index] + layer_blob_bytes_[(size_t) layer] <= complement_pin_limit_;
4904}
4905
4906const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const {
4907    if (!pinned(layer, expert) || complement_device_ == nullptr) return nullptr;
4908    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
4909    if (exchange_storage_.active()) return exchange_storage_.resident(index).device;
4910    if (!soft_in_.empty() && soft_in_[index] != SIZE_MAX)   // soft_commit_exchanges: out is read from its exchange buffer
4911        return override_.empty() || override_[index] == nullptr || xstage_dev_ == nullptr
4912                   ? nullptr : xstage_dev_ + (size_t) (override_[index] - xstage_);
4913    return complement_device_ + (size_t) complement_offsets_[index];
4914}
4915
4916bool FileExpertSource::pcie_layer(int64_t layer) const {
4917    if (complement_ready_ && complement_pinned_ && complement_device_ != nullptr)
4918        return layer >= 0 && layer < n_layers_;
4919    return device_alias(layer, 0) != nullptr;
4920}
4921
4922// ================================ THE ADAPTER ================================
4923
4924bool ExpertDispatch::fetch_can(int64_t layer) const {
4925    return fetch_admit > 0 && res_mut != nullptr && !usage.empty() && plan != nullptr && plan->pcie_mode == 2 &&
4926           plan->dst2 != nullptr && peer == nullptr && remote_count == 0 && fs == nullptr && pcie_num > 0 &&
4927           src != nullptr && src->pcie_layer(layer);
4928}
4929
4930void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd,
4931                          int64_t k, float* out) {
4932    (void) weights;   // clause 2: `moe_combine` applies it on the device.  Not an oversight.
4933    ExpertDispatch& d = *(ExpertDispatch*) user;
4934    if (d.failed) return;   // a previous layer already failed; do not make it worse
4935
4936    using namespace strata::kernels::cpu;
4937    // Clause 3: the blob's internal offsets are compile-time constants, so a mismatched geometry does not
4938    // produce a wrong answer - it produces a walk off the end of the blob into the next expert's bytes, which
4939    // is finite and plausible.  Refuse, name the number, and let the driver report it.
4940    if (n_embd != H) {
4941        d.failed = true;
4942        d.fail = "the expert kernel is compiled for a 2560-wide activation";
4943        d.fail_layer = d.layers;
4944        return;
4945    }
4946    if (expert_layout().native) {
4947        // plan v0.3 P6: a native pack runs its experts in verify windows only (the driver guarantees it)
4948        d.failed = true;
4949        d.fail = "the single-token expert path does not take a native (IQ) pack";
4950        d.fail_layer = d.layers;
4951        return;
4952    }
4953    if (k > (int64_t) d.jobs.size()) d.jobs.resize((size_t) k);
4954
4955    d.src->begin_layer(d.layers, ids, k);
4956
4957    // Clause 1: rebuilt from `x_f` on EVERY call.  `x_f` is mapped pinned memory whose address never changes,
4958    // so anything cached against it would be layer 0's activation reused 48 times.
4959    act_quant_q8_1(x_f, H, d.act);
4960
4961    // ---- R4.2c: THE POOL'S HALF OF THE SPLIT.  **IT DOES NOT DECIDE ANYTHING - `Launch` ALREADY DID.**
4962    //
4963    // The decision has to be made on THIS layer's ids, and `Launch` is the only callback that runs before the
4964    // pool while the ids are known (the doorbell publishes them when the ring fires).  So `expert_hit_run`
4965    // decides, and this consumes `d.is_hit`.  The first version decided here instead, which meant `Launch`
4966    // computed the PREVIOUS layer's experts into this layer's rows: C1 went from mean KL 9.69e-02 to 1.03e+00.
4967    //
4968    // `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a hit.
4969    const bool graph_hits = d.host_res != nullptr;
4970    const bool use_hits = graph_hits || (d.hits_ready() && d.decided);
4971    int64_t njobs = 0;
4972
4973    if (d.remote_count > 0) {
4974        int32_t kind[32];
4975        if (k > 32) {
4976            d.failed = true; d.fail = "remote experts: routing width exceeds 32"; return;
4977        }
4978        for (int64_t i = 0; i < k; ++i)
4979            kind[i] = use_hits && ids[i] >= 0 && ids[i] < d.n_expert && (graph_hits
4980                ? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] >= 0
4981                : d.is_hit[(size_t) i] != 0) ? 0 : -1;
4982        static thread_local std::string remote_error;
4983        for (int r = 0; r < d.remote_count; ++r)
4984            if (!d.remote[r]->begin(d.layers, x_f, ids, 1, k, kind, d.host_res, remote_error)) {
4985                d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
4986            }
4987    }
4988
4989    for (int64_t i = 0; i < k; ++i) {
4990        const int64_t e = ids[i];
4991        if (e < 0 || e >= d.n_expert) {
4992            d.failed = true;
4993            d.fail = "a routed expert id is out of range";
4994            d.fail_layer = d.layers;
4995            d.fail_expert = e;
4996            return;
4997        }
4998        const uint8_t* b = d.src->blob(d.layers, e);
4999        if (b == nullptr) {
5000            // The one failure the loop cannot see.  Leaving `out` at its previous contents would feed the NEXT
5001            // layer a stale expert vector, which `moe_combine` would weight and add - the token would still be
5002            // finite and would still be wrong, 48 layers deep.
5003            d.failed = true;
5004            d.fail = "the expert source could not produce a blob";
5005            d.fail_layer = d.layers;
5006            d.fail_expert = e;
5007            ++d.missing;
5008            return;
5009        }
5010        // A hit's row was zeroed by `Launch` and belongs to the GPU; the pool must not touch it.
5011        if (use_hits && (graph_hits ? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0
5012                                    : d.is_hit[(size_t) i] != 0)) {
5013            if (graph_hits) ++d.cache_hits;
5014            // The GPU owns this row and `hit_out` is zeroed, so the CPU's contribution is zero - but
5015            // `y_miss` is a REUSED pinned buffer, so the row must be written, not merely skipped.
5016            std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float));
5017            continue;
5018        }
5019        if (graph_hits) ++d.cache_refused;   // token graph: a miss (nothing is admitted during a token)
5020
5021        bool remote_owns = false;
5022        for (int r = 0; r < d.remote_count; ++r) remote_owns |= d.remote[r]->owns(i);
5023        if (remote_owns) {
5024            std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float));
5025            continue;
5026        }
5027
5028        // `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a
5029        // hit, and using one for the other is how a hit's row would get two experts summed into it.
5030        ExpertJob& j = d.jobs[(size_t) njobs++];
5031        j.blob = b;
5032        j.act = &d.act;             // SHARED across the batch: one conversion serves all ten experts
5033        j.out = out + (size_t) i * (size_t) n_embd;
5034        j.weight = 1.0f;            // clause 2: a diagnostic field, NOT the router weight
5035        j.slot = (int) i;
5036    }
5037
5038    // Plan v0.3 P4: rows of every expert across all threads (bitwise the same as `run`).
5039    if (d.split_rows) d.pool->run_split(d.jobs.data(), (int) njobs);
5040    else d.pool->run(d.jobs.data(), (int) njobs);
5041    if (d.remote_count > 0) {
5042        static thread_local std::string remote_error;
5043        for (int r = 0; r < d.remote_count; ++r)
5044            if (!d.remote[r]->finish(out, remote_error)) {
5045                d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
5046            }
5047    }
5048    ++d.layers;
5049    d.experts += k;
5050}
5051
5052namespace {
5053// the verify window's per-entry tables in `expert_pool_dispatch_multi` (`kind`, `distinct`, `first_of`)
5054// are fixed arrays of this many entries: a window's rows (kWindowMaxT) of the model's 10 routed experts must fit, and a
5055// larger k is refused at run time rather than written past them.  128 for the 8-row window (as it was), 256 for 16.
5056constexpr int64_t kMaxWindowEntries = strata::kernels::kWindowMaxT <= 8 ? 128 : 256;
5057static_assert(strata::kernels::kWindowMaxT * 10 <= kMaxWindowEntries, "a verify window's entries overflow the tables");
5058}  // namespace
5059
5060namespace {
5061// STRATA_ROUTE_TAIL_SKIP: the rank from which a missed expert that every token of the window routes that low is skipped.  An
5062// explicit environment value is read once; the serve start-up (generate.cpp) sets the CUDA default where it applies.
5063std::atomic<int> g_tail_skip_rank{-1};   // -1: not resolved yet
5064}  // namespace
5065int tail_skip_rank() {
5066    int r = g_tail_skip_rank.load(std::memory_order_relaxed);
5067    if (r < 0) {
5068        const char* v = std::getenv("STRATA_ROUTE_TAIL_SKIP");
5069        r = v != nullptr ? std::atoi(v) : 0;
5070        r = r > 0 && r < 10 ? r : 0;
5071        g_tail_skip_rank.store(r, std::memory_order_relaxed);
5072    }
5073    return r;
5074}
5075void set_tail_skip_rank(int r) { g_tail_skip_rank.store(r > 0 && r < 10 ? r : 0, std::memory_order_relaxed); }
5076
5077static void lat_quant_q8_1(const float* x, int n, uint8_t* o) {   // = quantize_q8_1_kernel, per 32: d, sum, qs
5078    const int nb = n / 32;
5079    for (int b = 0; b < nb; ++b) {
5080        const float* xb = x + b * 32;
5081        uint8_t* ob = o + b * 36;
5082        float amax = 0.0f, sum = 0.0f;
5083        for (int j = 0; j < 32; ++j) {
5084            const float v = xb[j];
5085            amax = fmaxf(amax, fabsf(v));
5086            sum += v;
5087        }
5088        const float d32 = amax / 127.0f;
5089        const float d = fabsf(d32) > 65504.0f ? copysignf(65504.0f, d32) : d32;
5090        const uint16_t dh = strata::kernels::f16_from_f32(d);
5091        const uint16_t sh = strata::kernels::f16_from_f32(sum);
5092        ob[0] = (uint8_t)(dh & 0xFFu); ob[1] = (uint8_t)(dh >> 8);
5093        ob[2] = (uint8_t)(sh & 0xFFu); ob[3] = (uint8_t)(sh >> 8);
5094        int8_t* q = (int8_t*)(ob + 4);
5095        // amax/sum stay scalar above (their order feeds the f16 d/sum - a SIMD reduction would
5096        // reorder it).  The qs loop is per element, no reduction: the AVX2 copy in kq_avx2.cpp.
5097        // THE 32-float SNAPSHOT is the race fix (probe-proven 2026-11-04): lh has a writer that
5098        // races this read - consuming it at a different moment changed the window's output (the
5099        // day's whole "parity red" chain).  The copy pins what the quant consumes, a few ns/block.
5100        // STRATA_LH_WHO=1 double-reads to catch the writer in the act.
5101        static const bool qs_simd_off = std::getenv("STRATA_NO_QS_SIMD") != nullptr;
5102        static const bool lh_who = std::getenv("STRATA_LH_WHO") != nullptr;
5103        float snap[32];
5104        std::memcpy(snap, xb, 32 * sizeof(float));
5105        if (lh_who) {   // read it again right away: a racing writer shows up as a delta
5106            static std::atomic<int> lh_diffs{0};
5107            for (int j = 0; j < 32; ++j)
5108                if (snap[j] != xb[j]) {
5109                    if (lh_diffs.fetch_add(1) < 8)
5110                        std::fprintf(stderr, "LHWHO b=%d j=%d: before %g after %g\n", b, j, snap[j], xb[j]);
5111                    break;
5112                }
5113        }
5114        if (amax != 0.0f && !qs_simd_off && strata::kernels::cpu::kq256_supported(8))
5115            strata::kernels::cpu::lat_quant_q8_1_qs_avx2(snap, &d, q);
5116        else {
5117            for (int j = 0; j < 32; ++j) {
5118                float v;
5119                if (amax == 0.0f) v = 0.0f;
5120                else v = roundf(xb[j] / d);
5121                v = v > 127.0f ? 127.0f : (v < -127.0f ? -127.0f : v);
5122                q[j] = (int8_t) v;
5123            }
5124        }
5125    }
5126}
5127
5128// ---- latent MoE: the CPU pool's expert arithmetic (edge0).  The GPU computes the whole window's D stage
5129// and its result (the q8_1 image of xl, row t*G + g) is in mapped host memory - the pool never recomputes D.
5130// Per CPU-served entry (kind == -1): the A blob computes h = A[e] . xl[t,g] (I then ELL, the pool's native
5131// row phases over the GPU's own quantized xl rows), then contribution = U[g] . q8_1(h) as a mode-7 row dot
5132// spread over the workers, written into the entry's mapped row (out + i*H).
5133static FileExpertSource* latent_io_source(ExpertSource* src) {
5134    static const bool enabled = [] {
5135        const char* v = std::getenv("STRATA_LATENT_IO_OVERLAP");
5136        return v != nullptr && std::atoi(v) != 0;
5137    }();
5138    if (!enabled) return nullptr;
5139    auto* file = dynamic_cast<FileExpertSource*>(src);
5140    return file != nullptr && file->unbuffered() ? file : nullptr;
5141}
5142
5143static void latent_cpu_run(ExpertDispatch& d, const float* x_f, const int32_t* ids,
5144                           int64_t n_tok, int64_t k, const int32_t* kind, float* out) {
5145    using namespace strata::kernels::cpu;
5146    const int64_t l = d.layers;
5147    const NativeFmt& f = expert_layout().fmt[(size_t) l];
5148    const int64_t ELL = d.lat_ELL, H = d.lat_H;
5149    const int G = d.lat_G, E = d.lat_E;
5150    const strata::core::LatentDense& dd = *d.lat_dense;
5151    const uint8_t* U = dd.u(l);
5152    const int32_t* labels = d.lat_labels + (size_t) l * (size_t) E;
5153    const size_t u_row = dd.u_row_bytes();
5154    const size_t xlq_row = (size_t) (ELL / 32) * 36;
5155    const double t_enter_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5156        std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // PROBE-OTHER: entry
5157
5158    // the CPU entries: j -> (entry index i, token, expert, group); the groups used
5159    static thread_local std::vector<int64_t> ent_i;
5160    static thread_local std::vector<int> ent_t, ent_e, ent_g;
5161    ent_i.clear(); ent_t.clear(); ent_e.clear(); ent_g.clear();
5162    bool used[64] = {};
5163    for (int64_t i = 0; i < n_tok * k; ++i) {
5164        if (kind[i] != -1) continue;
5165        const int32_t e = ids[i];
5166        if (e < 0 || e >= E) { d.failed = true; d.fail = "a routed expert id is out of range"; d.fail_layer = l; d.fail_expert = e; return; }
5167        const int g = labels[(size_t) e];
5168        if (g < 0 || g >= G) { d.failed = true; d.fail = "latent: a bad group label"; d.fail_layer = l; d.fail_expert = e; return; }
5169        ent_i.push_back(i); ent_t.push_back((int) (i / k)); ent_e.push_back(e); ent_g.push_back(g);
5170        if (g < 64) used[g] = true;
5171    }
5172    if (ent_t.empty()) return;
5173    static const bool s_pool_trace = std::getenv("STRATA_POOL_TRACE") != nullptr;
5174    if (s_pool_trace) std::fprintf(stderr, "POOL-ENTRY l=%d\n", (int) l);
5175    const float* xl = (const float*) d.lat_xlq;   // the D stage's f32 rows (mapped), row t*G + g
5176    if (xl == nullptr) { d.failed = true; d.fail = "latent CPU share: no D result for this window"; d.fail_layer = l; return; }
5177    double t_xlseq_ms = 0.0;
5178    if (d.lat_xlseq != nullptr) {   // the D stage's doorbell: the rows of layer l are in when it reaches l+1
5179        const uint32_t want = (uint32_t) (l + 1);
5180        if (s_pool_trace) std::fprintf(stderr, "POOL-DOORBELL l=%d want=%u got=%u\n", (int) l, want, *(volatile const uint32_t*) d.lat_xlseq);
5181        const auto t0 = std::chrono::steady_clock::now();
5182        while (*(volatile const uint32_t*) d.lat_xlseq < want) {
5183            if (std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count() > 20000.0) {
5184                d.failed = true; d.fail = "latent CPU share: the D rows never arrived for this layer";
5185                d.fail_layer = l;
5186                return;
5187            }
5188            std::this_thread::yield();
5189        }
5190        std::atomic_thread_fence(std::memory_order_seq_cst);
5191        t_xlseq_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
5192        if (s_pool_trace) std::fprintf(stderr, "POOL-QUANT l=%d\n", (int) l);
5193    }
5194
5195    // ---- A: the blob experts on the pool's native row phases.  The activation is quantized ON THE HOST from
5196    // the D stage's f32 rows (native_quant_act -> the blobs' vec_dot_type, Q8_0 for NVFP4); the layer's
5197    // Hadamard fold stays off - the D output is already in the blob's own basis (v1's verified fix).
5198    const double t_ew_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5199        std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // PROBE-OTHER: ew end
5200    static thread_local std::vector<float> lh;
5201    static thread_local std::vector<uint8_t> act;   // one Q8_0 activation row per CPU entry
5202    static thread_local std::vector<ExpertJobMulti> jobs;
5203    static thread_local std::vector<int64_t> job_experts;
5204    static thread_local std::vector<char> taken;
5205    FileExpertSource* const io = latent_io_source(d.src);
5206    struct FetchDrain {
5207        FileExpertSource* src;
5208        ~FetchDrain() { if (src != nullptr) (void) src->latent_fetch_wait(); }
5209    } fetch_drain{io};
5210    lh.assign((size_t) ent_t.size() * (size_t) ELL, 0.f);
5211    jobs.clear();
5212    job_experts.clear();
5213    taken.assign(ent_t.size(), 0);
5214    NativeFmt f_nr = f; f_nr.had_gu = false;   // no rotation: the D output is the blob's own basis
5215    const size_t act_row = f.act_bytes;        // per-entry activation bytes (the gu vec_dot_type, Q8_0)
5216    // DESIGN-4: the act rows arrive GPU-made (mapped, bit-exact - probe_std's zero diff; the D
5217    // stage quantizes them before the doorbell, so xlseq covers them).  The jobs point straight
5218    // at the mapped rows - zero host compute, zero copy.  STRATA_ACT_FALLBACK=1 keeps the old
5219    // host quantization (the A/B arm); STRATA_ACT_CHECK memcmps GPU rows vs the host reference
5220    // (zero-row guard included - the mod5 lesson).
5221    static const bool act_fallback = std::getenv("STRATA_ACT_FALLBACK") != nullptr;
5222    static const bool act_check = std::getenv("STRATA_ACT_CHECK") != nullptr;
5223    const uint8_t* act0 = (const uint8_t*) d.lat_act0;
5224    // DESIGN-4's GPU rows are ALWAYS Q8_0 (verify.cpp quantize_q8_0_rows), but this layer's
5225    // blobs may dot against another activation format (Q3_K -> ggml-cpu's Q8_K, 292 B per
5226    // 256 values): a non-Q8_0 layer must not consume them - the bytes would be misread and
5227    // the row stride would bleed into the next row.  Only a layer whose own act_row is the
5228    // Q8_0 one takes the GPU-made rows; the rest fall back to the host quantizer.
5229    const size_t act_q8_0_row = (size_t) (ELL / 32) * 34;
5230    const bool act_gpu = act0 != nullptr && !act_fallback && act_row == act_q8_0_row;
5231    act.assign((size_t) ent_t.size() * act_row, 0);
5232    if (act_gpu) {
5233        for (size_t j = 0; j < ent_t.size(); ++j) {
5234            const uint8_t* src = act0 + ((size_t) ent_t[j] * (size_t) G + (size_t) ent_g[j]) * act_row;
5235            if (act_check) {   // the GPU-vs-host probe, first diff only, zero-head guard
5236                static std::atomic<int> act_diffs{0};
5237                static thread_local std::vector<uint8_t> act_ref;
5238                act_ref.assign(act_row, 0);
5239                native_quant_act(f_nr, xl + ((size_t) ent_t[j] * (size_t) G + (size_t) ent_g[j]) * (size_t) ELL,
5240                                 act_ref.data());
5241                const uint8_t* a = act_ref.data();
5242                if (a[0] == 0 && a[1] == 0 && a[2] == 0 && a[3] == 0)
5243                    if (act_diffs.fetch_add(1) < 8)
5244                        std::fprintf(stderr, "ACTCHECK j=%zu: GPU ZERO HEAD\n", j);
5245                if (std::memcmp(a, src, act_row) != 0)
5246                    for (size_t k = 0; k < act_row; ++k)
5247                        if (a[k] != src[k]) {
5248                            if (act_diffs.fetch_add(1) < 8)
5249                                std::fprintf(stderr, "ACTCHECK j=%zu byte %zu: host %02x vs gpu %02x\n", j, k, a[k], src[k]);
5250                            break;
5251                        }
5252            }
5253            std::memcpy(act.data() + j * act_row, src, act_row);
5254        }
5255    } else {
5256        auto* const tr = ggml_get_type_traits_cpu((ggml_type) f_nr.gu_act);
5257        auto const ff = tr->from_float;
5258        for (size_t j = 0; j < ent_t.size(); ++j) {
5259            const float* src = xl + ((size_t) ent_t[j] * (size_t) G + (size_t) ent_g[j]) * (size_t) ELL;
5260            ff(src, act.data() + j * act_row, (int64_t) ELL);
5261        }
5262    }
5263    const double t_quant_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5264        std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGA: relative marker
5265    int64_t t_blob_ns = 0;
5266    for (size_t i0 = 0; i0 < ent_t.size(); ++i0) {
5267        if (taken[i0]) continue;
5268        const int e = ent_e[i0];
5269        ExpertJobMulti jb{};
5270        const auto tb0 = std::chrono::steady_clock::now();
5271        if (io == nullptr) jb.blob = d.src->blob(l, e);
5272        t_blob_ns += std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - tb0).count();
5273        if (io == nullptr && jb.blob == nullptr) { d.failed = true; d.fail = "the expert source could not produce a blob"; d.fail_layer = l; d.fail_expert = e; ++d.missing; return; }
5274        for (size_t i = i0; i < ent_t.size() && jb.nt < MAXT; ++i) {
5275            if (taken[i] || ent_e[i] != e) continue;
5276            taken[i] = 1;
5277            jb.nact[jb.nt] = act.data() + i * act_row;
5278            jb.out[jb.nt] = lh.data() + i * (size_t) ELL;
5279            ++jb.nt;
5280        }
5281        jobs.push_back(jb);
5282        if (io != nullptr) job_experts.push_back(e);
5283    }
5284    if (std::getenv("STRATA_DIAG_A") != nullptr) {
5285        static std::atomic<int64_t> dwin{0}, djobs{0}, dent{0};
5286        int64_t ent_sum = 0;
5287        for (const auto& jb : jobs) ent_sum += jb.nt;
5288        dwin.fetch_add(1, std::memory_order_relaxed);
5289        djobs.fetch_add((int64_t) jobs.size(), std::memory_order_relaxed);
5290        dent.fetch_add(ent_sum, std::memory_order_relaxed);
5291        if (dwin.load(std::memory_order_relaxed) % 48 == 0)
5292            std::fprintf(stderr, "DIAGA win=%lld jobs=%.1f entries=%.1f\n",
5293                         (long long) dwin.load(), (double) djobs.load() / dwin.load(),
5294                         (double) dent.load() / dwin.load());
5295    }
5296    const double t_a0_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5297        std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // PROBE-OTHER: jb end
5298    if (io == nullptr || jobs.empty()) {
5299        d.pool->run_split_multi_native(f, jobs.data(), (int) jobs.size(), NativeArithmetic::Default);
5300    } else {
5301        static const size_t batch = [] {
5302            const char* v = std::getenv("STRATA_LATENT_IO_BATCH");
5303            return (size_t) std::clamp(v != nullptr ? std::atoi(v) : 8, 1, 16);
5304        }();
5305        auto submit = [&](size_t at) {
5306            return io->latent_fetch_begin(l, job_experts.data() + at,
5307                                         (int64_t) std::min(batch, jobs.size() - at));
5308        };
5309        bool submitted = submit(0);
5310        for (size_t at = 0; at < jobs.size(); at += batch) {
5311            if (!submitted || !io->latent_fetch_wait()) {
5312                d.failed = true; d.fail = "latent: the direct fetch batch failed"; d.fail_layer = l; return;
5313            }
5314            const size_t count = std::min(batch, jobs.size() - at);
5315            for (size_t j = at; j < at + count; ++j) {
5316                jobs[j].blob = d.src->blob(l, job_experts[j]);
5317                if (jobs[j].blob == nullptr) {
5318                    d.failed = true; d.fail = "the expert source could not produce a blob";
5319                    d.fail_layer = l; d.fail_expert = job_experts[j]; ++d.missing; return;
5320                }
5321            }
5322            const size_t next = at + count;
5323            // blob() just refreshed current claims; <=16 next claims cannot reach claim_stage's 256-use eviction age.
5324            if (next < jobs.size()) submitted = submit(next);
5325            d.pool->run_split_multi_native(f, jobs.data() + at, (int) count, NativeArithmetic::Default);
5326        }
5327    }
5328    const double t_a1_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5329        std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGA: A wall
5330    if (s_pool_trace) std::fprintf(stderr, "POOL-A-END l=%d\n", (int) l);
5331
5332    // ---- U: contribution[j] = U[g] . q8_1(h_j): one matvec per used group over its entries (mode 7)
5333    static thread_local std::vector<uint8_t> hq;
5334    static thread_local std::vector<const void*> flat_act;
5335    static thread_local std::vector<float*> flat_out;
5336    static thread_local std::vector<ExpertPool::LatentMatvec> mvs;
5337    hq.resize(xlq_row * ent_t.size());
5338    for (size_t j = 0; j < ent_t.size(); ++j) lat_quant_q8_1(lh.data() + j * (size_t) ELL, (int) ELL, hq.data() + j * xlq_row);
5339    if (s_pool_trace) std::fprintf(stderr, "POOL-HQ-END l=%d\n", (int) l);
5340    // knife-0 (STRATA_LATENT_U_GPU=1): skip the CPU U matvec (mode 7); the GPU computes U from this hq.
5341    static const bool u_gpu = [] { const char* v = std::getenv("STRATA_LATENT_U_GPU"); return v != nullptr && std::atoi(v) != 0; }();
5342    if (const char* hqd = std::getenv("STRATA_HQ_DUMP")) {   // knife-0 debug: the hq rows this group computed
5343        static std::atomic<int> hqn{0};
5344        if (hqn.fetch_add(1, std::memory_order_relaxed) < 2) {
5345            FILE* f = std::fopen(hqd, "ab");
5346            if (f != nullptr) {
5347                std::fwrite(hq.data(), 1, hq.size(), f);
5348                std::fclose(f);
5349            }
5350        }
5351    }
5352    if (u_gpu) {
5353        uint8_t* lhq = (uint8_t*) out;   // m_ymiss_ reinterpreted: Q8_1, routed order (xlq_row per entry)
5354        std::memset(lhq, 0, (size_t) n_tok * (size_t) k * xlq_row);   // skipped (kind=-2) rows -> zero hq -> zero U
5355        for (size_t j = 0; j < ent_t.size(); ++j) {
5356            const int r = ent_i[j];
5357            std::memcpy(lhq + (size_t) r * xlq_row, hq.data() + j * xlq_row, xlq_row);
5358        }
5359        static const bool diag_hq = std::getenv("STRATA_DIAG_HQ") != nullptr;   // the first windows' hq rows as copied
5360        static std::atomic<int> diaghq_n{0};
5361        if (diag_hq && diaghq_n.fetch_add(1, std::memory_order_relaxed) < 5 && !ent_t.empty()) {
5362            const uint8_t* src = hq.data();
5363            const uint8_t* dst = lhq + (size_t) ent_i[0] * xlq_row;
5364            const int cmp = std::memcmp(src, dst, xlq_row);
5365            const uint16_t d = *(const uint16_t*) dst, s = *(const uint16_t*) (dst + 2);
5366            const bool nan_d = (d & 0x7C00) == 0x7C00 && (d & 0x3FF) != 0;
5367            const bool nan_s = (s & 0x7C00) == 0x7C00 && (s & 0x3FF) != 0;
5368            std::fprintf(stderr, "DIAGHQ nent=%zu out=%p tb_off_bytes=%lld ent_i0=%d cmp=%d d=0x%04x(nan=%d) s=0x%04x(nan=%d) q0..3=%d,%d,%d,%d\n",
5369                         ent_t.size(), (const void*) out, (long long) (ent_i[0] * xlq_row), ent_i[0], cmp,
5370                         d, (int) nan_d, s, (int) nan_s,
5371                         (int) (int8_t) dst[4], (int) (int8_t) dst[5], (int) (int8_t) dst[6], (int) (int8_t) dst[7]);
5372            std::fflush(stderr);
5373        }
5374        d.multi_entries += (int64_t) ent_t.size();
5375        return;
5376    }
5377    mvs.clear();
5378    flat_act.reserve(ent_t.size());
5379    flat_out.reserve(ent_t.size());
5380    int mv_base[64];
5381    for (int g = 0; g < G; ++g) {
5382        mv_base[g] = (int) flat_act.size();
5383        if (g >= 64 || !used[g]) continue;
5384        for (size_t j = 0; j < ent_t.size(); ++j) {
5385            if (ent_g[j] != g) continue;
5386            flat_act.push_back(hq.data() + j * xlq_row);
5387            flat_out.push_back(out + (size_t) ent_i[j] * (size_t) H);
5388        }
5389    }
5390    for (int g = 0; g < G; ++g) {
5391        if (g >= 64 || !used[g]) continue;
5392        const int i0 = mv_base[g];
5393        const int i1 = g + 1 < G ? mv_base[g + 1] : (int) flat_act.size();
5394        if (i1 <= i0) continue;
5395        ExpertPool::LatentMatvec mv{};
5396        mv.w = U + (size_t) g * (size_t) H * u_row;
5397        mv.row_bytes = u_row;
5398        mv.nrows = (int) H;
5399        mv.ncols = (int) ELL;
5400        mv.nt = i1 - i0;
5401        mv.act = flat_act.data() + i0;
5402        mv.out = flat_out.data() + i0;
5403        mvs.push_back(mv);
5404    }
5405    const double t_u1_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5406        std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGA: U wall
5407    static std::atomic<double> s_ur{0};
5408    const auto ur0 = std::chrono::steady_clock::now();
5409    d.pool->run_latent_rows(mvs.data(), (int) mvs.size());
5410    s_ur.fetch_add((double) std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::steady_clock::now() - ur0).count() / 1e6, std::memory_order_relaxed);
5411    d.multi_entries += (int64_t) ent_t.size();
5412    if (std::getenv("STRATA_DIAG_A") != nullptr) {
5413        static std::atomic<double> s_xlseq{0}, s_a{0}, s_u{0}, s_blob{0};
5414        static std::atomic<int64_t> s_calls{0};
5415        static std::atomic<double> s_ew{0}, s_jb{0}, s_am{0};   // PROBE-OTHER: the glue walls
5416        s_ew.fetch_add(t_ew_ms - t_enter_ms, std::memory_order_relaxed);
5417        s_jb.fetch_add(t_a0_ms - t_quant_ms, std::memory_order_relaxed);
5418        s_am.fetch_add(t_quant_ms - t_ew_ms, std::memory_order_relaxed);
5419        s_xlseq.fetch_add(t_xlseq_ms, std::memory_order_relaxed);
5420        s_a.fetch_add(t_a1_ms - t_a0_ms, std::memory_order_relaxed);
5421        s_u.fetch_add(t_u1_ms - t_a1_ms, std::memory_order_relaxed);
5422        s_blob.fetch_add((double) t_blob_ns / 1e6, std::memory_order_relaxed);
5423        if (s_calls.fetch_add(1, std::memory_order_relaxed) % 48 == 0)
5424            std::fprintf(stderr, "DIAGP ms/call: xlseq %.3f blob %.3f A %.3f U %.3f UR %.3f EW %.3f JB %.3f AM %.3f (n %lld)\n",
5425                         s_xlseq.load() / (s_calls.load() + 1), s_blob.load() / (s_calls.load() + 1),
5426                         s_a.load() / (s_calls.load() + 1), s_u.load() / (s_calls.load() + 1),
5427                         s_ur.load() / (s_calls.load() + 1),
5428                         s_ew.load() / (s_calls.load() + 1), s_jb.load() / (s_calls.load() + 1),
5429                         s_am.load() / (s_calls.load() + 1),
5430                         (long long) (s_calls.load() + 1));
5431    }
5432}
5433
5434// One routed entry's report counters: -2 skipped, 0 VRAM, 1 PCIe, 2 another GPU, -1 CPU.
5435static void count_route_entry(ExpertDispatch& d, int32_t kind) {
5436    if (kind == -2) { ++d.tail_skipped; return; }
5437    if (kind < 0) { ++d.cache_refused; return; }
5438    if (kind == 0) ++d.cache_hits;
5439    else ++d.offload_entries;   // #588: PCIe or another GPU
5440    if (kind == 2 && d.peer != nullptr) ++d.peer_entries;
5441}
5442
5443void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k,
5444                                float* out, strata::kernels::cpu::NativeArithmetic arithmetic) {
5445    using namespace strata::kernels::cpu;
5446    if (d.failed) return;
5447    d.lat_xlq = strata::core::latent_xl_current();      // this window's D rows (null: not latent)
5448    d.lat_xlseq = strata::core::latent_xlseq_current();
5449    d.lat_act0 = strata::core::latent_act0_current();   // DESIGN-4: the D rows as Q8_0, GPU-made
5450    if (n_tok < 1 || n_tok > strata::kernels::kWindowMaxT) {
5451        d.failed = true;
5452        d.fail = "a verify window has more tokens than the multi-token expert kernel takes";
5453        d.fail_layer = d.layers;
5454        return;
5455    }
5456    if (d.lookahead != nullptr) {
5457        if (d.lookahead->stats_on()) {
5458            if (d.layers == 0) d.lookahead->stats_window_start();
5459            d.lookahead->stats_score(d.layers, ids, n_tok * k, d.host_res, d.pcie_num);
5460        }
5461        d.lookahead->submit(d.layers, x_f, n_tok, d.host_res);   // CS-T: warm layer + 1
5462    }
5463    if (k < 1 || n_tok * k > kMaxWindowEntries) {
5464        d.failed = true;
5465        d.fail = "a verify window routes more entries than the expert pool's window tables hold";
5466        d.fail_layer = d.layers;
5467        return;
5468    }
5469    if ((int64_t) d.act_multi.size() < n_tok) d.act_multi.resize((size_t) strata::kernels::kWindowMaxT);
5470    const ExpertLayout& lay = expert_layout();
5471    const bool native = lay.native;
5472    if (native && d.nact_multi.size() < (size_t) strata::kernels::kWindowMaxT * kNativeActBytes)
5473        d.nact_multi.resize((size_t) strata::kernels::kWindowMaxT * kNativeActBytes);
5474    if (d.job_of.size() != (size_t) d.n_expert) d.job_of.assign((size_t) d.n_expert, (int16_t) -1);
5475    if (d.jobs_multi.size() < (size_t) (n_tok * k)) d.jobs_multi.resize((size_t) (strata::kernels::kWindowMaxT * k));
5476    static const bool ptrace = std::getenv("STRATA_POOL_TRACE") != nullptr;
5477    auto pt = [&](const char* what, long long a = -1) {
5478        if (ptrace) { std::fprintf(stderr, "pool trace: layer %lld %s %lld\n", (long long) d.layers, what, a); std::fflush(stderr); }
5479    };
5480    const auto c0 = std::chrono::steady_clock::now();
5481    const FileExpertSource::DecodeScope decode_scope;   // 149 STRATA_IO_PF_GATE: this thread reads for the decode
5482    // 149-cold STRATA_COLD_OVERLAP: 0 off, 1 overlap, 2 measure only, 3 overlap + zero-copy, 4 zero-copy only.
5483    // 0.2.0: unset, 4 for the GGUF read in place on Linux (zero-copy needs the page cache's residency query), else 0
5484    static const int cold_env = [] {
5485        const char* v = std::getenv("STRATA_COLD_OVERLAP");
5486        return v == nullptr || v[0] == '\0' ? -1 : std::clamp(std::atoi(v), 0, 4);
5487    }();
5488    d.cold_mode = cold_env >= 0 ? cold_env : (d.src != nullptr && d.src->linux_file_defaults() ? 4 : 0);
5489    pt("begin");
5490    const double t_b0_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5491        std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGB2: before begin_layer
5492    d.src->begin_layer(d.layers, ids, n_tok * k);
5493    pt("begun");
5494    if (!d.usage.empty())
5495        for (int64_t i = 0; i < n_tok * k; ++i)
5496            if (ids[i] >= 0 && ids[i] < d.n_expert) d.usage[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] += 1.0f;
5497    // ---- plan v0.3 P6: the GPU's share, decided and published FIRST so the GPU starts while the CPU works.
5498    // Distinct experts in routing order; resident ones and the last pcie_num/256 of the missed ones go to the GPU.
5499    const int64_t n = n_tok * k;
5500    const double t_c0_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5501        std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGB: dispatch entry
5502    double t_d1_ms = 0, t_d2_ms = 0, t_k1_ms = 0, t_k2_ms = 0;   // DIAGB2 stamps, assigned inside the plan block
5503    static std::atomic<int64_t> s_pinned_ns{0}, s_blob_ns{0}, s_pinned_calls{0};
5504    static std::atomic<int64_t> s_publish_ns{0}, s_fetch_ns{0}, s_pub_calls{0};
5505    int32_t kind[kMaxWindowEntries];       // per entry: -1 CPU, 0 VRAM, 1 PCIe
5506    if (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap) {
5507        int64_t distinct[kMaxWindowEntries], first_of[kMaxWindowEntries];
5508        int nd = 0, nmiss = 0;
5509        // a helper GPU (RemoteExperts) holding the expert computes it in its own VRAM once begin() claims the row: like
5510        // the peer tier's, such an expert is no miss of this plan and never part of the PCIe share, which would read it
5511        // over the primary's link instead (2x RX 6900 XT, IQ3_S, --remote-expert-opt with the probed share 0.39: ~4
5512        // helper experts per layer-window moved to PCIe, 59 ms per window against 34 ms)
5513        auto helper_holds = [&](int32_t e) {
5514            for (int r = 0; r < d.remote_count; ++r)
5515                if (d.remote[r]->holds(d.layers, e)) return true;
5516            return false;
5517        };
5518        for (int64_t i = 0; i < n; ++i) {
5519            first_of[i] = i;
5520            for (int64_t j = 0; j < i; ++j)
5521                if (ids[j] == ids[i]) { first_of[i] = first_of[j]; break; }
5522            if (first_of[i] == i) {
5523                distinct[nd++] = i;
5524                const int32_t e = ids[i];
5525                if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0 &&
5526                    !(d.peer != nullptr && d.peer->has(d.layers, e)) && !helper_holds(e)) ++nmiss;
5527            }
5528        }
5529        t_d1_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5530            std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGB2: distinct done
5531        // STRATA_ROUTE_TAIL_SKIP=R (default 7 on CUDA serve, =0 off; changes the output): a missed expert that EVERY token of the window routes
5532        // only at rank >= R (the smallest weights of the top-10) is neither copied nor computed; its contribution is
5533        // zero, without renormalisation (the others keep the weight the router gave them).  Less PCIe and CPU work.
5534        const int tail_rank = tail_skip_rank();
5535        bool skip_d[kMaxWindowEntries];
5536        for (int q = 0; q < nd; ++q) skip_d[q] = false;
5537        // STRATA_HELPER_RESIDENT=1: the skip also runs beside helper GPUs, for the misses no helper holds
5538        static const bool helper_skip = [] { const char* v = std::getenv("STRATA_HELPER_RESIDENT"); return v != nullptr && std::atoi(v) != 0; }();
5539        if (tail_rank > 0 && d.peer == nullptr && (d.remote_count == 0 || helper_skip)) {
5540            int minr[kMaxWindowEntries];
5541            for (int q = 0; q < nd; ++q) minr[q] = 99;
5542            for (int64_t i = 0; i < n; ++i) {
5543                int q = 0;
5544                while (q < nd && distinct[q] != first_of[i]) ++q;
5545                if (q < nd) minr[q] = std::min(minr[q], (int) (i % k));
5546            }
5547            for (int q = 0; q < nd; ++q) {
5548                const int32_t e = ids[distinct[q]];
5549                if (e < 0 || e >= d.n_expert || minr[q] < tail_rank) continue;
5550                if (d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) continue;   // resident
5551                if (helper_holds(e)) continue;                                                       // a helper computes it
5552                skip_d[q] = true;
5553                --nmiss;
5554                ++d.tail_experts;
5555            }
5556        }
5557        // STRATA_ROUTE_DUMP=<file> (bench only, off by default): one text line per layer-window, "layer n_tok nd nmiss | e:rows:res ..." in routing
5558        // order (res 1 = resident in the GPU cache, 0 = a miss the CPU computes unless the PCIe share takes it, 2 = tail-skipped), for replaying placement
5559        // policies offline on the routing the engine really produced (round 0216 P3.1).
5560        static std::FILE* const route_dump = [] { const char* f = std::getenv("STRATA_ROUTE_DUMP"); return f != nullptr && f[0] != '\0' ? std::fopen(f, "a") : nullptr; }();
5561        if (route_dump != nullptr) {
5562            std::fprintf(route_dump, "%lld %lld %d %d |", (long long) d.layers, (long long) n_tok, nd, nmiss);
5563            for (int q = 0; q < nd; ++q) {
5564                const int32_t e = ids[distinct[q]];
5565                int rows = 0;
5566                for (int64_t i = 0; i < n; ++i) rows += first_of[i] == distinct[q];
5567                const int res = skip_d[q] ? 2 : (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 1 : 0;
5568                std::fprintf(route_dump, " %d:%d:%d", (int) e, rows, res);
5569            }
5570            std::fputc(10, route_dump);
5571        }
5572        t_d2_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5573            std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGB2: tail_skip done
5574        // STRATA_PCIE_BALANCE (opt-in, #1548): the count comes from the measured CPU and GPU costs instead of the share
5575        const bool pcie_ok = (d.pcie_num > 0 || d.pcie_model.on) && d.src->pcie_layer(d.layers);
5576        int m = pcie_ok ? d.pcie_model.pick(nmiss, (nmiss * d.pcie_num) >> 8) : 0;
5577        // STRATA_PCIE_MIN1 (opt-in): the share rounds to 0 for 1-2 misses per layer, so the PCIe lane idles on the typical
5578        // decode step; with >= 2 misses give it at least one (the last in routing order).  It only flies if its blob is
5579        // pinned (the fetch below checks), else it stays a CPU miss exactly as before.  Read once.
5580        static const bool pcie_min1 = [] { const char* v = std::getenv("STRATA_PCIE_MIN1"); return v && std::atoi(v) != 0; }();
5581        if (pcie_min1 && pcie_ok && m < 1 && nmiss >= 2) m = 1;
5582        int miss_rank = 0, groups = 0, entries = 0, fetches = 0;
5583        GpuPlanSink& P = *d.plan;
5584        const uint8_t* dma_src[64];
5585        int64_t pcie_i0[64];
5586        // STRATA_ADAPT_FETCH: the share is the layer's most-routed misses, and the ones the tier would swap in are copied
5587        // into a slot as they are fetched (ExpertDispatch::fetch_admit)
5588        const bool fetch_on = m > 0 && d.fetch_can(d.layers);
5589        const float* use = d.usage.empty() ? nullptr : d.usage.data() + (size_t) d.layers * (size_t) d.n_expert;
5590        bool pick[kMaxWindowEntries];
5591        if (fetch_on) {
5592            int mq[kMaxWindowEntries], nm = 0;
5593            for (int q = 0; q < nd; ++q) {
5594                pick[q] = false;
5595                const int32_t e = ids[distinct[q]];   // a tail-skipped miss is not fetched
5596                // (an unpinned blob cannot be fetched: under STRATA_PIN_BY_NEED a PCIe layer is pinned in part)
5597                if (!skip_d[q] && e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0 &&
5598                    d.src->pinned(d.layers, e))
5599                    mq[nm++] = q;
5600            }
5601            std::stable_sort(mq, mq + nm, [&](int a, int b) { return use[ids[distinct[a]]] > use[ids[distinct[b]]]; });
5602            for (int j = 0; j < m && j < nm; ++j) pick[mq[j]] = true;
5603        }
5604        for (int q = 0; q < nd; ++q) {
5605            const int64_t i0 = distinct[q];
5606            const int32_t e = ids[i0];
5607            int kd = -1;
5608            unsigned long long ptr = 0;
5609            if (skip_d[q]) {                       // STRATA_ROUTE_TAIL_SKIP: neither copied nor computed
5610                for (int64_t i = i0; i < n; ++i)
5611                    if (first_of[i] == i0) kind[i] = -2;
5612                continue;
5613            }
5614            if (e >= 0 && e < d.n_expert) {
5615                const int32_t slot = d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e];
5616                if (slot >= 0) {
5617                    kd = 0;
5618                    ptr = (unsigned long long) (d.cache_base + (d.cache_slot_off ? (size_t) d.cache_slot_off[slot]
5619                                                                                 : (size_t) slot * (size_t) d.cache_blob));
5620                } else if (d.peer != nullptr && d.peer->has(d.layers, e)) {
5621                    kd = 2;                        // multi-GPU: the second GPU computes it
5622                } else if (helper_holds(e)) {
5623                    // left to the helper: kind -1 until RemoteExperts::begin() claims the row (see above)
5624                } else if (d.fs != nullptr && d.fs->take(d.layers, e, ptr)) {
5625                    kd = 0;                        // Foresight: a landed swap-space slot holds it - a GPU group like a hit
5626                } else {
5627                    if (d.fs != nullptr) d.fs->note_miss(d.src, d.layers, e);
5628                    if ((fetch_on ? pick[q] : miss_rank >= nmiss - m) && fetches < P.staging_cap && fetches < 64) {
5629                        const uint8_t* src;
5630                        {   // DIAGB2: time pinned() and blob() separately (PCIe-share miss only)
5631                            const auto tp0 = std::chrono::steady_clock::now();
5632                            const bool p = d.src->pinned(d.layers, e);
5633                            const auto tp1 = std::chrono::steady_clock::now();
5634                            src = p ? d.src->blob(d.layers, e) : nullptr;
5635                            const auto tp2 = std::chrono::steady_clock::now();
5636                            s_pinned_ns.fetch_add((int64_t) std::chrono::duration_cast<std::chrono::nanoseconds>(tp1 - tp0).count(), std::memory_order_relaxed);
5637                            s_blob_ns.fetch_add((int64_t) std::chrono::duration_cast<std::chrono::nanoseconds>(tp2 - tp1).count(), std::memory_order_relaxed);
5638                            s_pinned_calls.fetch_add(1, std::memory_order_relaxed);
5639                        }
5640                        if (src != nullptr) {
5641                            kd = 1;
5642                            dma_src[fetches] = src;
5643                            pcie_i0[fetches] = i0;
5644                            ++fetches;
5645                        }
5646                    }
5647                    ++miss_rank;
5648                }
5649            }
5650            for (int64_t i = i0; i < n; ++i)
5651                if (first_of[i] == i0) kind[i] = kd;
5652            if (kd != 0) continue;                 // the VRAM groups first; the PCIe groups below
5653            P.ptr[groups] = ptr;
5654            P.start[groups] = entries;
5655            for (int64_t i = i0; i < n; ++i)
5656                if (first_of[i] == i0) {
5657                    P.dst[entries] = (int32_t) i;
5658                    P.tok[entries] = (int32_t) (i / k);
5659                    ++entries;
5660                }
5661            ++groups;
5662        }
5663        t_k1_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5664            std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGB2: kind loop done
5665        P.start[groups] = entries;
5666        const uint64_t bb = lay.blob_bytes(d.layers);
5667        for (int q = 0; q < fetches; ++q) {       // the PCIe groups: staging slot q, entries after the VRAM ones
5668            const int64_t i0 = pcie_i0[q];
5669            P.ptr2[q] = P.pcie_mode != 0 ? (unsigned long long) d.src->device_alias(d.layers, ids[i0])
5670                                 : P.staging + (unsigned long long) q * (unsigned long long) bb;
5671            P.start2[q] = entries;
5672            for (int64_t i = i0; i < n; ++i)
5673                if (first_of[i] == i0) {
5674                    P.dst[entries] = (int32_t) i;
5675                    P.tok[entries] = (int32_t) (i / k);
5676                    ++entries;
5677                }
5678            ++d.pcie_experts;
5679        }
5680        if (d.fetch_admit > 0 && P.dst2 != nullptr)
5681            for (int q = 0; q < fetches; ++q) P.dst2[q] = 0;   // staging
5682        if (fetch_on && fetches > 0 && (size_t) d.layers < d.fetch_avail.size()) d.fetch_avail[(size_t) d.layers] = 1;
5683        if (fetch_on && fetches > 0) {
5684            // the fetched experts routed enough, most-routed first, each against the next least-routed resident expert
5685            // of the layer that the window does not route (its slot is read by nothing until the next window)
5686            const size_t lb = (size_t) d.layers * (size_t) d.n_expert;
5687            if (d.fetch_mark.size() != (size_t) d.n_expert) d.fetch_mark.assign((size_t) d.n_expert, 0);
5688            for (int64_t i = 0; i < n; ++i)
5689                if (ids[i] >= 0 && ids[i] < d.n_expert) d.fetch_mark[(size_t) ids[i]] = 1;
5690            int cq[64], nc = 0;
5691            for (int q = 0; q < fetches; ++q) {
5692                const int32_t e = ids[pcie_i0[q]];
5693                if (use[e] >= d.fetch_min && (d.in_flight.empty() || d.in_flight[lb + (size_t) e] == 0)) cq[nc++] = q;
5694            }
5695            std::stable_sort(cq, cq + nc, [&](int a, int b) { return use[ids[pcie_i0[a]]] > use[ids[pcie_i0[b]]]; });
5696            int32_t vic[64];
5697            int nv = 0;
5698            for (int32_t e = 0; e < (int32_t) d.n_expert && nc > 0; ++e) {
5699                if (d.res_mut[lb + (size_t) e] < 0 || d.fetch_mark[(size_t) e] != 0) continue;
5700                if (nv < nc) vic[nv++] = e;
5701                else if (use[e] < use[vic[nv - 1]]) vic[nv - 1] = e;
5702                else continue;
5703                for (int j = nv - 1; j > 0 && use[vic[j]] < use[vic[j - 1]]; --j) std::swap(vic[j], vic[j - 1]);
5704            }
5705            for (int j = 0; j < nc && j < nv; ++j) {
5706                const int q = cq[j];
5707                const int32_t e = ids[pcie_i0[q]], v = vic[j];
5708                if (use[e] < use[v] + d.fetch_margin) break;
5709                const int32_t slot = d.res_mut[lb + (size_t) v];
5710                P.dst2[q] = (unsigned long long) (d.cache_base + (d.cache_slot_off ? (size_t) d.cache_slot_off[slot]
5711                                                                                   : (size_t) slot * (size_t) d.cache_blob));
5712                d.res_mut[lb + (size_t) v] = -1;   // kNotResident
5713                d.res_mut[lb + (size_t) e] = slot;
5714                ++d.fetch_admitted;
5715                d.res_dirty = true;
5716                d.res_dirty_idx.push_back((int32_t) (lb + (size_t) v));
5717                d.res_dirty_idx.push_back((int32_t) (lb + (size_t) e));
5718                if (d.fetch_log_on) d.fetch_log.emplace_back((int64_t) (lb + (size_t) e), slot);
5719            }
5720            for (int64_t i = 0; i < n; ++i)
5721                if (ids[i] >= 0 && ids[i] < d.n_expert) d.fetch_mark[(size_t) ids[i]] = 0;
5722        }
5723        P.start2[fetches] = entries;
5724        P.counts[0] = groups;
5725        P.counts[1] = entries;
5726        P.counts[2] = fetches;
5727        std::atomic_thread_fence(std::memory_order_seq_cst);
5728        pt("publish", fetches);
5729        const auto pp0 = std::chrono::steady_clock::now();
5730        if (P.publish) P.publish(P.ctx);
5731        const auto pp1 = std::chrono::steady_clock::now();
5732        pt("fetch", fetches);
5733        if (P.fetch) P.fetch(P.ctx, dma_src, P.pcie_mode != 0 ? 0 : fetches, (size_t) bb);   // the copy engine, beside the CPU's work
5734        const auto pp2 = std::chrono::steady_clock::now();
5735        s_publish_ns.fetch_add((int64_t) std::chrono::duration_cast<std::chrono::nanoseconds>(pp1 - pp0).count(), std::memory_order_relaxed);
5736        s_fetch_ns.fetch_add((int64_t) std::chrono::duration_cast<std::chrono::nanoseconds>(pp2 - pp1).count(), std::memory_order_relaxed);
5737        s_pub_calls.fetch_add(1, std::memory_order_relaxed);
5738        t_k2_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5739            std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGB2: publish+fetch done
5740    } else {
5741        for (int64_t i = 0; i < n; ++i) {
5742            const int32_t e = ids[i];
5743            kind[i] = (e >= 0 && e < d.n_expert && d.host_res != nullptr &&
5744                       d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0
5745                    : (e >= 0 && e < d.n_expert && d.peer != nullptr && d.peer->has(d.layers, e)) ? 2 : -1;
5746        }
5747    }
5748    if (d.peer != nullptr) {                 // multi-GPU: start the second GPU's share before the CPU's own work
5749        std::string perr;
5750        if (!d.peer->launch(d.layers, x_f, ids, n_tok, k, kind, perr, out)) {
5751            std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers);
5752            d.failed = true;
5753            d.fail = "the peer GPU's experts could not be launched";
5754            d.fail_layer = d.layers;
5755            return;
5756        }
5757    }
5758    if (d.remote_count > 0) {
5759        static thread_local std::string remote_error;
5760        for (int r = 0; r < d.remote_count; ++r) {
5761            if (!d.remote[r]->begin(d.layers, x_f, ids, n_tok, k, kind, d.host_res, remote_error)) {
5762                d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
5763            }
5764            for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2;
5765        }
5766    }
5767    static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
5768    // the GPU's copy_rows_from_mapped zeroes the rows it computed itself (dec_batch); STRATA_VERIFY_DEVICE_PLAN's
5769    // copy_or_zero_from_mapped copies every row, so there the host still zeroes them
5770    static const bool device_plan = [] { const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); return v != nullptr && std::atoi(v) != 0; }();
5771    const bool gpu_zeroes_hits = (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap && dec_batch && !device_plan);
5772    bool any_cpu = false;
5773    for (int64_t i = 0; i < n; ++i)
5774        if (kind[i] == -1) { any_cpu = true; break; }   // -2: skipped (STRATA_ROUTE_TAIL_SKIP), no work
5775    if (d.dres_check != nullptr && any_cpu) {   // STRATA_ADAPT_CHECKRES
5776        bool published = false;
5777        for (int64_t i = 0; i < n && !published; ++i)
5778            published = ids[i] < 0 || ids[i] >= d.n_expert ||
5779                        d.dres_check[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] < 0;
5780        if (!published) ++d.stale_x;
5781    }
5782    const double t_kb_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5783        std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGB: K wall ends
5784    if (d.latent && any_cpu) {   // latent MoE: the CPU share runs the A-blob experts on the host (D -> A -> U)
5785        for (int64_t i = 0; i < n; ++i)   // counted before the CPU share, which may fail
5786            if (ids[i] >= 0 && ids[i] < d.n_expert) count_route_entry(d, kind[i]);
5787        static thread_local std::vector<int64_t> lmiss;
5788        static thread_local std::vector<uint8_t> lmiss_mark;   // one pass, no std::find scan
5789        lmiss.clear();
5790        if (lmiss_mark.size() < (size_t) d.n_expert) lmiss_mark.assign((size_t) d.n_expert, 0);
5791        for (int64_t i = 0; i < n; ++i)
5792            if (kind[i] == -1) {
5793                const int32_t e = ids[i];
5794                if (e < 0 || e >= d.n_expert || lmiss_mark[(size_t) e]) continue;
5795                lmiss_mark[(size_t) e] = 1;
5796                lmiss.push_back(e);
5797            }
5798        if (!lmiss.empty() && latent_io_source(d.src) == nullptr)
5799            d.src->prefetch(d.layers, lmiss.data(), (int64_t) lmiss.size());
5800        for (const int64_t e : lmiss) lmiss_mark[(size_t) e] = 0;   // the scratch resets for the next call
5801        for (int64_t i = 0; i < n; ++i)   // STRATA_ROUTE_TAIL_SKIP: a skipped entry's row is zero (the merge copies it)
5802            if (kind[i] == -2) std::memset(out + (size_t) i * (size_t) d.lat_H, 0, (size_t) d.lat_H * sizeof(float));
5803        const auto l0 = std::chrono::steady_clock::now();
5804        const double t_bb_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5805            std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;   // DIAGB: B wall ends
5806        latent_cpu_run(d, x_f, ids, n_tok, k, kind, out);
5807        const double t_run_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - l0).count();
5808        d.ms_run += t_run_ms;
5809        {   // DIAGB2: fine dispatch-bridge walls (ms/call cumulative mean). RUN = full latent_cpu_run wall.
5810            static std::atomic<double> s_beg{0}, s_dist{0}, s_tailw0{0}, s_kind{0}, s_pcie{0}, s_glue{0}, s_bwall{0}, s_run{0}, s_tailw{0};
5811            static std::atomic<int64_t> s_bn{0};
5812            const double t_tb_ms = (double) std::chrono::duration_cast<std::chrono::nanoseconds>(
5813                std::chrono::steady_clock::now().time_since_epoch()).count() / 1e6;
5814            s_beg.fetch_add(t_c0_ms - t_b0_ms, std::memory_order_relaxed);            // begin_layer + usage
5815            s_dist.fetch_add(t_d1_ms - t_c0_ms, std::memory_order_relaxed);           // distinct + nmiss
5816            s_tailw0.fetch_add(t_d2_ms - t_d1_ms, std::memory_order_relaxed);         // tail_skip
5817            s_kind.fetch_add(t_k1_ms - t_d2_ms, std::memory_order_relaxed);           // kind loop (incl pinned/blob)
5818            s_pcie.fetch_add(t_k2_ms - t_k1_ms, std::memory_order_relaxed);           // PCIe group fill + publish + fetch
5819            s_glue.fetch_add(t_kb_ms - t_k2_ms, std::memory_order_relaxed);           // peer/remote/any_cpu/dres_check glue
5820            s_bwall.fetch_add(t_bb_ms - t_kb_ms, std::memory_order_relaxed);          // lmiss + prefetch + memset(-2)
5821            s_run.fetch_add(t_run_ms, std::memory_order_relaxed);                     // latent_cpu_run full wall
5822            s_tailw.fetch_add(t_tb_ms - t_bb_ms - t_run_ms, std::memory_order_relaxed); // tail bookkeeping
5823            const int64_t bn = s_bn.fetch_add(1, std::memory_order_relaxed);
5824            if (std::getenv("STRATA_DIAG_A") != nullptr && bn % 48 == 0)
5825                std::fprintf(stderr,
5826                    "DIAGB2 ms/call: beg %.4f dist %.4f tail %.4f kind %.4f pcie %.4f glue %.4f B %.4f RUN %.4f tailw %.4f | pub %.4f fetch %.4f pinned %.4f blob %.4f | pub_c %.2f pin_c %.2f (n %lld)\n",
5827                    s_beg.load() / (double) (bn + 1), s_dist.load() / (double) (bn + 1),
5828                    s_tailw0.load() / (double) (bn + 1), s_kind.load() / (double) (bn + 1),
5829                    s_pcie.load() / (double) (bn + 1), s_glue.load() / (double) (bn + 1),
5830                    s_bwall.load() / (double) (bn + 1), s_run.load() / (double) (bn + 1),
5831                    s_tailw.load() / (double) (bn + 1),
5832                    (double) s_publish_ns.load() / 1e6 / (double) (bn + 1),
5833                    (double) s_fetch_ns.load() / 1e6 / (double) (bn + 1),
5834                    (double) s_pinned_ns.load() / 1e6 / (double) (bn + 1),
5835                    (double) s_blob_ns.load() / 1e6 / (double) (bn + 1),
5836                    (double) s_pub_calls.load() / (double) (bn + 1),
5837                    (double) s_pinned_calls.load() / (double) (bn + 1),
5838                    (long long) (bn + 1));
5839        }
5840        if (d.plan != nullptr) d.plan->cpu_jobs = (int) lmiss.size();
5841        d.multi_misses += (int64_t) lmiss.size();
5842        for (int64_t i = 0; i < n; ++i) {
5843            const int64_t e = ids[i];
5844            if (e >= 0 && e < d.n_expert) d.job_of[(size_t) e] = -1;
5845        }
5846        ++d.layers;
5847        d.experts += n_tok * k;
5848        return;
5849    }
5850    const auto c1 = std::chrono::steady_clock::now();
5851    if (any_cpu) {
5852        // #578 --remote-expert-opt: a token whose experts all run on a GPU (CUDA0 or a helper) needs no CPU activation
5853        const bool ep = d.remote_count > 0 && d.remote[0]->optimized_decode();
5854        for (int64_t t = 0; t < n_tok; ++t) {
5855            if (ep && std::all_of(kind + t * k, kind + (t + 1) * k, [](int32_t v) { return v >= 0; })) continue;
5856            if (native && strata::kernels::cpu::q2_native_kernels(lay.fmt[(size_t) d.layers].gu_type))   // a native Q2_0 pack: the Q2_0 kernels' activations
5857                act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
5858            else if (native)
5859                native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * H, d.nact_multi.data() + (size_t) t * kNativeActBytes);
5860            else
5861                act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
5862        }
5863    }
5864    const auto c2 = std::chrono::steady_clock::now();
5865    // 149-cold STRATA_COLD_OVERLAP (d.cold_mode): which of the CPU's experts still have a blob to read.  Mode 1 reads
5866    // them in the background and computes the ready ones first, then each read one as it lands; every expert keeps
5867    // its own token rows (the pool splits rows, never a row's sum), and the weighted sum over a token's experts is
5868    // the GPU's, after the dispatch - so the result is the same bits in any batch order.  The stage buffers stay
5869    // claimed (busy, then young) until the dispatch has joined its reads and run every batch.
5870    static thread_local std::vector<int64_t> miss;
5871    static thread_local std::vector<uint8_t> mstate;   // per miss: 0 ready, 1 being read, 2 landed, 3 computed
5872    miss.clear();
5873    int64_t npend = 0;
5874    double cold_r_ms = 0;
5875    if (any_cpu) {   // CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads)
5876        for (int64_t i = 0; i < n_tok * k; ++i)
5877            if (kind[i] == -1 && ids[i] >= 0 && ids[i] < d.n_expert &&
5878                std::find(miss.begin(), miss.end(), (int64_t) ids[i]) == miss.end())
5879                miss.push_back(ids[i]);
5880        if (d.cold_mode == 0) {
5881            d.src->prefetch(d.layers, miss.data(), (int64_t) miss.size());
5882        } else {
5883            mstate.assign(miss.size(), 0);
5884            const auto r0 = std::chrono::steady_clock::now();
5885            npend = d.src->prefetch_begin(d.layers, miss.data(), (int64_t) miss.size(), mstate.data());
5886            if (npend > 0 && d.cold_mode == 2) {   // measure: every read first, as mode 0 does
5887                d.src->prefetch_end();
5888                for (uint8_t& s : mstate) if (s == 1) s = 2;
5889                cold_r_ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - r0).count();
5890                d.ms_cold_wait += cold_r_ms;
5891            }
5892        }
5893    }
5894    // the CPU's experts this batch takes: all (mode 0, or no read), else by their state (want 0: the ready ones,
5895    // want 2: those that landed since the last batch)
5896    auto take = [&](int64_t e, uint8_t want) {
5897        if (npend == 0) return true;
5898        for (size_t q = 0; q < miss.size(); ++q)
5899            if (miss[q] == e) return mstate[q] == want;
5900        return want == 0;
5901    };
5902    int njobs = 0, njobs_all = 0;
5903    bool first_pass = true;
5904    uint8_t want = 0;
5905    double run_ms_extra = 0, cr_ms = 0;
5906    for (;;) {
5907    for (int64_t t = 0; t < n_tok; ++t)
5908        for (int64_t j = 0; j < k; ++j) {
5909            const int64_t i = t * k + j;
5910            const int64_t e = ids[i];
5911            float* row = out + (size_t) i * H;
5912            if (!first_pass && (e < 0 || e >= d.n_expert || kind[i] != -1 || !take(e, want)))
5913                continue;   // a later batch: only the CPU entries of the experts that just landed
5914            if (first_pass && kind[i] == -1 && e >= 0 && e < d.n_expert && !take(e, 0)) continue;   // being read: a later batch
5915            if (e < 0 || e >= d.n_expert) {
5916                d.failed = true;
5917                d.fail = "a routed expert id is out of range";
5918                d.fail_layer = d.layers;
5919                d.fail_expert = e;
5920                return;
5921            }
5922            count_route_entry(d, kind[i]);
5923            if (kind[i] == -2) {            // STRATA_ROUTE_TAIL_SKIP: a skipped tail expert contributes zero
5924                std::memset(row, 0, (size_t) H * sizeof(float));
5925                continue;
5926            }
5927            if (kind[i] >= 0) {             // CUDA0, PCIe, or a remote/peer result staged into this row below
5928                // multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it;
5929                // dec_batch: copy_rows_from_mapped_kernel already zeroes kind 0/1 rows on the GPU
5930                if (!((kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()) ||
5931                      (gpu_zeroes_hits && (kind[i] == 0 || kind[i] == 1))))
5932                    std::memset(row, 0, (size_t) H * sizeof(float));
5933                continue;
5934            }
5935            int16_t& jo = d.job_of[(size_t) e];
5936            if (jo < 0) {
5937                const uint8_t* zp[3] = {nullptr, nullptr, nullptr};
5938                const bool zc = d.cold_mode >= 3 && native && d.src->zc_roles(d.layers, e, zp);
5939                const uint8_t* b = zc ? zp[0] : d.src->blob(d.layers, e);
5940                if (b == nullptr) {
5941                    d.failed = true;
5942                    d.fail = "the expert source could not produce a blob";
5943                    d.fail_layer = d.layers;
5944                    d.fail_expert = e;
5945                    ++d.missing;
5946                    return;
5947                }
5948                jo = (int16_t) njobs++;
5949                ExpertJobMulti& nj = d.jobs_multi[(size_t) jo];
5950                nj.blob = b;
5951                nj.nt = 0;
5952                nj.fmt = nullptr;
5953                if (zc) {   // 149-cold mode 3: the gate rows are the blob; up and down at their distance in the mapping
5954                    if (d.zc_fmt.size() < d.jobs_multi.size()) d.zc_fmt.resize(d.jobs_multi.size());
5955                    strata::kernels::cpu::NativeFmt& f = d.zc_fmt[(size_t) jo];
5956                    f = lay.fmt[(size_t) d.layers];
5957                    f.up_off = (size_t) ((uintptr_t) zp[1] - (uintptr_t) zp[0]);     // modular: the tensors' order
5958                    f.down_off = (size_t) ((uintptr_t) zp[2] - (uintptr_t) zp[0]);   // in the file does not matter
5959                    nj.fmt = &f;
5960                    ++d.cold_zc;
5961                }
5962            }
5963            if (d.jobs_multi[(size_t) jo].nt == MAXT) {
5964                // a window of 9..16 rows routes more than MAXT tokens to this expert: the kernels and the pool's scratch
5965                // take MAXT tokens a job, so the rest are a further job over the same blob (each token's rows are its own,
5966                // so the split changes no value; the blob is read once more)
5967                const int16_t prev = jo;
5968                jo = (int16_t) njobs++;
5969                ExpertJobMulti& nj = d.jobs_multi[(size_t) jo];
5970                nj.blob = d.jobs_multi[(size_t) prev].blob;
5971                nj.fmt = d.jobs_multi[(size_t) prev].fmt;
5972                nj.nt = 0;
5973            }
5974            ExpertJobMulti& jb = d.jobs_multi[(size_t) jo];
5975            jb.act[jb.nt] = &d.act_multi[(size_t) t];
5976            jb.nact[jb.nt] = native ? d.nact_multi.data() + (size_t) t * kNativeActBytes : nullptr;
5977            jb.out[jb.nt] = row;
5978            ++jb.nt;
5979            ++d.multi_entries;
5980        }
5981    if (npend == 0) break;
5982    // 149-cold: run this batch now (the ready experts, then each landed group), then wait for the next landing
5983    {
5984        const auto b0 = std::chrono::steady_clock::now();
5985        if (njobs > 0) {
5986            if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs, arithmetic);
5987            else d.pool->run_split_multi(d.jobs_multi.data(), njobs);
5988            ++d.cold_batches;
5989        }
5990        const auto b1 = std::chrono::steady_clock::now();
5991        const double bm = std::chrono::duration<double, std::milli>(b1 - b0).count();
5992        run_ms_extra += bm;
5993        if (first_pass) { d.ms_cold_cr += bm; cr_ms = bm; }
5994        else d.ms_cold_cc += bm;
5995        if (first_pass) d.cold_ready += njobs;
5996        // the computed ones' job slots are free again (an expert is in one batch only)
5997        for (int jx = 0; jx < njobs; ++jx) d.jobs_multi[(size_t) jx].nt = 0;
5998        for (int64_t i = 0; i < n_tok * k; ++i)
5999            if (ids[i] >= 0 && ids[i] < d.n_expert) d.job_of[(size_t) ids[i]] = -1;
6000        if (!first_pass) for (uint8_t& s : mstate) if (s == 2) s = 3;
6001        njobs_all += njobs;
6002        njobs = 0;
6003        first_pass = false;
6004        want = 2;
6005        bool left = false;
6006        for (uint8_t s : mstate) left = left || s == 1 || s == 2;
6007        if (!left) break;
6008        if (std::none_of(mstate.begin(), mstate.end(), [](uint8_t s) { return s == 2; })) {
6009            const auto w0 = std::chrono::steady_clock::now();
6010            (void) d.src->wait_landed(d.layers, miss.data(), (int64_t) miss.size(), mstate.data());
6011            d.ms_cold_wait += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - w0).count();
6012        }
6013    }
6014    }
6015    if (npend > 0) {
6016        d.src->prefetch_end();
6017        const FileExpertSource* fs = dynamic_cast<const FileExpertSource*>(d.src);
6018        const double r_ms = d.cold_mode == 2 ? cold_r_ms : (fs != nullptr ? fs->async_fill_us() / 1e3 : 0.0);
6019        ++d.cold_layers;
6020        d.cold_pending += npend;
6021        d.ms_cold_r += r_ms;
6022        d.ms_cold_hide += std::min(r_ms, cr_ms);   // what an overlap can hide of this layer's reads at most
6023        njobs = njobs_all;
6024        d.ms_run += run_ms_extra;    // the batches ran inside the job loop: the pool's time stays the pool's
6025        d.ms_jobs -= run_ms_extra;
6026    }
6027    const auto c3 = std::chrono::steady_clock::now();
6028    if (d.plan != nullptr) d.plan->cpu_jobs = njobs;
6029    pt("run", njobs);
6030    if (njobs > 0 && npend == 0) {
6031        if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs, arithmetic);
6032        else d.pool->run_split_multi(d.jobs_multi.data(), njobs);
6033    }
6034    if (d.remote_count > 0) {
6035        static thread_local std::string remote_error;
6036        for (int r = 0; r < d.remote_count; ++r)
6037            if (!d.remote[r]->finish(out, remote_error)) {
6038                d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
6039            }
6040    }
6041    if (d.peer != nullptr) {                 // multi-GPU: the second GPU's rows, into the same mapped rows
6042        std::string perr;
6043        if (!d.peer->finish(out, perr)) {
6044            std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers);
6045            d.failed = true;
6046            d.fail = "the peer GPU's experts failed";
6047            d.fail_layer = d.layers;
6048            return;
6049        }
6050    }
6051    const auto c4 = std::chrono::steady_clock::now();
6052    pt("ran");
6053    auto ms = [](auto a, auto b) { return std::chrono::duration<double, std::milli>(b - a).count(); };
6054    d.ms_plan += ms(c0, c1);
6055    d.ms_actq += ms(c1, c2);
6056    d.ms_jobs += ms(c2, c3);
6057    d.ms_run += ms(c3, c4);
6058    for (int64_t i = 0; i < n_tok * k; ++i) {
6059        const int64_t e = ids[i];
6060        if (e >= 0 && e < d.n_expert) d.job_of[(size_t) e] = -1;
6061    }
6062    d.multi_misses += njobs;
6063    ++d.layers;
6064    d.experts += n_tok * k;
6065}
6066
6067void expert_hit_run(void* user, void* stream, HitPhase phase, const int32_t* ids, int64_t k) {
6068    ExpertDispatch& d = *(ExpertDispatch*) user;
6069    if (d.failed) return;
6070    cudaStream_t cs = (cudaStream_t) stream;
6071
6072    if (phase == HitPhase::Launch) {
6073        d.decided = false;
6074        d.hit_pending = false;
6075        if (!d.hits_ready() || ids == nullptr || k <= 0) return;
6076        if ((int64_t) d.is_hit.size() < k) d.is_hit.resize((size_t) k);
6077        // STRATA_EXPERT_NIBBLE=1: this split computes a resident expert with the GGUF-block kernels and admits + fills
6078        // a missed one with its GGUF blob - neither may meet a layer whose slots hold 4-bit codes (a native pack's
6079        // experts run in the verify windows, so this is the backstop, never the path)
6080#if STRATA_EXPERT_NIBBLE_BUILT   // compiled out of every other build: nothing is added to the hit split there
6081        if (strata::core::nibble::layer(d.layers).on)
6082            strata::core::nibble::fatal(d.layers, "the expert source's hit split (expert_hit_run)",
6083                                        "it computes resident experts as GGUF blocks and fills slots with GGUF blobs");
6084#endif
6085
6086        // ================================ THE DECISION, ONCE, ON THIS LAYER'S IDS ================================
6087        //
6088        // Every routed expert is asked of the cache.  Resident -> the GPU computes it.  Not resident -> it is
6089        // admitted and filled if there is room (which makes it a hit on THIS call, because the fill and the
6090        // kernel are on one stream in that order), and otherwise it stays a miss for the CPU.
6091        d.n_hits = 0;
6092        for (int64_t i = 0; i < k; ++i) {
6093            const int64_t e = ids[i];
6094            d.is_hit[(size_t) i] = 0;
6095            if (e < 0 || e >= d.n_expert) continue;   // out of range: the pool refuses it, with a message
6096            int32_t slot = d.cache->slot_of(d.layers, e);
6097            if (slot == kNotResident) {
6098                const int32_t cand = d.cache->admit(d.layers, e);
6099                if (cand == kNotResident) {
6100                    ++d.cache_refused;
6101                    continue;
6102                }
6103                // `blob` is asked ONLY for an expert about to be filled, so the source's read counter stays a
6104                // count of distinct experts moved rather than of looks.
6105                const uint8_t* b = d.src->blob(d.layers, e);
6106                std::string ferr;
6107                if (b == nullptr || !d.cache->fill_slot(cand, b, cs, ferr, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(d.layers))) {
6108                    d.failed = true;
6109                    d.fail = "the expert cache could not fill a slot";
6110                    d.fail_layer = d.layers;
6111                    d.fail_expert = e;
6112                    return;
6113                }
6114                d.src->note_async_read(b, cs);   // #1237: a page-locked stage buffer is not recycled under the queued copy
6115                ++d.cache_admitted;
6116                slot = cand;
6117            } else {
6118                ++d.cache_hits;
6119            }
6120            d.is_hit[(size_t) i] = 1;
6121            d.h_slot[(size_t) d.n_hits] = slot;
6122            d.h_dst[(size_t) d.n_hits] = (int32_t) i;
6123            ++d.n_hits;
6124        }
6125        d.decided = true;
6126        if (d.n_hits <= 0) return;   // nothing resident yet: no GPU work, and nothing for `Combine` to add
6127
6128        const size_t list_bytes = (size_t) d.n_hits * sizeof(int32_t);
6129        // `hit_out` is ZEROED rather than overwritten: the kernel writes only the rows this layer's hits own,
6130        // so a row that was a hit last layer and a miss this one would still hold last layer's expert and
6131        // `add_inplace` would sum it in.  Finite, plausible, wrong.
6132        if (cudaMemsetAsync(d.hit_out, 0, (size_t) d.parts_elems * sizeof(float), cs) != cudaSuccess ||
6133            cudaMemcpyAsync(d.d_slot, d.h_slot.data(), list_bytes, cudaMemcpyHostToDevice, cs) != cudaSuccess ||
6134            cudaMemcpyAsync(d.d_dst, d.h_dst.data(), list_bytes, cudaMemcpyHostToDevice, cs) != cudaSuccess) {
6135            d.hit_fail = "the hit list could not be staged";
6136            d.failed = true;
6137            d.fail = d.hit_fail;
6138            return;
6139        }
6140        // The activation is quantized HERE rather than reused from `s.moe.x_q8_0`, which `post[l-1]` wrote from
6141        // the PREVIOUS layer's `mixed`.  `pre[l]` has since overwritten `mixed`, so that buffer is a layer stale
6142        // - and a stale activation produces a perfectly finite expert for the wrong input.
6143        // **R4.2h: THE SCALED QUANTIZER, SO A HIT REPRODUCES A MISS.**  The CPU pool quantizes this same
6144        // activation with `act_quant_q8_1` and multiplies by the fp32 `ActQ::scale`; `quantize_q8_0` writes
6145        // an fp16 `d` instead, and `bench/micro/act_quant_parity.cu` measured **80 of 80 chunks differing by
6146        // up to 4.761e-04 relative**.  `quantize_q8_0_scaled` adopts the CPU's rule and scale, and the kernel
6147        // takes the fp32 array.  Falling back to the old path would silently reintroduce the divergence, so
6148        // the scales are required here rather than optional.
6149        if (d.x_q8_0_hit_scale == nullptr) {
6150            d.failed = true;
6151            d.fail = "the hit path has no fp32 activation scales (R4.2h)";
6152            return;
6153        }
6154        strata::kernels::quantize_q8_0_scaled(d.mixed, d.x_q8_0_hit, d.x_q8_0_hit_scale, strata::kernels::cpu::H,
6155                                              cs);
6156        if (d.hit_cpu_order)
6157            strata::kernels::moe_hit_grouped_s2_cpu_order(d.cache_base, d.d_slot, d.d_dst, d.n_hits,
6158                d.cache_blob, d.x_q8_0_hit, d.hit_scratch, d.hit_out, cs, d.x_q8_0_hit_scale);
6159        else
6160            strata::kernels::moe_hit_grouped_s2(d.cache_base, d.d_slot, d.d_dst, d.n_hits, d.cache_blob,
6161                d.x_q8_0_hit, d.hit_scratch, d.hit_out, cs, d.x_q8_0_hit_scale);
6162        d.hit_pending = true;
6163        if (d.hit_done != nullptr) cudaEventRecord((cudaEvent_t) d.hit_done, cs);
6164        // The A/B arm: ONE driver entry here, and nothing else changes.  If the work was waiting for the host
6165        // to enter the driver, this is what lets it start while the pool runs.
6166        if (d.hit_poke && d.hit_done != nullptr) (void) cudaEventQuery((cudaEvent_t) d.hit_done);
6167        return;
6168    }
6169
6170    // Combine: `parts += hit_out`, stream-ordered after the misses were copied into `parts`.
6171    if (!d.hit_pending) return;
6172    d.hit_pending = false;
6173    // Did the GPU get the hit work done while the CPU was in the pool?  This query is itself a driver entry,
6174    // so it is the LAST chance to observe a late start: a NOT-READY here means the work had not finished by the
6175    // time the pool returned, and with no poke in front of it that can only be because it began after.
6176    if (d.hit_done != nullptr) {
6177        if (cudaEventQuery((cudaEvent_t) d.hit_done) == cudaSuccess) ++d.hit_ready;
6178        else ++d.hit_late;
6179    }
6180    strata::kernels::add_inplace(d.parts_out, d.hit_out, d.parts_elems, cs);
6181}
6182
6183// ================================ THE RESIDENT ARENA (R2.1) ================================
6184
6185namespace {
6186
6187void hash_u64(uint64_t& h, uint64_t v) {
6188    h = fnv1a64((const uint8_t*) &v, sizeof v, h);
6189}
6190
6191void hash_text(uint64_t& h, const std::string& s) {
6192    h = fnv1a64((const uint8_t*) s.data(), (uint64_t) s.size(), h);
6193}
6194
6195bool hash_small_file(const std::filesystem::path& path, uint64_t& h, std::string& err) {
6196    hash_text(h, path.filename().string());
6197    std::ifstream f(path, std::ios::binary);
6198    if (!f) {
6199        hash_u64(h, 0);
6200        return true;
6201    }
6202    hash_u64(h, 1);
6203    std::vector<uint8_t> buf(64u << 10);
6204    for (;;) {
6205        f.read((char*) buf.data(), (std::streamsize) buf.size());
6206        const std::streamsize n = f.gcount();
6207        if (n > 0) h = fnv1a64(buf.data(), (uint64_t) n, h);
6208        if (f.eof()) break;
6209        if (!f) {
6210            err = "ArenaExpertSource: cannot hash pack metadata " + path.string();
6211            return false;
6212        }
6213    }
6214    return true;
6215}
6216
6217bool hash_sampled_file(const std::filesystem::path& path, uint64_t& h, std::string& err) {
6218    std::ifstream f(path, std::ios::binary | std::ios::ate);
6219    if (!f) {
6220        err = "ArenaExpertSource: cannot sample pack source " + path.string();
6221        return false;
6222    }
6223    const std::streamoff end = f.tellg();
6224    if (end < 0) {
6225        err = "ArenaExpertSource: cannot size pack source " + path.string();
6226        return false;
6227    }
6228    const uint64_t bytes = (uint64_t) end;
6229    hash_text(h, path.filename().string());
6230    hash_u64(h, bytes);
6231    constexpr uint64_t sample = 64u << 10;
6232    const uint64_t starts[3] = {0, bytes / 2, bytes > sample ? bytes - sample : 0};
6233    std::vector<uint8_t> buf((size_t) std::min<uint64_t>(sample, bytes));
6234    for (uint64_t off : starts) {
6235        if (buf.empty()) break;
6236        const uint64_t at = std::min<uint64_t>(off, bytes - (uint64_t) buf.size());
6237        f.clear();
6238        f.seekg((std::streamoff) at);
6239        f.read((char*) buf.data(), (std::streamsize) buf.size());
6240        if ((size_t) f.gcount() != buf.size()) {
6241            err = "ArenaExpertSource: short read while hashing pack source " + path.string();
6242            return false;
6243        }
6244        hash_u64(h, at);
6245        h = fnv1a64(buf.data(), (uint64_t) buf.size(), h);
6246    }
6247    return true;
6248}
6249
6250bool shared_arena_pack_hash(const std::string& pack_dir, const std::string& experts_path,
6251                            const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay,
6252                            uint64_t& out, std::string& err) {
6253    uint64_t h = 1469598103934665603ull;
6254    hash_text(h, "strata-shared-expert-arena-pack-v1");
6255    hash_u64(h, (uint64_t) lay.n_layers);
6256    hash_u64(h, (uint64_t) lay.n_expert);
6257    hash_u64(h, lay.total);
6258    hash_u64(h, lay.max_blob);
6259    hash_u64(h, lay.native ? 1 : 0);
6260
6261    const std::filesystem::path pack(pack_dir);
6262    for (const char* name : {"manifest.json", "index.txt", "native_experts.txt"}) {
6263        if (!hash_small_file(pack / name, h, err)) return false;
6264    }
6265
6266    if (std::filesystem::exists(experts_path)) {
6267        if (!hash_sampled_file(experts_path, h, err)) return false;
6268    } else if (!gguf.empty()) {
6269        // Native packs may read experts straight from one or more GGUF shards.  Sample every distinct source
6270        // file named by native_experts.txt; this keeps the fingerprint cheap while still tying it to the model
6271        // bytes rather than only to an equal-size layout.
6272        const std::filesystem::path first(gguf);
6273        std::vector<std::filesystem::path> sources{first};
6274        for (const std::string& name : lay.gguf_file) {
6275            if (name.empty()) continue;
6276            const std::filesystem::path p = first.parent_path() / name;
6277            if (std::find(sources.begin(), sources.end(), p) == sources.end()) sources.push_back(p);
6278        }
6279        for (const auto& p : sources) {
6280            if (!hash_sampled_file(p, h, err)) return false;
6281        }
6282    }
6283
6284    out = h == 0 ? 1 : h;
6285    return true;
6286}
6287
6288}  // namespace
6289
6290namespace {
6291/// The GGUF file that holds role `r` (0 gate, 1 up, 2 down) of layer `l`: a name beside the --native shard
6292/// (native_experts.txt v3 per layer, v4 per role), or the --native shard itself.
6293std::string expert_gguf_file(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, int64_t l, int r) {
6294    const size_t i = (size_t) (3 * l + r);
6295    if (lay.gguf_file.size() <= i || lay.gguf_file[i].empty()) return gguf;
6296    const size_t cut = gguf.find_last_of("/\\");
6297    return (cut == std::string::npos ? std::string() : gguf.substr(0, cut + 1)) + lay.gguf_file[i];
6298}
6299}  // namespace
6300
6301void ExpertSource::record_inputs(const std::string& pack_experts, const std::string& gguf,
6302                                 const strata::kernels::cpu::ExpertLayout& lay, bool from_gguf) {
6303    static const char* roles[3] = {"gate", "up", "down"};
6304    inputs_.clear();
6305    if (!from_gguf) { inputs_.push_back({"pack experts.bin", pack_experts}); return; }
6306    // the same resolution open_gguf / load_experts_gguf use: every (layer, role) tensor and the file it is read from
6307    for (int64_t l = 0; l < lay.n_layers; ++l)
6308        for (int r = 0; r < 3; ++r)
6309            inputs_.push_back({"expert blk." + std::to_string(l) + ".ffn_" + roles[r], expert_gguf_file(gguf, lay, l, r)});
6310}
6311
6312bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, std::string& err) {
6313    static const char* roles[3] = {"gate", "up", "down"};
6314    if (lay.gguf_off.size() != (size_t) (3 * lay.n_layers)) {
6315        err = "native_experts.txt has no GGUF offsets (a pack older than v2): repack it with tools/iq_pack.py";
6316        return false;
6317    }
6318    try {
6319        std::map<std::string, std::unique_ptr<strata::GgufFile>> files;
6320        for (int64_t l = 0; l < lay.n_layers; ++l) {
6321            const auto& fm = lay.fmt[(size_t) l];
6322            const uint64_t blob = lay.bytes[(size_t) l];
6323            const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
6324            for (int r = 0; r < 3; ++r) {
6325                const std::string path = expert_gguf_file(gguf, lay, l, r);
6326                auto& f = files[path];
6327                if (!f) f = std::make_unique<strata::GgufFile>(path);
6328                const std::string name = "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight";
6329                const strata::TensorInfo* t = f->find(name);
6330                const uint64_t want_type = (uint64_t) (r < 2 ? fm.gu_type : fm.d_type);
6331                // GGUF order: dim 0 is the row (the input), dim 1 the rows, dim 2 the experts
6332                const uint64_t cols = (uint64_t) (r < 2 ? fm.n_embd : fm.n_ff);
6333                const uint64_t rows = (uint64_t) (r < 2 ? fm.n_ff : fm.n_embd);
6334                const uint64_t bytes = per[r] * (uint64_t) lay.n_expert;
6335                const uint64_t payload = f->file_size() - f->data_start();
6336                std::string why;
6337                if (t == nullptr) why = "is not in it";
6338                else if (t->type != want_type)
6339                    why = std::string("is ") + t->type_name() + ", the pack says type " + std::to_string(want_type);
6340                else if (t->shape.size() != 3 || t->shape[0] != cols || t->shape[1] != rows ||
6341                         t->shape[2] != (uint64_t) lay.n_expert)
6342                    why = "is not [" + std::to_string(cols) + ", " + std::to_string(rows) + ", " +
6343                          std::to_string(lay.n_expert) + "]";
6344                else if (strata::tensor_payload_bytes(*t) != bytes)
6345                    why = "is not " + std::to_string(per[r]) + " B per expert";
6346                else if (f->data_start() + t->offset != lay.gguf_off[(size_t) (3 * l + r)])
6347                    why = "starts at byte " + std::to_string(f->data_start() + t->offset) + ", the pack says " +
6348                          std::to_string(lay.gguf_off[(size_t) (3 * l + r)]);
6349                else if (t->offset > payload || bytes > payload - t->offset)
6350                    why = "runs past the end of the file (a truncated shard?)";
6351                if (!why.empty()) {
6352                    err = "the pack's native_experts.txt does not match the model: " + name + " in " + path + " " +
6353                          why + " - repack with tools/iq_pack.py from this model's shards";
6354                    return false;
6355                }
6356            }
6357        }
6358        return true;
6359    } catch (const std::exception& e) {
6360        err = std::string("native experts from the GGUF: ") + e.what();
6361        return false;
6362    }
6363}
6364
6365// Plan v0.3 P6: the arena from the model's GGUF shards.  Each layer's gate, up and down tensors hold the 512
6366// experts one after another; they are read in chunks and each expert's slice lands at its place in the blob
6367// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin.  Each role
6368// is read from its own file (native_experts.txt v4: a shard boundary can fall inside a layer; per role as in
6369// #255, gopinath87607).  The caller checks the spans first (check_experts_gguf).
6370// `unbuffered` (Windows, experts_unbuffered): each chunk's 4 KiB-aligned window is read with FILE_FLAG_NO_BUFFERING into
6371// an aligned buffer and scattered into the blobs - no copy through the file cache when the drive is read anyway.
6372LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay,
6373                            int threads, bool unbuffered, const std::atomic<int>* ready, const PadMap* pad) {
6374    // where blob (l, e) goes in `dst`: packed (experts.bin) or the padded layout of pin by need
6375    auto dst_blob = [&lay, pad](int64_t l, int64_t e) -> uint64_t {
6376        return pad != nullptr ? pad->blob_off(l, e) : lay.blob_offset(l, e);
6377    };
6378    // `ready`: layer l is written only once *ready > l + 1 (a PinnedArena registering its slices meanwhile; the next
6379    // slice too, since its registration starts on the page that may hold this layer's tail)
6380    auto wait_ready = [ready](int64_t l) {
6381        if (ready != nullptr)
6382            while (ready->load(std::memory_order_acquire) <= l + 1) std::this_thread::yield();
6383    };
6384    LoadStats st;
6385    st.layers = (uint64_t) lay.n_layers;
6386    const auto t0 = std::chrono::steady_clock::now();
6387    std::atomic<int64_t> next{0};
6388    std::atomic<bool> bad{false};
6389#if defined(_WIN32)
6390    if (unbuffered) {
6391        uint64_t max_chunk = 0;
6392        for (int64_t l = 0; l < lay.n_layers; ++l) {
6393            const auto& fm = lay.fmt[(size_t) l];
6394            max_chunk = std::max<uint64_t>(max_chunk, std::max<uint64_t>(fm.up_off, lay.bytes[(size_t) l] - fm.down_off) * 16);
6395        }
6396        std::mutex err_mu;
6397        std::string err;
6398        auto worker = [&]() {
6399            constexpr uint64_t kSector = 4096;
6400            const uint64_t cap = (max_chunk + 2 * kSector + kSector - 1) / kSector * kSector;
6401            uint8_t* buf = (uint8_t*) VirtualAlloc(nullptr, (size_t) cap, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
6402            HANDLE h = INVALID_HANDLE_VALUE;
6403            std::string open_name;
6404            auto fail = [&](const std::string& what) {
6405                std::lock_guard<std::mutex> g(err_mu);
6406                if (err.empty()) err = what;
6407                bad = true;
6408            };
6409            if (buf == nullptr) fail("cannot allocate a read buffer");
6410            for (;;) {
6411                const int64_t l = next.fetch_add(1);
6412                if (l >= lay.n_layers || bad) break;
6413                wait_ready(l);
6414                const auto& fm = lay.fmt[(size_t) l];
6415                const uint64_t blob = lay.bytes[(size_t) l];
6416                const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
6417                const uint64_t at[3] = {0, fm.up_off, fm.down_off};
6418                for (int r = 0; r < 3 && !bad; ++r) {
6419                    // the handle is kept while consecutive roles share a file (every layer of a v3 pack)
6420                    const std::string name = expert_gguf_file(gguf, lay, l, r);
6421                    if (name != open_name) {
6422                        if (h != INVALID_HANDLE_VALUE) CloseHandle(h);
6423                        const int wide = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, nullptr, 0);
6424                        std::vector<wchar_t> w((size_t) std::max(wide, 1), L'\0');
6425                        if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, w.data(), wide);
6426                        h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
6427                                        FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
6428                        if (h == INVALID_HANDLE_VALUE) {
6429                            fail("cannot open " + name + " (error " + std::to_string((unsigned long long) GetLastError()) + ")");
6430                            break;
6431                        }
6432                        open_name = name;
6433                    }
6434                    const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)];
6435                    const uint64_t total = per[r] * (uint64_t) lay.n_expert;
6436                    const uint64_t chunk = per[r] * 16;           // 16 experts per read
6437                    for (uint64_t done = 0; done < total; done += chunk) {
6438                        const uint64_t n = std::min<uint64_t>(chunk, total - done);
6439                        const uint64_t a0 = (src + done) / kSector * kSector;
6440                        const uint64_t a1 = (src + done + n + kSector - 1) / kSector * kSector;
6441                        OVERLAPPED ov{};
6442                        ov.Offset = (DWORD) a0;
6443                        ov.OffsetHigh = (DWORD) (a0 >> 32);
6444                        DWORD got = 0;
6445                        // the window may run past the end of the file: only the tensor's own bytes have to arrive
6446                        if (!ReadFile(h, buf, (DWORD) (a1 - a0), &got, &ov) || (uint64_t) got < src + done - a0 + n) {
6447                            fail("short unbuffered read of layer " + std::to_string(l) + " in " + name + " (error " +
6448                                 std::to_string((unsigned long long) GetLastError()) + ")");
6449                            break;
6450                        }
6451                        const uint8_t* q = buf + (src + done - a0);
6452                        for (uint64_t k = 0; k < n / per[r]; ++k) {
6453                            const uint64_t e = done / per[r] + k;
6454                            std::memcpy(dst + dst_blob(l, (int64_t) e) + at[r], q + k * per[r], (size_t) per[r]);
6455                        }
6456                    }
6457                }
6458            }
6459            if (h != INVALID_HANDLE_VALUE) CloseHandle(h);
6460            if (buf != nullptr) VirtualFree(buf, 0, MEM_RELEASE);
6461        };
6462        std::vector<std::thread> pool;
6463        for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
6464        worker();
6465        for (auto& t : pool) t.join();
6466        if (bad) {
6467            st.seconds = -1.0;
6468            st.ok = false;
6469            st.error = err.empty() ? "unreadable shard while reading the experts from the GGUF" : err;
6470            return st;
6471        }
6472        st.bytes = lay.total;
6473        st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
6474        return st;
6475    }
6476#else
6477    (void) unbuffered;
6478#endif
6479    auto worker = [&]() {
6480        // #230: `fread` on a `FILE*`, as load_experts_ranges (#89): MSVC's `std::ifstream::read` splits a request
6481        // into 4095-byte freads, which took this path to 0.02 GiB/s on a Windows install without experts.bin.
6482        // The guard closes the handle on every return.
6483        struct Closer {
6484            FILE* f = nullptr;
6485            ~Closer() { if (f != nullptr) std::fclose(f); }
6486        } file;
6487        std::string open_name;
6488        std::vector<uint8_t> buf;
6489        for (;;) {
6490            const int64_t l = next.fetch_add(1);
6491            if (l >= lay.n_layers || bad) break;
6492            wait_ready(l);
6493            const auto& fm = lay.fmt[(size_t) l];
6494            const uint64_t blob = lay.bytes[(size_t) l];
6495            const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
6496            const uint64_t at[3] = {0, fm.up_off, fm.down_off};
6497            for (int r = 0; r < 3; ++r) {
6498                // the handle is kept while consecutive roles share a file (every layer of a v3 pack)
6499                const std::string name = expert_gguf_file(gguf, lay, l, r);
6500                if (name != open_name) {
6501                    if (file.f != nullptr) std::fclose(file.f);
6502                    file.f = std::fopen(name.c_str(), "rb");
6503                    if (file.f == nullptr) { bad = true; return; }
6504                    open_name = name;
6505                }
6506                FILE* const f = file.f;
6507                const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)];
6508                const uint64_t total = per[r] * (uint64_t) lay.n_expert;
6509                const uint64_t chunk = per[r] * 16;           // 16 experts per read
6510                buf.resize((size_t) chunk);
6511                for (uint64_t done = 0; done < total; done += chunk) {
6512                    const uint64_t n = std::min<uint64_t>(chunk, total - done);
6513                    // 64-bit seek: a shard is tens of GB
6514                    if (STRATA_FSEEK64(f, src + done) != 0) { bad = true; return; }
6515                    if (std::fread(buf.data(), 1, (size_t) n, f) != (size_t) n) { bad = true; return; }
6516                    for (uint64_t k = 0; k < n / per[r]; ++k) {
6517                        const uint64_t e = done / per[r] + k;
6518                        std::memcpy(dst + dst_blob(l, (int64_t) e) + at[r], buf.data() + k * per[r], (size_t) per[r]);
6519                    }
6520                }
6521            }
6522        }
6523    };
6524    std::vector<std::thread> pool;
6525    for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
6526    worker();
6527    for (auto& t : pool) t.join();
6528    if (bad) {
6529        st.seconds = -1.0;
6530        st.ok = false;
6531        st.error = "short read or unreadable shard while reading the experts from the GGUF";
6532        return st;
6533    }
6534    st.bytes = lay.total;
6535    st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
6536    return st;
6537}
6538
6539ArenaExpertSource::~ArenaExpertSource() { close(); }
6540
6541bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads,
6542                             std::string& err, uint64_t max_pinned_bytes,
6543                             const std::string& shared_arena_file) {
6544    close();
6545    const std::string path = pack_dir + "/experts.bin";
6546    // plan v0.3 P6: the layout (canonical, or a native pack's per-layer blobs) was loaded by the driver
6547    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
6548    if (lay.n_layers != n_layers || lay.n_expert != n_expert) {
6549        err = "ArenaExpertSource: the expert layout was loaded for a different geometry";
6550        return false;
6551    }
6552    const int64_t blob = (int64_t) lay.max_blob;
6553    const uint64_t want = lay.total;
6554
6555    // plan v0.3 P6: no experts.bin in a native pack -> the experts come straight from the GGUF
6556    const bool from_gguf = !std::ifstream(path, std::ios::binary) && lay.native && !lay.gguf_off.empty() && !gguf_.empty();
6557    // SIZE CHECK BEFORE THE ALLOCATION, not after.  A wrong pack should name the two numbers rather than spend
6558    // 34 GB and a minute of loading first.
6559    if (from_gguf) {
6560        // every (file, offset) of native_experts.txt must be the tensor it claims, of the pack's type and
6561        // dimensions and inside its file - before the allocation, so a pack of another model or a truncated
6562        // shard is a message rather than an arena of plausible wrong experts
6563        if (!check_experts_gguf(gguf_, lay, err)) { err = "ArenaExpertSource: " + err; return false; }
6564    } else {
6565        std::ifstream f(path, std::ios::binary | std::ios::ate);
6566        if (!f) { err = "ArenaExpertSource: cannot open " + path; return false; }
6567        const uint64_t got = (uint64_t) f.tellg();
6568        if (got != want && got != want + (uint64_t) blob) {   // + one blob: STRATA_ARENA_MMAP's padded file
6569            char buf[400];
6570            std::snprintf(buf, sizeof buf,
6571                          "ArenaExpertSource: %s is %llu B but %lld layers x %lld experts (blobs up to %lld B) "
6572                          "make %llu B - this is not the pack this geometry came from",
6573                          path.c_str(), (unsigned long long) got, (long long) n_layers, (long long) n_expert,
6574                          (long long) blob, (unsigned long long) want);
6575            err = buf;
6576            return false;
6577        }
6578    }
6579
6580    // STRATA_ARENA_MMAP=1 (a small-RAM machine whose GPUs hold most experts): the arena is the pack's experts.bin
6581    // mapped READ-ONLY - not locked, not pinned.  The page cache keeps what the CPU pool and the prompt path
6582    // actually read (the experts no VRAM cache holds) and gives back the rest under memory pressure; a page
6583    // dropped is re-read from the file, so a result never depends on what is resident.  The GPUs then get no
6584    // mapped alias: run with --pcie-frac 0.  The first start writes experts.bin (arena layout, padded by one blob
6585    // so a whole-slot copy may start at any expert), later ones map it.
6586#if defined(_WIN32)
6587    static const bool arena_mmap = false;   // POSIX mmap/madvise: Linux only for now
6588#else
6589    static const bool arena_mmap = [] { const char* v = std::getenv("STRATA_ARENA_MMAP"); return v && v[0] == '1'; }();
6590    if (arena_mmap) {
6591        const uint64_t file_bytes = want + (uint64_t) blob;
6592        uint64_t have = 0;
6593        {
6594            std::ifstream f(path, std::ios::binary | std::ios::ate);
6595            if (f) have = (uint64_t) f.tellg();
6596        }
6597        if (have == file_bytes) {
6598            const int fd = ::open(path.c_str(), O_RDONLY);
6599            void* v = fd >= 0 ? mmap(nullptr, (size_t) file_bytes, PROT_READ, MAP_SHARED, fd, 0) : MAP_FAILED;
6600            if (fd >= 0) ::close(fd);
6601            if (v == MAP_FAILED) { err = "ArenaExpertSource: mmap of " + path + " failed"; return false; }
6602            map_ = v;
6603            map_bytes_ = file_bytes;
6604            base_ = (const uint8_t*) v;
6605            pinned_bytes_ = 0;
6606            dev_slice_.clear();
6607            slice_bytes_ = 0;
6608            ranges_ = false;
6609            blobs_ = n_layers * n_expert;
6610            n_expert_ = n_expert;
6611            reads_ = 0;
6612            note_ = "mapped read-only from " + path + " (STRATA_ARENA_MMAP: not locked, not pinned)";
6613            gib_per_s_ = 0.0;
6614            load_seconds_ = load_read_s_ = load_copy_s_ = 0.0;
6615            record_inputs(path, gguf_, lay, from_gguf);   // session files: the mapped experts.bin is a model input
6616            return true;
6617        }
6618    }
6619#endif
6620
6621    // #633: THE RAM BEFORE THE ALLOCATION.  On Linux the arena is an anonymous mapping that succeeds whatever the host
6622    // has; its pages are committed as the load writes them, so a container whose memory limit is below the arena was
6623    // killed by the OOM killer part-way through the load, without a message.  A hard cgroup limit below it is
6624    // certain to end that way: refused, with the numbers.  Less RAM available than the arena (another program, an
6625    // engine still exiting) is only a warning - the OS may make room - per the recommend-not-force rule.
6626    ram_warning_.clear();
6627    ram_short_ = false;
6628    // (a shared arena, --shared-expert-arena, may already be in RAM for another engine: not checked)
6629    if (detail::HostMemory hm; shared_arena_file.empty() && detail::host_available_memory(hm)) {
6630        // --ram-keep-gib W: the arena is chosen only if W GiB stay free after it, so its need here is the arena plus W
6631        const uint64_t need = arena_need_with_keep(want + (uint64_t) blob, ram_keep_bytes);
6632        // under a hard limit the arena also needs the headroom (the engine's own memory comes on top of it, and the arena is never given back)
6633        const uint64_t limit_need = arena_hard_limit_need(want + (uint64_t) blob, ram_keep_bytes, hard_limit_headroom_bytes, fall_back_when_ram_short);
6634        const double gib = 1073741824.0;
6635        char buf[512];
6636        char keep_note[96] = "";
6637        if (ram_keep_bytes > 0)
6638            std::snprintf(keep_note, sizeof keep_note, ", with the %.2f GiB --ram-keep-gib asks to leave free", (double) ram_keep_bytes / gib);
6639        if (arena_ram_verdict(limit_need, ~uint64_t{0}, hm.cgroup_limit, fall_back_when_ram_short) != ArenaRamVerdict::Load) {
6640            if (fall_back_when_ram_short) {   // #4846: the caller reads the experts from the file instead of refusing
6641                std::snprintf(buf, sizeof buf, "it needs %.2f GiB (with the %.2f GiB the engine's own memory and the RAM to keep take on top of it) and this process's memory limit is %.2f GiB",
6642                              (double) limit_need / gib, (double) (limit_need - (want + (uint64_t) blob)) / gib, (double) hm.cgroup_limit / gib);
6643                err = buf;
6644                ram_short_ = true;
6645                return false;
6646            }
6647            std::snprintf(buf, sizeof buf,
6648                          "ArenaExpertSource: the expert arena needs %.2f GiB of RAM but this process's memory limit "
6649                          "(cgroup memory.max / memory.limit_in_bytes) is %.2f GiB: it would be killed while loading. "
6650                          "Raise the container's limit, or run with less RAM: --mmap-experts with "
6651                          "--resident-budget-gib N keeps only the hottest experts in RAM",
6652                          (double) need / gib, (double) hm.cgroup_limit / gib);
6653            err = buf;
6654            return false;
6655        }
6656        if (hm.available < need) {
6657            // #4051: the shortfall is often an engine that was still exiting (the code's own example), a few seconds
6658            // from giving its RAM back: wait for it, not for ever, and say so.  STRATA_ARENA_RAM_WAIT_S changes the
6659            // seconds (0 loads at once, as before this wait).  Still short after it (and after the give-back below): the caller's
6660            // --mmap-experts fallback (#4846) when it asked for one, otherwise the load goes on and only warns.
6661            double wait_s = 20.0;
6662            if (const char* w = std::getenv("STRATA_ARENA_RAM_WAIT_S"); w != nullptr && w[0] != '\0') {
6663                char* end = nullptr;
6664                const double v = std::strtod(w, &end);
6665                if (end != w && *end == '\0' && v >= 0.0 && v <= 3600.0) wait_s = v;
6666            }
6667            double waited = 0.0;
6668            uint64_t avail = hm.available;
6669            if (wait_s > 0.0) {
6670                const bool came = detail::wait_for_ram(
6671                    need, wait_s, 0.25, 5.0,
6672                    [](uint64_t& a) { detail::HostMemory h; if (!detail::host_available_memory(h)) return false; a = h.available; return true; },
6673                    [](double s) { std::this_thread::sleep_for(std::chrono::duration<double>(s)); },
6674                    [&](double w, uint64_t a) {
6675                        std::fprintf(stderr, "strata generate: the expert arena needs %.2f GiB of RAM%s and %.2f GiB is "
6676                                             "available; waiting up to %.0f s for it (another engine still exiting?) - "
6677                                             "%.0f s so far (STRATA_ARENA_RAM_WAIT_S changes this)\n",
6678                                     (double) need / gib, keep_note, (double) a / gib, wait_s, w);
6679                    },
6680                    waited, avail);
6681                if (came)
6682                    std::fprintf(stderr, "strata generate: %.2f GiB of RAM is available now (after %.1f s): loading the "
6683                                         "expert arena\n", (double) avail / gib, waited);
6684                hm.available = avail;
6685            }
6686            if (hm.available < need && give_back_ram) {
6687                // #4846: the shortfall survived the wait.  A lock the engine took by itself (the PLE table's residency lock) is
6688                // given back before the registration starts: its pages stay cached, the OS may take them for the arena.
6689                const uint64_t freed = give_back_ram();
6690                if (freed > 0) {
6691                    detail::HostMemory h2;
6692                    if (detail::host_available_memory(h2)) {
6693                        std::fprintf(stderr, "strata generate: the expert arena needs %.2f GiB of RAM and %.2f GiB was available: "
6694                                             "gave back %.2f GiB of locked RAM, %.2f GiB is available now\n",
6695                                     (double) need / gib, (double) hm.available / gib, (double) freed / gib, (double) h2.available / gib);
6696                        hm.available = h2.available;
6697                    }
6698                }
6699            }
6700            const ArenaRamVerdict verdict = arena_ram_verdict(need, hm.available, ~uint64_t{0}, fall_back_when_ram_short);
6701#if defined(__linux__)
6702            // #5327: the refusal reads every shortfall as one the kernel can only serve by taking another program's
6703            // memory (#4051's host: an engine that was still exiting, anonymous RAM - the stall the refusal is for).
6704            // On a bare Linux host the usual false alarm is a reserved hugetlb pool: MemAvailable does not count free
6705            // huge pages, and a launcher may reserve the pool for exactly this arena (the arena maps MAP_HUGETLB
6706            // first), so the reserve itself takes MemAvailable below the need while the pool holds all of it.  That
6707            // is the case 0.1.54/0.1.55 loaded anyway ("expert arena read through the file cache") at full decode
6708            // speed: credit the pool when it holds the whole arena (and free pages + droppable file pages, which the
6709            // kernel evicts as the arena reads - only a small margin beyond MemAvailable's own count) and load,
6710            // LOUDLY (a service setup never sees stderr).  STRATA_ARENA_FILE_CACHE=0
6711            // refuses as since 0.1.56.  Not under a cgroup limit (the host's cache is not the container's to drop)
6712            // and not on Windows: the proceed path was never trusted there ("buffered (not Windows)", the mapped
6713            // view's trim needs the headroom the refusal keeps).
6714            const bool file_cache_off = [] { const char* v = std::getenv("STRATA_ARENA_FILE_CACHE"); return v != nullptr && v[0] == '0'; }();
6715            bool file_cache_arena = false;
6716            uint64_t memfree_b = 0, droppable_b = 0, huge_free_b = 0;
6717            if (verdict == ArenaRamVerdict::FallBack && hm.cgroup_limit == ~uint64_t{0} && !file_cache_off) {
6718                if (std::ifstream info("/proc/meminfo"); info) {
6719                    const std::string text((std::istreambuf_iterator<char>(info)), std::istreambuf_iterator<char>());
6720                    if (meminfo_free_and_droppable(text, memfree_b, droppable_b, &huge_free_b)) {
6721                        // the pool serves the arena only if the MAP_HUGETLB try is made (STRATA_NO_LARGEPAGES skips it) and
6722                        // the pool holds the whole mapping, which is the padded arena plus the spare blob, not `want + blob`
6723                        uint64_t map_bytes = want + (uint64_t) blob;
6724                        if (pin_by_need_ && !pin_pairs_.empty() && !arena_mmap && shared_arena_file.empty()) {
6725                            uint64_t at = 0;
6726                            for (int64_t l = 0; l < n_layers; ++l)
6727                                at += ((lay.blob_bytes(l) + 4095) & ~(uint64_t) 4095) * (uint64_t) n_expert;
6728                            map_bytes = at + (uint64_t) blob;
6729                        }
6730                        if (std::getenv("STRATA_NO_LARGEPAGES") != nullptr || huge_free_b < map_bytes) huge_free_b = 0;
6731                        file_cache_arena = arena_shortfall_served_by_file_cache(need, memfree_b, droppable_b, huge_free_b);
6732                    }
6733                }
6734            }
6735            if (file_cache_arena) {
6736                std::snprintf(buf, sizeof buf,
6737                              "the experts need %.2f GiB of RAM and %.2f GiB is free, but free memory, file cache and reserved huge "
6738                              "pages can hold them, so they load anyway (same answers). STRATA_ARENA_FILE_CACHE=0 reads them from "
6739                              "the file instead.",
6740                              (double) need / gib, (double) hm.available / gib);
6741                ram_warning_ = buf;   // the caller says it on stderr before the load's numbers
6742                if (notices_on_stdout) {   // --serve only: a service setup never sees stderr (#5327); a plain run keeps its token stream clean
6743                    std::printf("strata generate: WARNING: %s\n", buf);
6744                    std::fflush(stdout);
6745                }
6746            } else
6747#endif
6748            if (verdict == ArenaRamVerdict::FallBack) {
6749                // #4846 (owner 11-01): still short after the wait and the give-back.  Registering anyway can stall the whole host in
6750                // reclaim until it is power-cycled: nothing is allocated, the caller takes the --mmap-experts source for this run.
6751                std::snprintf(buf, sizeof buf,
6752                              "it needs %.2f GiB%s and %.2f GiB is available (%.2f GiB short%s)",
6753                              (double) need / gib, keep_note, (double) hm.available / gib, (double) (need - hm.available) / gib,
6754                              waited > 0.0 ? ", after waiting" : "");
6755                err = buf;
6756                ram_short_ = true;
6757                return false;
6758            }
6759            if (hm.available < need && ram_warning_.empty()) {
6760                std::snprintf(buf, sizeof buf,
6761                              "the expert arena needs %.2f GiB of RAM but %.2f GiB is available (%.2f GiB short%s): the "
6762                              "load may swap or be stopped by the OS%s. Close other programs, or run with less RAM: "
6763                              "--mmap-experts with --resident-budget-gib N",
6764                              (double) need / gib, (double) hm.available / gib, (double) (need - hm.available) / gib,
6765                              waited > 0.0 ? ", after waiting" : "",
6766                              hm.available < need / 2 ? " - with this little room the whole machine can stall in "
6767                                                        "memory reclaim until it is restarted (#4051); on Linux a "
6768                                                        "systemd MemoryHigh= below the RAM keeps one program from "
6769                                                        "taking all of it" : "");
6770                ram_warning_ = buf;
6771            }
6772        }
6773    }
6774
6775    uint64_t pack_hash = 0;
6776    if (!shared_arena_file.empty() &&
6777        !shared_arena_pack_hash(pack_dir, path, gguf_, lay, pack_hash, err)) return false;
6778
6779    // one layer per registration slice, so no expert straddles two registrations.  The arena is one blob
6780    // longer than the file: a copy of a whole VRAM slot (the largest blob) may then start at any expert.
6781    std::vector<uint64_t> bounds, loff, lbytes;
6782    for (int64_t l = 0; l < n_layers; ++l) {
6783        bounds.push_back(lay.layer_offset(l));
6784        loff.push_back(lay.layer_offset(l));
6785        lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert);
6786    }
6787    bounds.push_back(want);
6788    // Pin by need: the arena gets a page-aligned blob STRIDE (blob rounded up to 4 KiB, ~+0.15 %), so every blob starts
6789    // on a page and any set of blobs can be registered exactly (a canonical blob is 337.5 pages: packed, an isolated
6790    // blob could never be registered without its neighbours' bytes).  Not with the mapped arena file (STRATA_ARENA_MMAP
6791    // writes experts.bin from the arena).  The file offsets (loff) stay packed; only the destination moves.
6792    padded_ = false;
6793    pad_ = PadMap{};
6794    if (pin_by_need_ && !pin_pairs_.empty() && !arena_mmap && shared_arena_file.empty()) {   // (a shared arena file has one layout for every process: the packed one)
6795        padded_ = true;
6796        uint64_t at = 0;
6797        for (int64_t l = 0; l < n_layers; ++l) {
6798            const uint64_t b = lay.blob_bytes(l), s = (b + 4095) & ~(uint64_t) 4095;
6799            pad_.dst_off.push_back(at);
6800            pad_.blob.push_back(b);
6801            pad_.stride.push_back(s);
6802            at += s * (uint64_t) n_expert;
6803        }
6804        pad_.total = at;
6805    }
6806    const uint64_t arena_bytes = padded_ ? pad_.total : want;   // the spare blob below comes on top, as before
6807    // Pin by need: the pairs set_pin_priority gave, as byte ranges in priority order.  Neighbours (adjacent blobs) merge
6808    // into one range that takes the best rank of its members, so the hottest experts are registered first and the
6809    // number of cudaHostRegister calls stays far below the number of pairs.
6810    std::vector<std::pair<uint64_t, uint64_t>> need_ranges;
6811    const bool by_need = padded_;
6812    if (by_need) {
6813        // every blob starts on a page and owns its whole stride (pad included), so a run of adjacent blobs is one exact
6814        // range: [first start, last start + stride).  The best rank of a run's members is its priority.
6815        struct Ext { uint64_t off, len; size_t rank; int tier; };
6816        std::vector<Ext> ex;
6817        ex.reserve(pin_pairs_.size());
6818        std::vector<uint8_t> seen((size_t) (n_layers * n_expert), 0);
6819        for (size_t i = 0; i < pin_pairs_.size(); ++i) {
6820            const int64_t l = pin_pairs_[i].first, e = pin_pairs_[i].second;
6821            if (l < 0 || l >= n_layers || e < 0 || e >= n_expert || seen[(size_t) (l * n_expert + e)]) continue;
6822            seen[(size_t) (l * n_expert + e)] = 1;
6823            ex.push_back({arena_off(l, e), pad_.stride[(size_t) l], i, i < pin_first_ ? 0 : 1});
6824        }
6825        std::sort(ex.begin(), ex.end(), [](const Ext& a, const Ext& b) { return a.off < b.off; });
6826        std::vector<Ext> merged;
6827        for (const Ext& x : ex) {
6828            if (!merged.empty() && merged.back().off + merged.back().len == x.off && merged.back().tier == x.tier) {
6829                merged.back().len += x.len;
6830                merged.back().rank = std::min(merged.back().rank, x.rank);
6831            } else {
6832                merged.push_back(x);
6833            }
6834        }
6835        std::stable_sort(merged.begin(), merged.end(), [](const Ext& a, const Ext& b) { return a.rank < b.rank; });
6836        for (const Ext& x : merged) need_ranges.emplace_back(x.off, x.len);
6837    }
6838    // #285: on Windows the per-layer registration runs on a thread ahead of the readers, which wait for their
6839    // layer's slice (the whole arena registered before the load cost ~2.5 s at 33 GiB of 4 KB pages, not hidden).
6840    // Only where the whole arena would be registered: no cap (STRATA_ARENA_PIN_GIB, multi-GPU), no shared arena.
6841    // Linux keeps the whole-arena pin (#253). OPT-IN (STRATA_DEFERRED_REGISTER=1): on the RTX 5070 / Windows the
6842    // arena registered per layer before it is filled decoded ~10% slower than the old order (whole-arena try, sliced
6843    // fallback after the load) with identical output; the start-time gain does not pay for that.
6844#ifdef _WIN32
6845    const char* defer_env = std::getenv("STRATA_DEFERRED_REGISTER");
6846    const bool deferred = !by_need && max_pinned_bytes == 0 && arena_pin_cap_gib() == -1 && shared_arena_file.empty() &&
6847                          (defer_env != nullptr && defer_env[0] != 0 && defer_env[0] != '0');
6848#else
6849    const bool deferred = false;
6850#endif
6851    PinnedArena* a = by_need ? new PinnedArena(arena_bytes + (uint64_t) blob, PinnedArena::ByNeed{}, need_ranges,
6852                                               max_pinned_bytes, shared_arena_file, pack_hash)
6853                   : deferred ? new PinnedArena(want + (uint64_t) blob, bounds, PinnedArena::Deferred{})
6854                              : new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes,
6855                                                shared_arena_file, pack_hash);
6856    if (!a->valid()) {
6857        const std::string why = a->note;
6858        delete a;
6859        err = "ArenaExpertSource: the arena could not be reserved (" +
6860              std::to_string(want + (uint64_t) blob) + " B)" +
6861              (why.empty() ? std::string{} : ": " + why);
6862        return false;
6863    }
6864    // #285: unbuffered when the drive is read anyway and the file cache could not keep the experts for the next
6865    // start either (a 64 GB PC); otherwise the buffered readers, which a warm restart serves from the cache
6866    std::vector<std::string> files;
6867    if (from_gguf) {
6868        for (int64_t l = 0; l < n_layers; ++l)
6869            for (int r = 0; r < 3; ++r) {
6870                const std::string f = expert_gguf_file(gguf_, lay, l, r);
6871                if (std::find(files.begin(), files.end(), f) == files.end()) files.push_back(f);
6872            }
6873    } else {
6874        files.push_back(path);
6875    }
6876    std::string why;
6877    const bool unbuffered = experts_unbuffered(files, want + (uint64_t) blob, why);
6878    const int readers = unbuffered ? std::max(threads, 16) : threads;   // 16 keep a PCIe 5 drive's queue full
6879    LoadStats st;
6880    // A shared arena (--shared-expert-arena, the replicas): ONE engine reads the experts into it, the others wait and skip the
6881    // read.  The state word in the file's header says who: 0 nobody, a pid loading, ~0 filled.  An engine that finds a
6882    // pid that is gone takes the load over (the previous one died mid-read: the arena is read again from the start), so a
6883    // dead loader never leaves the others waiting, and an engine that waits too long loads it itself.
6884    constexpr uint64_t kArenaFilled = ~uint64_t{0};
6885    std::atomic<uint64_t>* arena_state = padded_ ? nullptr : a->shared_state;
6886    bool arena_leader = false, arena_skip = false;
6887    if (arena_state != nullptr) {
6888        const uint64_t me = arena_this_pid();
6889        const auto t_begin = std::chrono::steady_clock::now();
6890        bool said = false;
6891        for (;;) {
6892            uint64_t cur = arena_state->load(std::memory_order_acquire);
6893            if (cur == kArenaFilled) { arena_skip = true; break; }
6894            if (cur == 0 || cur == me) {
6895                if (arena_state->compare_exchange_strong(cur, me, std::memory_order_acq_rel)) { arena_leader = true; break; }
6896                continue;
6897            }
6898            const bool alive = arena_pid_alive(cur);
6899            if (!alive) {
6900                if (arena_state->compare_exchange_strong(cur, me, std::memory_order_acq_rel)) {
6901                    std::fprintf(stderr, "strata generate: shared expert arena: engine %llu died while reading it; reading it again\n",
6902                                 (unsigned long long) cur);
6903                    arena_leader = true;
6904                    break;
6905                }
6906                continue;
6907            }
6908            if (std::chrono::steady_clock::now() - t_begin > std::chrono::minutes(45)) break;   // (loads it on its own)
6909            if (!said) {
6910                said = true;
6911                std::fprintf(stderr, "strata generate: shared expert arena: engine %llu is reading the experts; waiting for it "
6912                                     "instead of reading them again\n", (unsigned long long) cur);
6913            }
6914            std::this_thread::sleep_for(std::chrono::milliseconds(200));
6915        }
6916    }
6917    std::atomic<int> ready{0};
6918    std::thread reg;
6919    if (deferred) {
6920        int dev = 0;
6921        cudaGetDevice(&dev);
6922        reg = std::thread([a, &ready, dev] {
6923            cudaSetDevice(dev);
6924            a->register_slices(ready);
6925        });
6926    }
6927    const std::atomic<int>* rp = deferred ? &ready : nullptr;
6928    if (arena_skip) {
6929        st.ok = true;
6930        st.bytes = want;
6931        st.seconds = 0.0;
6932        std::fprintf(stderr, "strata generate: shared expert arena: already filled by another engine; the read is skipped\n");
6933    } else if (from_gguf) {
6934        st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered, rp, padded_ ? &pad_ : nullptr);
6935    } else {
6936        if (unbuffered && !padded_) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20, rp);
6937        if (!unbuffered || padded_ || (!st.ok && st.error.empty()))   // unaligned ranges / the padded layout: the buffered reader
6938            st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20, rp, padded_ ? &pad_ : nullptr,
6939                                     /*drop_behind=*/strata::core::page_cache_drop::enabled());   // integrated gfx11 under Linux
6940    }
6941    if (reg.joinable()) reg.join();
6942    std::fprintf(stderr, "strata generate: expert arena read %s (%s)\n", unbuffered ? "unbuffered" : "through the file cache",
6943                 why.c_str());
6944    if (!st.ok) {
6945        if (arena_leader) arena_state->store(0, std::memory_order_release);   // (somebody else may try)
6946        delete a;
6947        err = "ArenaExpertSource: the expert load was refused: " + (st.error.empty() ? std::string("unknown") : st.error);
6948        return false;
6949    }
6950    if (st.bytes != want) {
6951        if (arena_leader) arena_state->store(0, std::memory_order_release);
6952        delete a;
6953        err = "ArenaExpertSource: the load read " + std::to_string(st.bytes) + " B of " + std::to_string(want);
6954        return false;
6955    }
6956    if (arena_leader) arena_state->store(kArenaFilled, std::memory_order_release);   // the others may use (and skip reading) it
6957    if (std::getenv("STRATA_VERIFY_ARENA") != nullptr) {   // tests: the loaded arena's checksum, any loader
6958        std::fprintf(stderr, "strata generate: expert arena checksum %016llx (%.2f GiB)\n",
6959                     (unsigned long long) fnv1a64(a->data(), want), (double) want / (1ull << 30));
6960    }
6961    // the first start: write experts.bin for the mapped starts after this one - only when the drive has room for it
6962    // and 2 GiB more (a full drive fails other writes too); otherwise this start says so and runs pinned as before
6963    std::error_code space_ec;
6964    const uint64_t free_disk = arena_mmap && from_gguf ? (uint64_t) std::filesystem::space(
6965        std::filesystem::path(path).parent_path(), space_ec).available : 0;
6966    const bool room = !space_ec && free_disk >= want + (uint64_t) blob + (2ull << 30);
6967    if (arena_mmap && from_gguf && !room)
6968        std::fprintf(stderr, "strata generate: STRATA_ARENA_MMAP: NOT writing %s - %.1f GiB free on that drive, it needs "
6969                             "%.1f GiB plus 2 GiB to spare; this start keeps the arena in RAM\n", path.c_str(),
6970                     (double) free_disk / 1073741824.0, (double) (want + (uint64_t) blob) / 1073741824.0);
6971    if (arena_mmap && from_gguf && room) {
6972        const std::string tmp = path + ".tmp";
6973        std::FILE* f = std::fopen(tmp.c_str(), "wb");
6974        bool ok = f != nullptr && std::fwrite(a->data(), 1, (size_t) want, f) == (size_t) want;
6975        if (ok) {
6976            std::vector<uint8_t> pad((size_t) blob, 0);
6977            ok = std::fwrite(pad.data(), 1, pad.size(), f) == pad.size();
6978        }
6979        if (f) ok = std::fclose(f) == 0 && ok;
6980        if (ok) ok = std::rename(tmp.c_str(), path.c_str()) == 0;
6981        if (!ok) std::remove(tmp.c_str());
6982        std::fprintf(stderr, "strata generate: STRATA_ARENA_MMAP: %s %s (the next start maps it)\n",
6983                     ok ? "wrote" : "could NOT write", path.c_str());
6984    }
6985    arena_ = a;
6986    base_ = a->data();
6987    pinned_bytes_ = a->registered_bytes;
6988    // plan v0.3 P6: device aliases of the mapped registration, for the PCIe share of the misses
6989    dev_slice_.clear();
6990    slice_bytes_ = a->slice_bytes;
6991    pin_start_.clear(); pin_end_.clear(); pin_dev_.clear(); layer_pcie_.clear();
6992    ranges_ = false;
6993    if (a->by_need) {
6994        // device alias of each registered range's start (device_alias adds the blob's distance from it); one
6995        // refusal drops the whole table: no PCIe share rather than a wrong pointer
6996        ranges_ = true;
6997        for (const auto& r : a->pin_ranges) {
6998            void* d = nullptr;
6999            if (cudaHostGetDevicePointer(&d, (void*) (base_ + r.first), 0) != cudaSuccess) {
7000                (void) cudaGetLastError();
7001                ranges_ = false;
7002                break;
7003            }
7004            pin_start_.push_back(r.first);
7005            pin_end_.push_back(r.first + r.second);
7006            pin_dev_.push_back((const uint8_t*) d);
7007        }
7008        if (!ranges_) {
7009            pin_start_.clear(); pin_end_.clear(); pin_dev_.clear();
7010            pinned_bytes_ = 0;
7011        } else {
7012            layer_pcie_.assign((size_t) n_layers, 0);
7013            n_expert_ = n_expert;   // pinned() reads it; the common tail below sets the same value
7014            for (int64_t l = 0; l < n_layers; ++l)
7015                for (int64_t e = 0; e < n_expert && !layer_pcie_[(size_t) l]; ++e)
7016                    layer_pcie_[(size_t) l] = pinned(l, e) ? 1 : 0;
7017        }
7018    } else if (a->registered_bytes > 0) {
7019        std::vector<uint64_t> starts = a->slice_bytes > 0 ? a->slice_starts : std::vector<uint64_t>{0};
7020        for (uint64_t off : starts) {
7021            void* d = nullptr;
7022            if (cudaHostGetDevicePointer(&d, (void*) (base_ + off), 0) != cudaSuccess) {
7023                (void) cudaGetLastError();
7024                dev_slice_.clear();
7025                break;
7026            }
7027            dev_slice_.push_back((const uint8_t*) d);
7028        }
7029    }
7030    blobs_ = n_layers * n_expert;
7031    n_expert_ = n_expert;
7032    reads_ = 0;
7033    note_ = a->note;
7034    gib_per_s_ = st.gib_per_second();
7035    load_seconds_ = st.seconds;
7036    load_read_s_ = st.read_seconds;
7037    load_copy_s_ = st.copy_seconds;
7038    record_inputs(path, gguf_, lay, from_gguf);
7039    return true;
7040}
7041
7042void ArenaExpertSource::close() {
7043#if !defined(_WIN32)
7044    if (map_ != nullptr) munmap(map_, (size_t) map_bytes_);
7045#endif
7046    map_ = nullptr;
7047    map_bytes_ = 0;
7048    inputs_.clear();
7049    if (arena_ != nullptr) {
7050        delete (PinnedArena*) arena_;
7051        arena_ = nullptr;
7052    }
7053    base_ = nullptr;
7054    blobs_ = 0;
7055    n_expert_ = 0;
7056}
7057
7058void ArenaExpertSource::prefetch(int64_t layer, int64_t expert) {
7059#if defined(_WIN32)
7060    (void) layer; (void) expert;
7061#else
7062    if (map_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return;
7063    const auto& lay = strata::kernels::cpu::expert_layout();
7064    const uint64_t off = lay.blob_offset(layer, expert) & ~(uint64_t) 4095;
7065    const uint64_t end = lay.blob_offset(layer, expert) + lay.blob_bytes(layer);
7066    madvise((uint8_t*) map_ + off, (size_t) (end - off), MADV_WILLNEED);
7067#endif
7068}
7069
7070// Only the pages wholly inside the blob: a page shared with a neighbour the CPU may still read stays.  MADV_DONTNEED
7071// unmaps them from this process; they stay in the page cache as clean, unmapped pages - the first the kernel takes
7072// back under pressure, and a minor fault away when the CPU needs the expert again (an adaptive swap evicts it).
7073// Dropping them from the cache too (POSIX_FADV_DONTNEED) made every eviction a re-read from the disk: ~200 major
7074// faults a second in decode, +8 ms a window.  The memory the arena used to hold was never the cache itself but
7075// ROCclr's pin-in-place locks on it (see main) - locked pages are the ones the kernel cannot take back.
7076uint64_t ArenaExpertSource::release(int64_t layer, int64_t expert) {
7077#if defined(_WIN32)
7078    (void) layer; (void) expert;
7079    return 0;
7080#else
7081    if (map_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return 0;
7082    const auto& lay = strata::kernels::cpu::expert_layout();
7083    const uint64_t off = (lay.blob_offset(layer, expert) + 4095) & ~(uint64_t) 4095;
7084    const uint64_t end = (lay.blob_offset(layer, expert) + lay.blob_bytes(layer)) & ~(uint64_t) 4095;
7085    if (end <= off) return 0;
7086    if (madvise((uint8_t*) map_ + off, (size_t) (end - off), MADV_DONTNEED) != 0) return 0;
7087    return end - off;
7088#endif
7089}
7090
7091int64_t ArenaExpertSource::pin_range_of(uint64_t off, uint64_t len) const {
7092    // last range starting at or before the blob; it must also end after it (a blob is inside ONE range: merged
7093    // neighbours are contiguous, and a blob split by a trimmed page is reported unpinned - the safe answer)
7094    const auto it = std::upper_bound(pin_start_.begin(), pin_start_.end(), off);
7095    if (it == pin_start_.begin()) return -1;
7096    const size_t i = (size_t) (it - pin_start_.begin()) - 1;
7097    return off + len <= pin_end_[i] ? (int64_t) i : -1;
7098}
7099
7100uint64_t ArenaExpertSource::arena_off(int64_t layer, int64_t expert) const {
7101    return padded_ ? pad_.blob_off(layer, expert) : strata::kernels::cpu::expert_layout().blob_offset(layer, expert);
7102}
7103
7104bool ArenaExpertSource::pcie_layer(int64_t layer) const {
7105    if (!ranges_) return device_alias(layer, 0) != nullptr;   // the prefix rule (ExpertSource's default)
7106    return layer >= 0 && (size_t) layer < layer_pcie_.size() && layer_pcie_[(size_t) layer] != 0;
7107}
7108
7109bool ArenaExpertSource::pinned(int64_t layer, int64_t expert) const {
7110    if (base_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return false;
7111    const auto& lay = strata::kernels::cpu::expert_layout();
7112    if (ranges_) return pin_range_of(arena_off(layer, expert), lay.blob_bytes(layer)) >= 0;   // the whole blob inside ONE registered range
7113    return lay.blob_offset(layer, expert) + lay.blob_bytes(layer) <= pinned_bytes_;
7114}
7115
7116const uint8_t* ArenaExpertSource::device_alias(int64_t layer, int64_t expert) const {
7117    if (ranges_) {   // pin by need: the range's device base + the blob's offset inside it
7118        if (base_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return nullptr;
7119        const auto& rl = strata::kernels::cpu::expert_layout();
7120        const uint64_t off = arena_off(layer, expert);
7121        const int64_t i = pin_range_of(off, rl.blob_bytes(layer));
7122        return i < 0 ? nullptr : pin_dev_[(size_t) i] + (off - pin_start_[(size_t) i]);
7123    }
7124    if (dev_slice_.empty() || !pinned(layer, expert)) return nullptr;
7125    const auto& lay = strata::kernels::cpu::expert_layout();
7126    if (slice_bytes_ == 0) return dev_slice_[0] + lay.blob_offset(layer, expert);
7127    // one registration slice per layer
7128    if ((size_t) layer >= dev_slice_.size()) return nullptr;
7129    return dev_slice_[(size_t) layer] + (uint64_t) expert * lay.blob_bytes(layer);
7130}
7131
7132const uint8_t* ArenaExpertSource::blob(int64_t layer, int64_t expert) {
7133    if (base_ == nullptr) return nullptr;
7134    if (layer < 0 || expert < 0 || expert >= n_expert_) return nullptr;
7135    const int64_t idx = layer * n_expert_ + expert;
7136    if (idx < 0 || idx >= blobs_) return nullptr;
7137    reads_.fetch_add(1, std::memory_order_relaxed);
7138    // Pointer arithmetic into resident memory.  No fault, no copy, no mapping - which is the entire point of
7139    // this class over `FileExpertSource`.
7140    return base_ + arena_off(layer, expert);
7141}
7142
7143const uint8_t* ArenaExpertSource::blob_at(int64_t layer, int64_t expert) const {
7144    if (base_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return nullptr;
7145    const int64_t idx = layer * n_expert_ + expert;
7146    if (idx < 0 || idx >= blobs_) return nullptr;
7147    return base_ + arena_off(layer, expert);   // (the padded layout of pin by need too)
7148}
7149
7150}  // namespace strata::core
7151
7152// ---- Foresight swap space (see include/strata/core/foresight_swap.hpp) ------------------------------------------
7153namespace strata::core {
7154
7155bool ForesightSwap::init(int slots_per_layer, int64_t layers, int64_t experts, const std::vector<int>& card_of_layer,
7156                         const std::vector<int>& devices, std::string& err) {
7157    slots = slots_per_layer;
7158    n_layers = layers;
7159    n_expert = experts;
7160    const size_t ns = (size_t) (layers * slots);
7161    slot.reset(new Slot[ns]);
7162    where.assign((size_t) (layers * experts), -1);
7163    miss_cnt.assign((size_t) (layers * experts), 0);
7164    miss_at.assign((size_t) (layers * experts), 0);
7165    layer_card = card_of_layer;
7166    layer_dev.resize((size_t) layers);
7167    card_dev = devices;
7168    card_stream.assign(devices.size(), nullptr);
7169    card_mem.assign(devices.size(), nullptr);
7170    card_round.assign(devices.size(), ~0ull);
7171    card_used.assign(devices.size(), 0);
7172    const auto& lay = strata::kernels::cpu::expert_layout();
7173    for (size_t c = 0; c < devices.size(); ++c) {
7174        uint64_t bytes = 0;
7175        for (int64_t l = 0; l < layers; ++l)
7176            if (card_of_layer[(size_t) l] == (int) c) bytes += (uint64_t) slots * (uint64_t) lay.blob_bytes(l);
7177        if (bytes == 0) continue;
7178        const OnDevice on(devices[c]);
7179        cudaStream_t s = nullptr;
7180        if (cudaMalloc(&card_mem[c], bytes) != cudaSuccess ||
7181            cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking) != cudaSuccess) {
7182            cudaGetLastError();
7183            err = "cannot allocate " + std::to_string(bytes >> 20) + " MiB on CUDA" + std::to_string(devices[c]) +
7184                  " (raise --vram-reserve-mib by about that much)";
7185            return false;
7186        }
7187        card_stream[c] = s;
7188        uint64_t off = 0;
7189        for (int64_t l = 0; l < layers; ++l) {
7190            if (card_of_layer[(size_t) l] != (int) c) continue;
7191            layer_dev[(size_t) l] = devices[c];
7192            const uint64_t bb = (uint64_t) lay.blob_bytes(l);
7193            for (int s2 = 0; s2 < slots; ++s2) {
7194                Slot& sl = slot[(size_t) (l * slots + s2)];
7195                sl.dptr = (unsigned long long) ((uint8_t*) card_mem[c] + off);
7196                sl.bytes = bb;
7197                cudaEvent_t ev = nullptr;
7198                if (cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) != cudaSuccess) {
7199                    cudaGetLastError();
7200                    err = "cannot create the copy events";
7201                    return false;
7202                }
7203                sl.ev = ev;
7204                off += bb;
7205            }
7206        }
7207    }
7208    filler_ = std::thread([this] { fill_loop(); });
7209    return true;
7210}
7211
7212ForesightSwap::~ForesightSwap() {
7213    {
7214        std::lock_guard<std::mutex> lk(mu_);
7215        stop_ = true;
7216    }
7217    cv_.notify_all();
7218    if (filler_.joinable()) filler_.join();
7219    for (size_t c = 0; c < card_dev.size(); ++c) {
7220        const OnDevice on(card_dev[c]);
7221        if (card_stream[c]) cudaStreamSynchronize((cudaStream_t) card_stream[c]);
7222        if (card_mem[c]) cudaFree(card_mem[c]);
7223        if (card_stream[c]) cudaStreamDestroy((cudaStream_t) card_stream[c]);
7224    }
7225    if (slot)
7226        for (int64_t i = 0; i < n_layers * slots; ++i)
7227            if (slot[(size_t) i].ev) cudaEventDestroy((cudaEvent_t) slot[(size_t) i].ev);
7228}
7229
7230void ForesightSwap::fill_loop() {
7231    strata::platform::name_this_thread("strata-fill");
7232    int cur_dev = -1;
7233    for (;;) {
7234        int64_t idx;
7235        {
7236            std::unique_lock<std::mutex> lk(mu_);
7237            cv_.wait(lk, [&] { return stop_ || !queue_.empty(); });
7238            if (stop_) return;
7239            idx = queue_.front();
7240            queue_.pop_front();
7241        }
7242        Slot& sl = slot[(size_t) idx];
7243        const int64_t l = idx / slots;
7244        const int dev = layer_dev[(size_t) l];
7245        if (dev != cur_dev) { cudaSetDevice(dev); cur_dev = dev; }
7246        cudaStream_t s = (cudaStream_t) card_stream[(size_t) layer_card[(size_t) l]];
7247        if (cudaMemcpyAsync((void*) sl.dptr, sl.src, sl.bytes, cudaMemcpyHostToDevice, s) != cudaSuccess ||
7248            cudaEventRecord((cudaEvent_t) sl.ev, s) != cudaSuccess) {
7249            cudaGetLastError();
7250            if (!failed.exchange(true)) std::fprintf(stderr, "strata serve: foresight swap: a copy failed - swap space off\n");
7251            continue;   // never marked issued: the slot is never used
7252        }
7253        sl.issued.store(true, std::memory_order_release);
7254    }
7255}
7256
7257bool ForesightSwap::take(int64_t layer, int32_t expert, unsigned long long& ptr) {
7258    std::lock_guard<std::mutex> smu_lk(smu_);
7259    const int s = where[(size_t) (layer * n_expert + expert)];
7260    if (s < 0) return false;
7261    Slot& sl = slot[(size_t) (layer * slots + s)];
7262    if (!sl.ready) {
7263        if (!sl.loading || !sl.issued.load(std::memory_order_acquire)) { ++pending; return false; }
7264        const cudaError_t q = cudaEventQuery((cudaEvent_t) sl.ev);
7265        if (q != cudaSuccess) {
7266            if (q != cudaErrorNotReady) cudaGetLastError();
7267            ++pending;
7268            return false;
7269        }
7270        sl.ready = true;
7271        sl.loading = false;
7272        if (verify) {   // test mode: the bytes the GPU will read must be the expert's own
7273            std::vector<uint8_t> back((size_t) sl.bytes);
7274            const OnDevice on(layer_dev[(size_t) layer]);
7275            const bool same = cudaMemcpy(back.data(), (const void*) sl.dptr, (size_t) sl.bytes, cudaMemcpyDeviceToHost) ==
7276                                  cudaSuccess && std::memcmp(back.data(), sl.src, (size_t) sl.bytes) == 0;
7277            if (same) ++verify_ok;
7278            else {
7279                cudaGetLastError();
7280                ++verify_bad;
7281                sl.ready = false;                           // never serve it
7282                where[(size_t) (layer * n_expert + expert)] = -1;
7283                sl.expert = -1;
7284                return false;
7285            }
7286        }
7287    }
7288    sl.last_ref = completed.load(std::memory_order_acquire);
7289    ptr = sl.dptr;
7290    ++hits;
7291    return true;
7292}
7293
7294void ForesightSwap::hold(int64_t layer, int32_t expert) {
7295    if (layer < 0 || layer >= n_layers || expert < 0 || expert >= n_expert) return;
7296    std::lock_guard<std::mutex> smu_lk(smu_);
7297    const size_t key = (size_t) (layer * n_expert + expert);
7298    const int s = where[key];
7299    where[key] = kHeld;
7300    if (s < 0) return;
7301    Slot& sl = slot[(size_t) (layer * slots + s)];
7302    sl.expert = kDropped;   // `loading` and `last_ref` stay: a copy in flight and a window that read it are waited for
7303    sl.ready = false;
7304    ++dropped;
7305}
7306
7307void ForesightSwap::unhold(int64_t layer, int32_t expert) {
7308    if (layer < 0 || layer >= n_layers || expert < 0 || expert >= n_expert) return;
7309    std::lock_guard<std::mutex> smu_lk(smu_);
7310    int16_t& w = where[(size_t) (layer * n_expert + expert)];
7311    if (w == kHeld) w = -1;
7312}
7313
7314void ForesightSwap::note_miss(ExpertSource* src, int64_t layer, int32_t expert) {
7315    std::lock_guard<std::mutex> smu_lk(smu_);
7316    request_locked(src, layer, expert, false);
7317}
7318
7319void ForesightSwap::predict(ExpertSource* src, int64_t layer, int32_t expert) {
7320    if (layer < 0 || layer >= n_layers || expert < 0 || expert >= n_expert) return;
7321    std::lock_guard<std::mutex> smu_lk(smu_);
7322    request_locked(src, layer, expert, true);
7323}
7324
7325void ForesightSwap::request_locked(ExpertSource* src, int64_t layer, int32_t expert, bool predicted_copy) {
7326    if (failed.load(std::memory_order_relaxed)) return;
7327    const size_t key = (size_t) (layer * n_expert + expert);
7328    if (where[key] != -1) return;                       // already on its way, or held by an exchange (#2134)
7329    const uint64_t now = completed.load(std::memory_order_acquire);
7330    if (admit > 1 && !predicted_copy) {
7331        if (now > miss_at[key] + 4) miss_cnt[key] = 0;
7332        miss_at[key] = now;
7333        if (miss_cnt[key] < 255) ++miss_cnt[key];
7334        if (miss_cnt[key] < admit) return;
7335    }
7336    const int c = layer_card[(size_t) layer];
7337    if (card_round[(size_t) c] != now) { card_round[(size_t) c] = now; card_used[(size_t) c] = 0; }
7338    if (card_used[(size_t) c] >= budget) { ++over_budget; return; }
7339    if (src == nullptr || !src->pinned(layer, expert)) return;   // async copies need the pinned arena
7340    const uint8_t* b = src->blob(layer, expert);
7341    if (b == nullptr) return;
7342    int best = -1;
7343    uint64_t best_ref = ~0ull;
7344    for (int s = 0; s < slots; ++s) {   // an empty slot, else the one used longest ago that no window can still read
7345        Slot& sl = slot[(size_t) (layer * slots + s)];
7346        if (sl.loading) {   // copied in but never asked for since: landed long ago -> an ordinary candidate
7347            if (sl.last_ref + (uint64_t) depth > now || !sl.issued.load(std::memory_order_acquire)) continue;
7348            const cudaError_t q = cudaEventQuery((cudaEvent_t) sl.ev);
7349            if (q != cudaSuccess) { if (q != cudaErrorNotReady) cudaGetLastError(); continue; }
7350            sl.loading = false;
7351            sl.ready = true;
7352        }
7353        if (sl.expert == -1) { best = s; break; }      // never used (a dropped slot, kDropped, waits like a used one)
7354        if (sl.last_ref + (uint64_t) depth > now) continue;
7355        if (sl.last_ref < best_ref) { best_ref = sl.last_ref; best = s; }
7356    }
7357    if (best < 0) { ++busy; return; }
7358    Slot& sl = slot[(size_t) (layer * slots + best)];
7359    if (sl.expert >= 0) where[(size_t) (layer * n_expert + sl.expert)] = -1;
7360    sl.expert = expert;
7361    sl.ready = false;
7362    sl.loading = true;
7363    sl.issued.store(false, std::memory_order_relaxed);
7364    sl.src = b;
7365    sl.last_ref = now;
7366    where[key] = (int16_t) best;
7367    ++card_used[(size_t) c];
7368    ++copies;
7369    if (predicted_copy) ++predicted;
7370    {
7371        std::lock_guard<std::mutex> lk(mu_);
7372        queue_.push_back(layer * slots + best);
7373    }
7374    cv_.notify_one();
7375}
7376
7377std::string ForesightSwap::report() const {
7378    std::lock_guard<std::mutex> smu_lk(const_cast<std::mutex&>(smu_));
7379    char buf[320];
7380    std::snprintf(buf, sizeof buf, "foresight swap: %llu experts served from the swap space, %llu copies (%llu from the "
7381                                   "router look-ahead), %llu not landed yet, %llu no free slot, %llu over budget%s",
7382                  (unsigned long long) hits, (unsigned long long) copies, (unsigned long long) predicted,
7383                  (unsigned long long) pending, (unsigned long long) busy, (unsigned long long) over_budget, verify ? "" : "");
7384    std::string r = buf;
7385    if (dropped > 0) r += ", " + std::to_string(dropped) + " dropped by exchanges";
7386    if (verify) r += ", verified " + std::to_string(verify_ok) + " ok / " + std::to_string(verify_bad) + " BAD";
7387    return r;
7388}
7389
7390ForesightSwap* foresight_swap_from_env(int64_t layers, int64_t experts, const std::vector<int>& card_of_layer,
7391                                       const std::vector<int>& devices) {
7392    const char* v = std::getenv("STRATA_FS_SLOTS");
7393    const int slots = v ? std::atoi(v) : 0;
7394    if (slots <= 0) return nullptr;
7395    if (const char* dp = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); dp && std::atoi(dp) != 0) {
7396        std::fprintf(stderr, "strata serve: foresight swap: off beside STRATA_VERIFY_DEVICE_PLAN (the device would plan "
7397                             "resident layers without the host)\n");
7398        return nullptr;
7399    }
7400    auto* f = new ForesightSwap();
7401    auto env_int = [](const char* name, int def, int lo) { const char* e = std::getenv(name); const int x = e ? std::atoi(e) : def; return x < lo ? lo : x; };
7402    f->budget = env_int("STRATA_FS_BUDGET", 32, 1);
7403    f->admit = env_int("STRATA_FS_ADMIT", 1, 1);
7404    f->depth = env_int("STRATA_FS_DEPTH", 4, 2);
7405    f->verify = env_int("STRATA_FS_VERIFY", 0, 0) != 0;
7406    std::string err;
7407    if (!f->init(std::min(slots, 64), layers, experts, card_of_layer, devices, err)) {
7408        std::fprintf(stderr, "strata serve: foresight swap: %s - swap space off\n", err.c_str());
7409        delete f;
7410        return nullptr;
7411    }
7412    std::fprintf(stderr, "strata serve: foresight swap: %d slots per layer on %zu card(s), up to %d copies per card and "
7413                         "window, admit after %d miss(es), reuse after %d windows\n",
7414                 f->slots, devices.size(), f->budget, f->admit, f->depth);
7415    return f;
7416}
7417
7418}  // namespace strata::core