okami.mom/strata

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

Niko1221Merge f-141-amdintel: AMD and Intel work, watchdog file-tier tolerance, portsa00d88938

main
175.2 KiB3647 linesraw
1// src/core/expert_source.cpp - the adapter.  See the header for the three clauses of the contract.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include <dpct/dpct.hpp>
5#include "strata/sycl_queue.hpp"
6#include "strata/core/expert_source.hpp"
7#include "strata/core/remote_experts.hpp"
8#include "strata/core/peer_experts.hpp"
9#include "strata/kernels/cpu/expert_layout.hpp"
10#include "strata/artifact/gguf_reader.hpp"
11
12#include "strata/core/pinned.hpp"
13#include "strata/platform/memory.hpp"
14#include "strata/kernels/elementwise.hpp"
15#include "strata/kernels/quantize_act.hpp"
16#include "strata/kernels/s2_expert_grouped.hpp"
17#include "strata/kernels/cpu/kq_avx1.hpp"
18#include "strata/kernels/cpu/kq_avx2.hpp"
19
20#include <algorithm>
21#include <atomic>
22#include <cerrno>
23#include <chrono>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <fstream>
28#include <filesystem>
29#include <sstream>
30#include <limits>
31#include <map>
32#include <memory>
33#include <mutex>
34#include <thread>
35#include <utility>
36#include <vector>
37
38#if defined(_WIN32)
39#define WIN32_LEAN_AND_MEAN
40#ifndef NOMINMAX
41#define NOMINMAX   // std::numeric_limits<T>::max() below
42#endif
43#include <windows.h>
44#else
45#include <fcntl.h>
46#include <sys/mman.h>
47#include <sys/stat.h>
48#include <unistd.h>
49#endif
50#if defined(__linux__)
51#include <cerrno>
52#include <linux/aio_abi.h>   // the kernel's own asynchronous reads (io_submit): no library, allowed by Docker's seccomp
53#include <sys/syscall.h>
54#endif
55
56// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform
57#ifndef STRATA_FSEEK64
58#ifdef _WIN32
59#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET)
60#else
61#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET)
62#endif
63#endif
64
65namespace strata::core {
66
67namespace detail {
68
69bool cgroup_available_bytes(uint64_t limit, const CgroupMemoryStat& stat, uint64_t& bytes) {
70    bytes = 0;
71    if (!stat.valid) return false;
72
73    // memory.stat's inactive_file can race memory.current, so bound it to charged usage first.
74    uint64_t reclaimable = std::min(stat.inactive_file, stat.current);
75    reclaimable = stat.file_dirty >= reclaimable ? 0 : reclaimable - stat.file_dirty;
76    reclaimable = stat.file_writeback >= reclaimable ? 0 : reclaimable - stat.file_writeback;
77
78    // Reclaiming clean file pages reduces usage; saturating subtraction also handles a transient over-limit read.
79    const uint64_t usage_after_reclaim = stat.current - reclaimable;
80    bytes = usage_after_reclaim < limit ? limit - usage_after_reclaim : 0;
81    return true;
82}
83
84uint64_t clamp_resident_budget(uint64_t requested, uint64_t physical, uint64_t commit, uint64_t headroom) {
85    const uint64_t available = std::min(physical, commit);
86    const uint64_t room = available > headroom ? available - headroom : 0;
87    if (requested <= room) return requested;
88    const uint64_t margin = 256ull << 20;
89    return room > margin ? room - margin : 0;
90}
91
92bool make_cache_complement_plan(
93    int64_t n_layers, int64_t n_expert, const std::vector<uint64_t>& layer_blob_bytes,
94    const std::vector<std::pair<int32_t, int32_t>>& primary_gpu_pairs,
95    const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs,
96    std::vector<uint64_t>& offsets, uint64_t& bytes, std::string& err) {
97    offsets.clear();
98    bytes = 0;
99    err.clear();
100    if (n_layers <= 0 || n_expert <= 0 || layer_blob_bytes.size() != (size_t) n_layers) {
101        err = "FileExpertSource: invalid geometry for the cache complement plan";
102        return false;
103    }
104    if ((uint64_t) n_layers > (uint64_t) std::numeric_limits<size_t>::max() / (uint64_t) n_expert) {
105        err = "FileExpertSource: cache complement index table is too large";
106        return false;
107    }
108    const size_t count = (size_t) n_layers * (size_t) n_expert;
109    std::vector<uint8_t> omitted(count, 0);
110    auto mark_pairs = [&](const std::vector<std::pair<int32_t, int32_t>>& pairs, uint8_t bit,
111                          const char* label) -> bool {
112        for (const auto& pair : pairs) {
113            if (pair.first < 0 || pair.second < 0 || pair.first >= n_layers || pair.second >= n_expert) {
114                err = std::string("FileExpertSource: ") + label + " pair is outside the expert geometry";
115                return false;
116            }
117            const size_t index = (size_t) pair.first * (size_t) n_expert + (size_t) pair.second;
118            if ((omitted[index] & bit) != 0) {
119                err = std::string("FileExpertSource: duplicate ") + label + " pair in the cache complement plan";
120                return false;
121            }
122            if (bit == 2 && (omitted[index] & 1) != 0) {
123                err = "FileExpertSource: the primary and additional GPU expert tiers overlap";
124                return false;
125            }
126            omitted[index] |= bit;
127        }
128        return true;
129    };
130    if (!mark_pairs(primary_gpu_pairs, 1, "primary GPU") ||
131        !mark_pairs(additional_gpu_pairs, 2, "additional GPU")) return false;
132    for (uint64_t blob_bytes : layer_blob_bytes) {
133        if (blob_bytes == 0) {
134            err = "FileExpertSource: cache complement layer has zero-sized expert blobs";
135            return false;
136        }
137    }
138
139    offsets.assign(count, kNoCacheComplement);
140    for (int64_t layer = 0; layer < n_layers; ++layer) {
141        const uint64_t blob_bytes = layer_blob_bytes[(size_t) layer];
142        for (int64_t expert = 0; expert < n_expert; ++expert) {
143            const size_t index = (size_t) layer * (size_t) n_expert + (size_t) expert;
144            if (omitted[index] != 0) continue;
145            if (bytes > std::numeric_limits<uint64_t>::max() - blob_bytes) {
146                offsets.clear();
147                bytes = 0;
148                err = "FileExpertSource: cache complement size overflows";
149                return false;
150            }
151            offsets[index] = bytes;
152            bytes += blob_bytes;
153        }
154    }
155    if (bytes > (uint64_t) std::numeric_limits<size_t>::max()) {
156        offsets.clear();
157        bytes = 0;
158        err = "FileExpertSource: cache complement exceeds the host address space";
159        return false;
160    }
161    return true;
162}
163
164const uint8_t* cache_complement_blob_or_fallback(
165    size_t index, const std::vector<uint64_t>& offsets, const uint8_t* complement_host,
166    const uint8_t* mapped_fallback) {
167    if (complement_host != nullptr && index < offsets.size() && offsets[index] != kNoCacheComplement)
168        return complement_host + (size_t) offsets[index];
169    return mapped_fallback;
170}
171
172int64_t choose_resident_keep_from(const std::vector<uint64_t>& slot_bytes, uint64_t base_bytes, uint64_t budget,
173                                  int64_t lend_from) {
174    if (base_bytes > budget) return -1;
175    const int64_t slots = (int64_t) slot_bytes.size();
176    if (lend_from < 0 || lend_from > slots) lend_from = slots;   // no lend region: only the experts no slot holds
177    int64_t keep = slots;
178    uint64_t bytes = base_bytes;
179    while (keep > lend_from) {
180        const uint64_t b = slot_bytes[(size_t) keep - 1];
181        if (b > budget - bytes) break;
182        bytes += b;
183        --keep;
184    }
185    return keep;
186}
187
188bool exchange_cache_complement(std::vector<uint64_t>& offsets, size_t in, size_t out) {
189    if (in == out || in >= offsets.size() || out >= offsets.size() || offsets[in] == kNoCacheComplement ||
190        offsets[out] != kNoCacheComplement) return false;
191    offsets[out] = offsets[in];
192    offsets[in] = kNoCacheComplement;
193    return true;
194}
195
196}  // namespace detail
197
198namespace {
199
200#if defined(__linux__)
201bool read_cgroup_memory_stat(const std::filesystem::path& path, uint64_t current,
202                             detail::CgroupMemoryStat& stat) {
203    std::ifstream input(path / "memory.stat");
204    if (!input) return false;
205
206    bool inactive_file = false, file_dirty = false, file_writeback = false;
207    std::string line;
208    while (std::getline(input, line)) {
209        std::istringstream fields(line);
210        std::string key;
211        uint64_t value = 0;
212        if (!(fields >> key >> value)) return false;
213        fields >> std::ws;
214        if (!fields.eof()) return false;
215
216        if (key == "inactive_file") {
217            if (inactive_file) return false;
218            inactive_file = true;
219            stat.inactive_file = value;
220        } else if (key == "file_dirty") {
221            if (file_dirty) return false;
222            file_dirty = true;
223            stat.file_dirty = value;
224        } else if (key == "file_writeback") {
225            if (file_writeback) return false;
226            file_writeback = true;
227            stat.file_writeback = value;
228        }
229    }
230    if (!input.eof() || !inactive_file || !file_dirty || !file_writeback) return false;
231    stat.current = current;
232    stat.valid = true;
233    return true;
234}
235#endif
236
237}  // namespace
238
239namespace detail {
240
241bool host_available_memory(HostMemory& m, const std::string& meminfo, const std::string& self_cgroup,
242                           const std::string& cgroup_root) {
243    m = HostMemory{};
244#if defined(_WIN32)
245    (void) meminfo; (void) self_cgroup; (void) cgroup_root;
246    MEMORYSTATUSEX status{};
247    status.dwLength = sizeof(status);
248    if (!GlobalMemoryStatusEx(&status)) return false;
249    m.available = (uint64_t) status.ullAvailPhys;
250    m.commit = (uint64_t) status.ullAvailPageFile;
251    return m.available > 0;
252#elif defined(__linux__)
253    // MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES.
254    std::ifstream info(meminfo);
255    std::string line;
256    uint64_t bytes = 0;
257    while (std::getline(info, line)) {
258        std::istringstream fields(line);
259        std::string key, unit;
260        uint64_t value = 0;
261        if (fields >> key >> value >> unit && key == "MemAvailable:" && unit == "kB" &&
262            value <= std::numeric_limits<uint64_t>::max() / 1024) bytes = value * 1024;
263    }
264    if (bytes == 0) return false;
265    // Account for the tightest cgroup ancestor limit when its normal mount is visible.
266    // This is a point-in-time guard, not a reservation against concurrent allocations.
267    std::ifstream groups(self_cgroup);
268    if (!groups) return false;
269    const std::filesystem::path root(cgroup_root);
270    bool v2 = false;
271    std::string v1_path;   // the memory controller's group (cgroup v1), when there is no v2 line
272    while (std::getline(groups, line)) {
273        if (line.rfind("0::/", 0) != 0) {
274            // v1: "N:controller[,controller]:/path"
275            const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1);
276            if (c2 == std::string::npos) continue;
277            std::istringstream ctl(line.substr(c1 + 1, c2 - c1 - 1));
278            for (std::string c; std::getline(ctl, c, ',');)
279                if (c == "memory") v1_path = line.substr(c2 + 1);
280            continue;
281        }
282        auto path = (root / line.substr(4)).lexically_normal();
283        if (path.string().rfind(root.string(), 0) != 0 || !std::filesystem::is_directory(path)) return false;
284        v2 = true;
285        while (path.string().rfind(root.string(), 0) == 0) {
286            std::ifstream limit_file(path / "memory.max"), current_file(path / "memory.current");
287            std::string limit;
288            uint64_t current = 0;
289            const bool readable = bool(limit_file >> limit) && bool(current_file >> current);
290            // The host's root cgroup has no memory.max; ordinary child groups must expose their limits.
291            if (!readable && !(path == root && !std::filesystem::exists(path / "memory.max") &&
292                               std::filesystem::exists(path / "cgroup.controllers"))) return false;
293            if (readable && limit != "max") {
294                try {
295                    size_t consumed = 0;
296                    const uint64_t cap = std::stoull(limit, &consumed);
297                    if (consumed != limit.size()) return false;
298                    CgroupMemoryStat stat;
299                    if (!read_cgroup_memory_stat(path, current, stat)) return false;
300                    uint64_t cgroup_available = 0;
301                    if (!cgroup_available_bytes(cap, stat, cgroup_available)) return false;
302                    bytes = std::min(bytes, cgroup_available);
303                    m.cgroup_limit = std::min(m.cgroup_limit, cap);
304                } catch (...) { return false; }
305            }
306            if (path == root) break;
307            path = path.parent_path();
308        }
309    }
310    if (!v2 && !v1_path.empty()) {
311        // #633: cgroup v1 (older Docker hosts, RHEL 7/8): the memory controller's group and its ancestors.  An
312        // unlimited group says a number near 2^63 (rounded to its page size); a group whose files are not
313        // visible (no mount in this namespace) is skipped - MemAvailable alone, as with no cgroup at all.
314        const std::filesystem::path mroot = root / "memory";
315        auto path = (mroot / v1_path.substr(v1_path.rfind('/', 0) == 0 ? 1 : 0)).lexically_normal();
316        while (path.string().rfind(mroot.string(), 0) == 0) {
317            std::ifstream limit_file(path / "memory.limit_in_bytes"), usage_file(path / "memory.usage_in_bytes");
318            uint64_t cap = 0, usage = 0;
319            if (limit_file >> cap && usage_file >> usage && cap < (1ull << 62)) {
320                bytes = std::min(bytes, usage < cap ? cap - usage : 0);
321                m.cgroup_limit = std::min(m.cgroup_limit, cap);
322            }
323            if (path == mroot) break;
324            path = path.parent_path();
325        }
326    }
327    m.available = bytes;
328    return true;
329#else
330    (void) meminfo; (void) self_cgroup; (void) cgroup_root;
331    const long pages = sysconf(_SC_AVPHYS_PAGES);
332    const long page_bytes = sysconf(_SC_PAGESIZE);
333    if (pages <= 0 || page_bytes <= 0 ||
334        (uint64_t) pages > std::numeric_limits<uint64_t>::max() / (uint64_t) page_bytes) return false;
335    m.available = (uint64_t) pages * (uint64_t) page_bytes;
336    return m.available > 0;
337#endif
338}
339
340}  // namespace detail
341
342namespace {
343
344bool available_memory_bytes(uint64_t& bytes, uint64_t* commit = nullptr) {
345    detail::HostMemory m;
346    if (!detail::host_available_memory(m)) return false;
347    bytes = m.available;
348    if (commit != nullptr) *commit = m.commit;
349    return bytes > 0;
350}
351
352void log_complement_memory(const char* stage, uint64_t requested) {
353#if defined(_WIN32)
354    MEMORYSTATUSEX status{};
355    status.dwLength = sizeof(status);
356    if (!GlobalMemoryStatusEx(&status)) {
357        std::fprintf(stderr, "FileExpertSource: %s: GlobalMemoryStatusEx failed (error %lu)\n", stage, GetLastError());
358        return;
359    }
360    std::fprintf(stderr, "FileExpertSource: %s: requested %.2f GiB, available RAM %.2f GiB, available commit %.2f GiB "
361                         "(limit %.2f GiB), available virtual address space %.2f GiB\n",
362                 stage, (double) requested / 1073741824.0, (double) status.ullAvailPhys / 1073741824.0,
363                 (double) status.ullAvailPageFile / 1073741824.0, (double) status.ullTotalPageFile / 1073741824.0,
364                 (double) status.ullAvailVirtual / 1073741824.0);
365#else
366    (void) stage;
367    (void) requested;
368#endif
369}
370
371/// #286: an unbuffered file handle - a HANDLE on Windows, an O_DIRECT descriptor (as a pointer-sized integer) on Linux.
372void close_direct(void* h) {
373#if defined(_WIN32)
374    CloseHandle((HANDLE) h);
375#else
376    ::close((int) (intptr_t) h);
377#endif
378}
379
380/// #286/#577: whether the file tier reads its `read_bytes` unbuffered, beside `arena_bytes` of RAM copy still to be
381/// taken.  Windows times probe reads too (experts_unbuffered); on Linux the same rule as its `cache_counts = false`
382/// arm decides: whether the file cache could keep those bytes at all, from MemAvailable and the tightest cgroup
383/// limit (host_available_memory).  STRATA_UNBUFFERED_LOAD=1 / 0 forces it either way, as on Windows.
384bool file_tier_unbuffered(const std::vector<std::string>& paths, uint64_t arena_bytes, uint64_t read_bytes,
385                          std::string& why) {
386#if defined(_WIN32)
387    return experts_unbuffered(paths, arena_bytes, why, /*cache_counts=*/false, read_bytes);
388#elif defined(__linux__)
389    (void) paths;
390    if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') {
391        why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
392        return env[0] != '0';
393    }
394    uint64_t avail = 0;
395    if (!available_memory_bytes(avail)) {
396        why = "the available RAM is unknown";
397        return false;
398    }
399    const bool keepable = strata::platform::file_cache_keeps(avail, arena_bytes, read_bytes);
400    char msg[256];
401    std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB "
402                  "of experts read from the files: the file cache %s keep them",
403                  (double) avail / (1ull << 30), (double) arena_bytes / (1ull << 30), (double) read_bytes / (1ull << 30),
404                  keepable ? "can" : "cannot");
405    why = msg;
406    return !keepable;
407#else
408    (void) paths; (void) arena_bytes; (void) read_bytes;
409    why = "through the file cache (no unbuffered reads on this platform)";
410    return false;
411#endif
412}
413
414}  // namespace
415
416// ================================ THE FILE-BACKED SOURCE ================================
417
418FileExpertSource::~FileExpertSource() { close(); }
419
420bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err) {
421    close();
422    if (n_layers <= 0 || n_expert <= 0) { err = "FileExpertSource: the geometry is empty"; return false; }
423    const auto& layout = strata::kernels::cpu::expert_layout();
424    if (layout.n_layers != n_layers || layout.n_expert != n_expert) {
425        err = "FileExpertSource: the requested geometry does not match the loaded expert layout";
426        return false;
427    }
428    if ((uint64_t) n_layers > (uint64_t) std::numeric_limits<int64_t>::max() / (uint64_t) n_expert) {
429        err = "FileExpertSource: the expert count overflows";
430        return false;
431    }
432    const uint64_t blob_count = (uint64_t) n_layers * (uint64_t) n_expert;
433    if (blob_count > (uint64_t) std::numeric_limits<int64_t>::max() ||
434        (uint64_t) n_layers > (uint64_t) std::numeric_limits<size_t>::max()) {
435        err = "FileExpertSource: the expert count overflows";
436        return false;
437    }
438
439    std::vector<uint64_t> layer_offsets((size_t) n_layers), layer_blob_bytes((size_t) n_layers);
440    const uint64_t want = layout.total;
441    if (want == 0 || want > (uint64_t) std::numeric_limits<size_t>::max()) {
442        err = "FileExpertSource: the loaded expert layout has an invalid size";
443        return false;
444    }
445    if (!layout.native) {
446        if (blob_count > std::numeric_limits<uint64_t>::max() / (uint64_t) strata::kernels::cpu::BLOB) {
447            err = "FileExpertSource: the canonical expert size overflows";
448            return false;
449        }
450        const uint64_t canonical_size = blob_count * (uint64_t) strata::kernels::cpu::BLOB;
451        if (want != canonical_size) {
452            err = "FileExpertSource: the canonical expert layout has an inconsistent size";
453            return false;
454        }
455        const uint64_t bytes = (uint64_t) strata::kernels::cpu::BLOB;
456        const uint64_t layer_bytes = (uint64_t) n_expert * bytes;
457        for (int64_t layer = 0; layer < n_layers; ++layer) {
458            layer_offsets[(size_t) layer] = (uint64_t) layer * layer_bytes;
459            layer_blob_bytes[(size_t) layer] = bytes;
460        }
461    } else {
462        if (layout.offset.size() != (size_t) n_layers || layout.bytes.size() != (size_t) n_layers ||
463            layout.fmt.size() != (size_t) n_layers) {
464            err = "FileExpertSource: the native expert layout is incomplete";
465            return false;
466        }
467        uint64_t at = 0;
468        for (int64_t layer = 0; layer < n_layers; ++layer) {
469            const size_t i = (size_t) layer;
470            const uint64_t bytes = (uint64_t) layout.fmt[i].bytes;
471            if (layout.offset[i] != at || bytes == 0 || layout.bytes[i] != bytes ||
472                bytes > std::numeric_limits<uint64_t>::max() / (uint64_t) n_expert) {
473                err = "FileExpertSource: the native expert layout is invalid at layer " + std::to_string(layer);
474                return false;
475            }
476            const uint64_t layer_bytes = bytes * (uint64_t) n_expert;
477            if (at > want || layer_bytes > want - at) {
478                err = "FileExpertSource: the native expert layout exceeds its declared size at layer " +
479                      std::to_string(layer);
480                return false;
481            }
482            layer_offsets[i] = layout.offset[i];
483            layer_blob_bytes[i] = bytes;
484            at += layer_bytes;
485        }
486        if (at != want) {
487            err = "FileExpertSource: the native expert layout has an inconsistent size";
488            return false;
489        }
490    }
491    const std::string path = pack_dir + "/experts.bin";
492    if (layout.native && !gguf_.empty() && !std::filesystem::exists(path)) {
493        // CS-T: no experts.bin - the model's GGUF shards, read in place
494        blobs_ = (int64_t) blob_count;
495        n_layers_ = n_layers;
496        n_expert_ = n_expert;
497        layer_offsets_ = std::move(layer_offsets);
498        layer_blob_bytes_ = std::move(layer_blob_bytes);
499        if (!open_gguf(err)) { close(); return false; }
500        record_inputs(path, gguf_, layout, true);
501        return true;
502    }
503
504#if defined(_WIN32)
505    // UTF-8 -> UTF-16: the pack may live under a path with non-ASCII characters, and `CreateFileA` would
506    // silently mangle it into a file-not-found.
507    const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
508    std::vector<wchar_t> wpath((size_t) (wide > 0 ? wide : 1));
509    if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
510    // **`FILE_FLAG_RANDOM_ACCESS` WAS HERE AND IT COST 14x.**
511    //
512    // The design depends on the OS page cache holding the whole 34 GB expert set, because this machine has
513    // 64 GB of DDR5 and `L9` measured the CPU path at 44.14 GB/s from DRAM.  `FILE_FLAG_RANDOM_ACCESS` tells
514    // the cache manager the opposite: it disables read-ahead AND it lets the manager drop the pages again
515    // quickly, on the assumption that a large randomly-accessed file will not be re-read.  Measured, on
516    // `strata generate --max-new 24`: **1.93 GB/s** - disk speed, 344 ms/token, and it never warmed up over 25
517    // tokens, because the pages were being evicted as fast as they were faulted in.
518    //
519    // The correct flag is NO flag.  The access pattern IS random (10 of 512 experts per layer, a different 10
520    // each layer), but every byte read is read again on the next token, so retention is the whole game.
521    HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
522                           FILE_ATTRIBUTE_NORMAL, nullptr);
523    if (f == INVALID_HANDLE_VALUE) {
524        err = "FileExpertSource: cannot open " + path;
525        return false;
526    }
527    LARGE_INTEGER sz{};
528    if (!GetFileSizeEx(f, &sz)) {
529        CloseHandle(f);
530        err = "FileExpertSource: cannot size " + path;
531        return false;
532    }
533    if ((uint64_t) sz.QuadPart != want) {
534        char buf[400];
535        std::snprintf(buf, sizeof buf,
536                      "FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not "
537                      "the pack this geometry came from",
538                      path.c_str(), (unsigned long long) sz.QuadPart, (unsigned long long) want);
539        CloseHandle(f);
540        err = buf;
541        return false;
542    }
543    HANDLE m = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr);
544    if (m == nullptr) {
545        CloseHandle(f);
546        err = "FileExpertSource: CreateFileMapping failed on " + path;
547        return false;
548    }
549    void* view = MapViewOfFile(m, FILE_MAP_READ, 0, 0, 0);
550    if (view == nullptr) {
551        CloseHandle(m);
552        CloseHandle(f);
553        err = "FileExpertSource: MapViewOfFile failed on " + path;
554        return false;
555    }
556    file_ = f;
557    mapping_ = m;
558    base_ = (const uint8_t*) view;
559    paths_.assign(1, path);
560#else
561    const int fd = ::open(path.c_str(), O_RDONLY);
562    if (fd < 0) { err = "FileExpertSource: cannot open " + path; return false; }
563    struct stat st{};
564    if (fstat(fd, &st) != 0) { ::close(fd); err = "FileExpertSource: cannot stat " + path; return false; }
565    if (st.st_size < 0 || (uint64_t) st.st_size != want) {
566        char buf[400];
567        std::snprintf(buf, sizeof buf,
568                      "FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not "
569                      "the pack this geometry came from",
570                      path.c_str(), (unsigned long long) (st.st_size < 0 ? 0 : st.st_size),
571                      (unsigned long long) want);
572        ::close(fd);
573        err = buf;
574        return false;
575    }
576    void* view = mmap(nullptr, (size_t) want, PROT_READ, MAP_SHARED, fd, 0);
577    if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: mmap failed on " + path; return false; }
578    fd_ = fd;
579    base_ = (const uint8_t*) view;
580    paths_.assign(1, path);   // #286: open_direct opens it again with O_DIRECT
581#endif
582    blobs_ = (int64_t) blob_count;
583    n_layers_ = n_layers;
584    n_expert_ = n_expert;
585    mapped_bytes_ = want;
586    layer_offsets_ = std::move(layer_offsets);
587    layer_blob_bytes_ = std::move(layer_blob_bytes);
588    record_inputs(path, gguf_, layout, false);
589    return true;
590}
591
592void FileExpertSource::close() {
593    inputs_.clear();
594    if (complement_arena_ != nullptr) {
595        if (complement_pinned_ && !complement_partial_)(void) DPCT_CHECK_ERROR(
596            sycl::free(complement_arena_, dpct::get_in_order_queue()));
597        else {
598            /*
599            DPCT1027: The call to cudaHostUnregister was replaced with 0
600            because SYCL currently does not support registering of existing host
601            memory for use by device. Use USM to allocate memory for use by host
602            and device.
603            */
604            if (complement_partial_)(void) 0;
605            if (complement_locked_ > 0)
606                strata::platform::unlock_resident((uint8_t*) complement_arena_ + complement_lock_off_, complement_locked_);
607            std::free(complement_arena_);
608        }
609    }
610    if (xstage_ != nullptr) {
611        if (xstage_pinned_)(void)
612            DPCT_CHECK_ERROR(sycl::free(xstage_, dpct::get_in_order_queue()));
613        else std::free(xstage_);
614    }
615    xstage_ = nullptr;
616    xstage_pinned_ = false;
617    xstage_cap_ = 0;
618    xstage_blob_ = 0;
619    override_.clear();
620    staged_.clear();
621    exchange_storage_.clear();
622    exchanges_ = 0;
623    file_reads_.store(0);
624    complement_arena_ = nullptr;
625    complement_host_ = nullptr;
626    complement_device_ = nullptr;
627    complement_bytes_ = 0;
628    complement_offsets_.clear();
629    complement_pinned_ = false;
630    complement_partial_ = false;
631    complement_pin_limit_ = 0;
632    complement_lock_off_ = 0;
633    complement_ready_ = false;
634    complement_locked_ = 0;
635    complement_lent_slots_ = 0;
636    if (!maps_.empty()) {
637        for (Map& m : maps_) {
638#if defined(_WIN32)
639            if (m.base != nullptr) UnmapViewOfFile((LPCVOID) m.base);
640            if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping);
641            if (m.file != nullptr) CloseHandle((HANDLE) m.file);
642#else
643            if (m.base != nullptr) munmap((void*) m.base, (size_t) m.bytes);
644            if (m.fd >= 0) ::close(m.fd);
645#endif
646        }
647        maps_.clear();
648        base_ = nullptr;   // one of the views above
649    }
650    role_ptr_.clear();
651    role_bytes_.clear();
652    role_file_.clear();
653    paths_.clear();
654    for (void* h : direct_) close_direct(h);
655    direct_.clear();
656    {
657        std::lock_guard<std::mutex> lk(stage_mu_);
658        stage_buf_.clear();
659        stage_key_.clear();
660        stage_epoch_.clear();
661        stage_used_.clear();
662        stage_busy_.clear();
663        stage_of_.clear();
664        stage_blob_ = 0;
665        stage_seq_ = 0;
666        epoch_ = 0;
667        last_layer_ = -1;
668        stage_grew_ = false;
669    }
670    ram_reads_.store(0);
671    warm_stamp_.reset();
672    warm_hits_.store(0);
673    warm_count_.store(0);
674    file_read_bytes_.store(0);
675    file_blob_bytes_.store(0);
676    file_us_.store(0);
677#if defined(_WIN32)
678    if (base_ != nullptr) UnmapViewOfFile((LPCVOID) base_);
679    if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_);
680    if (file_ != nullptr) CloseHandle((HANDLE) file_);
681    mapping_ = nullptr;
682    file_ = nullptr;
683#else
684    if (base_ != nullptr) munmap((void*) base_, (size_t) mapped_bytes_);
685    if (fd_ >= 0) ::close(fd_);
686    fd_ = -1;
687#endif
688    base_ = nullptr;
689    blobs_ = 0;
690    n_layers_ = 0;
691    n_expert_ = 0;
692    mapped_bytes_ = 0;
693    layer_offsets_.clear();
694    layer_blob_bytes_.clear();
695    reads_ = 0;
696}
697
698
699bool ExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
700    const uint8_t* b = blob(layer, expert);
701    if (b == nullptr || dst == nullptr) return false;
702    std::memcpy(dst, b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(layer));
703    return true;
704}
705
706// ================================ CS-T: THE GGUF SHARDS IN PLACE ================================
707//
708// A native pack without experts.bin: every file native_experts.txt names is mapped (MapViewOfFile / mmap, no
709// flag - the same retention argument as experts.bin above), and an expert's blob [gate rows | up rows | down rows]
710// is three slices of three tensors, possibly in two shards (UD-Q4_K_XL's layer 11).  Nothing is read at open; a
711// blob is assembled when it is asked for (`blob`, into a small pool of buffers) or copied where it is needed
712// (`copy_blob`: the RAM copy, the prompt path's pinned stager buffers).
713bool FileExpertSource::open_gguf(std::string& err) {
714    const auto& lay = strata::kernels::cpu::expert_layout();
715    if (!check_experts_gguf(gguf_, lay, err)) { err = "FileExpertSource: " + err; return false; }
716    const size_t cut = gguf_.find_last_of("/\\");
717    const std::string dir = cut == std::string::npos ? std::string() : gguf_.substr(0, cut + 1);
718    std::map<std::string, size_t> index;
719    role_ptr_.assign((size_t) (3 * n_layers_), nullptr);
720    role_bytes_.assign((size_t) (3 * n_layers_), 0);
721    role_file_.assign((size_t) (3 * n_layers_), 0);
722    for (int64_t l = 0; l < n_layers_; ++l) {
723        const auto& fm = lay.fmt[(size_t) l];
724        const uint64_t per[3] = {fm.up_off, fm.up_off, lay.bytes[(size_t) l] - fm.down_off};
725        for (int r = 0; r < 3; ++r) {
726            const size_t i = (size_t) (3 * l + r);
727            const std::string path = lay.gguf_file.size() > i && !lay.gguf_file[i].empty() ? dir + lay.gguf_file[i]
728                                                                                            : gguf_;
729            auto it = index.find(path);
730            if (it == index.end()) {
731                Map m;
732#if defined(_WIN32)
733                const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
734                std::vector<wchar_t> wpath((size_t) (wide > 0 ? wide : 1));
735                if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
736                HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
737                                       FILE_ATTRIBUTE_NORMAL, nullptr);
738                LARGE_INTEGER sz{};
739                if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx(f, &sz)) {
740                    if (f != INVALID_HANDLE_VALUE) CloseHandle(f);
741                    err = "FileExpertSource: cannot open " + path;
742                    return false;
743                }
744                HANDLE mh = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr);
745                void* view = mh != nullptr ? MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0) : nullptr;
746                if (view == nullptr) {
747                    if (mh != nullptr) CloseHandle(mh);
748                    CloseHandle(f);
749                    err = "FileExpertSource: cannot map " + path;
750                    return false;
751                }
752                m.file = f;
753                m.mapping = mh;
754                m.bytes = (uint64_t) sz.QuadPart;
755                m.base = (const uint8_t*) view;
756#else
757                const int fd = ::open(path.c_str(), O_RDONLY);
758                struct stat st{};
759                if (fd < 0 || fstat(fd, &st) != 0 || st.st_size <= 0) {
760                    if (fd >= 0) ::close(fd);
761                    err = "FileExpertSource: cannot open " + path;
762                    return false;
763                }
764                void* view = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_SHARED, fd, 0);
765                if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: cannot map " + path; return false; }
766                m.fd = fd;
767                m.bytes = (uint64_t) st.st_size;
768                m.base = (const uint8_t*) view;
769#endif
770                maps_.push_back(m);
771                paths_.push_back(path);
772                it = index.emplace(path, maps_.size() - 1).first;
773            }
774            const Map& m = maps_[it->second];
775            role_file_[i] = (int) it->second;
776            const uint64_t at = lay.gguf_off[i], bytes = per[r] * (uint64_t) n_expert_;
777            if (at > m.bytes || bytes > m.bytes - at) {   // check_experts_gguf proved it; the mapping must agree
778                err = "FileExpertSource: an expert span runs past the end of " + path;
779                return false;
780            }
781            role_ptr_[i] = m.base + (size_t) at;
782            role_bytes_[i] = per[r];
783        }
784    }
785    base_ = maps_.front().base;       // "opened"; mapped_blob answers nullptr in this mode
786    warm_stamp_.reset(new std::atomic<uint32_t>[(size_t) (n_layers_ * n_expert_)]());
787    for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
788    return true;
789}
790
791bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const {
792    if (dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
793    if (!direct_.empty()) {   // #286: from the drive; a failed read falls back to the mapping below
794        const Fill f{0, layer, expert, dst};
795        if (read_direct(&f, 1)) return true;
796        direct_fallbacks_.fetch_add(1, std::memory_order_relaxed);
797    }
798    if (!role_ptr_.empty()) {
799        uint64_t at = 0;
800        for (int r = 0; r < 3; ++r) {
801            const size_t i = (size_t) (3 * layer + r);
802            const uint64_t per = role_bytes_[i];
803            std::memcpy(dst + at, role_ptr_[i] + (size_t) ((uint64_t) expert * per), (size_t) per);
804            at += per;
805        }
806        return true;
807    }
808    const uint8_t* b = mapped_blob(layer, expert);
809    if (b == nullptr) return false;
810    std::memcpy(dst, b, (size_t) layer_blob_bytes_[(size_t) layer]);
811    return true;
812}
813
814// A blob assembled from the three role slices.  The buffer of a (layer, expert) is reused for another only once
815// its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes
816// first, and never while it is being filled: the pool computes a layer's misses before it starts the next, and a
817// fill (the GPU cache at startup, an adaptive swap, a helper GPU) copies the blob right away.
818//
819// `claim_stage` finds or reserves the buffer of `key` (stage_mu_ held): true when the blob is already there (or
820// being filled by another thread - the caller then waits), false when the caller must fill buffer `v`.
821bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) {
822    constexpr uint64_t kStageSeq = 256;
823    const uint64_t seq = ++stage_seq_;
824    auto it = stage_of_.find(key);
825    fill = false;
826    if (it != stage_of_.end()) {
827        v = it->second;
828        stage_epoch_[v] = epoch_;
829        stage_used_[v] = seq;
830        return true;
831    }
832    v = stage_buf_.size();
833    uint64_t oldest = std::numeric_limits<uint64_t>::max();
834    for (size_t i = 0; i < stage_buf_.size(); ++i)
835        if (!stage_busy_[i] && (stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) &&
836            stage_used_[i] < oldest) {
837            oldest = stage_used_[i];
838            v = i;
839        }
840    if (v == stage_buf_.size()) {
841        stage_buf_.emplace_back(new (std::nothrow) uint8_t[(size_t) stage_blob_]);
842        if (!stage_buf_.back()) { stage_buf_.pop_back(); return false; }
843        stage_key_.push_back(-1);
844        stage_epoch_.push_back(0);
845        stage_used_.push_back(0);
846        stage_busy_.push_back(0);
847        if (stage_buf_.size() == 512 && !stage_grew_) {
848            stage_grew_ = true;
849            std::fprintf(stderr, "FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n",
850                         stage_buf_.size(), (double) stage_buf_.size() * (double) stage_blob_ / 1073741824.0);
851        }
852    } else {
853        stage_of_.erase(stage_key_[v]);
854    }
855    stage_key_[v] = key;
856    stage_epoch_[v] = epoch_;
857    stage_used_[v] = seq;
858    stage_busy_[v] = 1;
859    stage_of_[key] = v;
860    fill = true;
861    return false;
862}
863
864// Fills buffer `v` (reserved by claim_stage) outside the lock, then publishes it.
865bool FileExpertSource::fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst) {
866    const auto t0 = std::chrono::steady_clock::now();
867    const bool ok = copy_from_files(layer, expert, dst);
868    publish_stage(v, layer, ok, std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count());
869    return ok;
870}
871
872void FileExpertSource::publish_stage(size_t v, int64_t layer, bool ok, double us) {
873    file_us_.fetch_add((uint64_t) us, std::memory_order_relaxed);
874    if (ok) {
875        file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
876        file_blob_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
877    }
878    {
879        std::lock_guard<std::mutex> lk(stage_mu_);
880        stage_busy_[v] = 0;
881        if (!ok) {
882            stage_of_.erase(stage_key_[v]);
883            stage_key_[v] = -1;
884        }
885    }
886    stage_cv_.notify_all();
887}
888
889const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) {
890    const int64_t key = layer * n_expert_ + expert;
891    size_t v = 0;
892    bool fill = false;
893    uint8_t* dst = nullptr;
894    {
895        std::unique_lock<std::mutex> lk(stage_mu_);
896        const bool have = claim_stage(key, v, fill);
897        if (!have && !fill) return nullptr;
898        dst = stage_buf_[v].get();
899        if (have) {
900            // another thread (a prefetch, the adaptive tier) is filling it: wait for that
901            stage_cv_.wait(lk, [&] { return !stage_busy_[v] || stage_key_[v] != key; });
902            if (stage_key_[v] != key) return nullptr;   // its fill failed
903            return dst;
904        }
905    }
906    return fill_stage(v, layer, expert, dst) ? dst : nullptr;
907}
908
909void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n) {
910    if (!staged() || n <= 0 || layer < 0 || layer >= n_layers_) return;
911    std::vector<Fill> todo;
912    {
913        std::lock_guard<std::mutex> lk(stage_mu_);
914        for (int64_t i = 0; i < n; ++i) {
915            const int64_t e = experts[i];
916            if (e < 0 || e >= n_expert_) continue;
917            const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
918            if (complement_ready_ && resident_blob(index) != nullptr)
919                continue;                                     // in the RAM copy
920            if (!override_.empty() && override_[index] != nullptr) continue;
921            size_t v = 0;
922            bool fill = false;
923            if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) {
924                todo.push_back({v, layer, e, stage_buf_[v].get()});
925                if (warm_stamp_) {
926                    const uint32_t s = warm_stamp_[index].load(std::memory_order_relaxed);
927                    if (s != 0 && (uint64_t) s + 3 >= epoch_ + 1) warm_hits_.fetch_add(1, std::memory_order_relaxed);
928                }
929            }
930        }
931    }
932    fill_many(todo);
933}
934
935void FileExpertSource::prefetch_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) {
936    if (direct_.empty() || pairs == nullptr || n <= 0) return;   // unbuffered only: the mapped fill stays as it was
937    std::vector<Fill> todo;
938    {
939        std::lock_guard<std::mutex> lk(stage_mu_);
940        for (int64_t i = 0; i < std::min<int64_t>(n, 64); ++i) {
941            const int64_t l = pairs[i].first, e = pairs[i].second;
942            if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue;
943            size_t v = 0;
944            bool fill = false;
945            if (!claim_stage(l * n_expert_ + e, v, fill) && fill) todo.push_back({v, l, e, stage_buf_[v].get()});
946        }
947    }
948    fill_many(todo);
949}
950
951bool FileExpertSource::advise_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) const {
952    if (base_ == nullptr || !direct_.empty() || !strata::platform::read_ahead_enabled()) return false;
953    for (int64_t i = 0; pairs != nullptr && i < n; ++i) {
954        const int64_t l = pairs[i].first, e = pairs[i].second;
955        if (l < 0 || e < 0 || l >= n_layers_ || e >= n_expert_) continue;
956        if (role_ptr_.empty()) {   // experts.bin: the blob is one contiguous range
957            if (const uint8_t* b = mapped_blob(l, e)) strata::platform::advise_willneed(b, layer_blob_bytes_[(size_t) l]);
958            continue;
959        }
960        for (int r = 0; r < 3; ++r) {
961            const size_t k = (size_t) (3 * l + r);
962            strata::platform::advise_willneed(role_ptr_[k] + (size_t) ((uint64_t) e * role_bytes_[k]), role_bytes_[k]);
963        }
964    }
965    return true;
966}
967
968void FileExpertSource::fill_many(const std::vector<Fill>& todo) {
969    if (todo.empty()) return;
970    if (!direct_.empty()) {
971        // #286: overlapped batches - every role window of 16 blobs in flight at once; a big batch (the profile
972        // fill) on up to 4 threads, a decode layer's few misses on this one
973        std::atomic<size_t> next{0};
974        auto work = [&] {
975            for (size_t at; (at = next.fetch_add(16)) < todo.size();) {
976                const size_t k = std::min<size_t>(16, todo.size() - at);
977                const auto t0 = std::chrono::steady_clock::now();
978                const bool ok = read_direct(todo.data() + at, k);
979                const double us = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count();
980                for (size_t i = at; i < at + k; ++i) {
981                    const Fill& f = todo[i];
982                    // a failed batch: each blob again on its own (copy_from_files falls back to the mapping)
983                    if (ok) publish_stage(f.v, f.layer, true, us / (double) k);
984                    else (void) fill_stage(f.v, f.layer, f.e, f.dst);
985                }
986            }
987        };
988        const size_t nt = std::min<size_t>(4, (todo.size() + 15) / 16);
989        std::vector<std::thread> th;
990        for (size_t t = 1; t < nt; ++t) th.emplace_back(work);
991        work();
992        for (auto& t : th) t.join();
993        return;
994    }
995#if defined(_WIN32)
996    // One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large
997    // requests, all queued at once, where the copies' page faults would read a few clusters each.  The copies below
998    // then find the pages resident (or in flight).  STRATA_FETCH_PVM=0 is the A/B arm.
999    {
1000        using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
1001        static const Pvm pvm = [] {
1002            const char* v = std::getenv("STRATA_FETCH_PVM");
1003            if (v != nullptr && std::atoi(v) == 0) return (Pvm) nullptr;
1004            return (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory");
1005        }();
1006        if (pvm != nullptr) {
1007            std::vector<WIN32_MEMORY_RANGE_ENTRY> ranges;
1008            ranges.reserve(todo.size() * 3);
1009            for (const Fill& f : todo)
1010                for (int r = 0; r < 3; ++r) {
1011                    const size_t i = (size_t) (3 * f.layer + r);
1012                    ranges.push_back({(PVOID) (role_ptr_[i] + (size_t) ((uint64_t) f.e * role_bytes_[i])),
1013                                      (SIZE_T) role_bytes_[i]});
1014                }
1015            (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0);
1016        }
1017    }
1018#endif
1019    // the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full
1020    std::atomic<size_t> next{0};
1021    auto work = [&] {
1022        for (size_t i; (i = next.fetch_add(1)) < todo.size();)
1023            (void) fill_stage(todo[i].v, todo[i].layer, todo[i].e, todo[i].dst);
1024    };
1025    const size_t nt = std::min<size_t>(todo.size(), (size_t) fetch_threads_);
1026    std::vector<std::thread> th;
1027    for (size_t t = 1; t < nt; ++t) th.emplace_back(work);
1028    work();
1029    for (auto& t : th) t.join();
1030}
1031
1032uint64_t FileExpertSource::expert_bytes() const {
1033    uint64_t total = 0;
1034    for (uint64_t b : layer_blob_bytes_) total += b * (uint64_t) n_expert_;
1035    return total;
1036}
1037
1038bool FileExpertSource::open_direct(std::string& why) {
1039#if defined(_WIN32)
1040    for (const std::string& path : paths_) {
1041        const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
1042        std::vector<wchar_t> w((size_t) (wide > 0 ? wide : 1), L'\0');
1043        if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, w.data(), wide);
1044        HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
1045                               FILE_FLAG_NO_BUFFERING | FILE_FLAG_OVERLAPPED, nullptr);
1046        if (h == INVALID_HANDLE_VALUE) {
1047            why += "; cannot open " + path + " unbuffered (error " + std::to_string((unsigned long long) GetLastError()) +
1048                   "), read through the file cache";
1049            for (void* d : direct_) CloseHandle((HANDLE) d);
1050            direct_.clear();
1051            return false;
1052        }
1053        direct_.push_back(h);
1054    }
1055    if (role_ptr_.empty()) {   // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob
1056        std::lock_guard<std::mutex> lk(stage_mu_);
1057        for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
1058    }
1059    return true;
1060#elif defined(__linux__)
1061    // O_DIRECT: the reads bypass the page cache, as FILE_FLAG_NO_BUFFERING does (4 KiB-aligned windows, read_direct)
1062    for (const std::string& path : paths_) {
1063        const int fd = ::open(path.c_str(), O_RDONLY | O_DIRECT | O_CLOEXEC);
1064        if (fd < 0) {
1065            why += "; cannot open " + path + " with O_DIRECT (" + std::strerror(errno) + "), read through the file cache";
1066            for (void* d : direct_) close_direct(d);
1067            direct_.clear();
1068            return false;
1069        }
1070        direct_.push_back((void*) (intptr_t) fd);
1071    }
1072    if (role_ptr_.empty()) {   // experts.bin: blob() now assembles into the stage buffers, sized for the largest blob
1073        std::lock_guard<std::mutex> lk(stage_mu_);
1074        for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
1075    }
1076    return true;
1077#else
1078    (void) why;
1079    return false;
1080#endif
1081}
1082
1083bool FileExpertSource::set_unbuffered(uint64_t ram_bytes, std::string& why) {
1084#if defined(_WIN32) || defined(__linux__)
1085    if (base_ == nullptr || paths_.empty() || !direct_.empty()) {
1086        why = !direct_.empty() ? "already unbuffered" : "no expert files open";
1087        return !direct_.empty();
1088    }
1089    // #577: the file tier reads the experts outside the RAM copy, not every byte of the shards (dense weights, the
1090    // PLE table), and the copy holds at most every expert - the budget asked for can be more than that
1091    const uint64_t experts = expert_bytes();
1092    const uint64_t arena = std::min(ram_bytes, experts);
1093    if (!file_tier_unbuffered(paths_, arena, experts - arena, why)) return false;
1094    return open_direct(why);
1095#else
1096    (void) ram_bytes;
1097    why = "through the file cache (no unbuffered reads on this platform)";
1098    return false;
1099#endif
1100}
1101
1102bool FileExpertSource::recheck_unbuffered(std::string& why) {
1103#if defined(_WIN32) || defined(__linux__)
1104    if (const char* env = std::getenv("STRATA_UNBUFFERED_LOAD"); env != nullptr && env[0] != '\0') {
1105        why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
1106        return !direct_.empty();
1107    }
1108    if (base_ == nullptr || paths_.empty()) {
1109        why = "no expert files open";
1110        return false;
1111    }
1112    // #577: the RAM copy is built (and already out of the available RAM), so what the file cache would have to keep
1113    // is exactly the experts outside it - the GPU cache's (refilled after a prompt borrowed their slots) and the
1114    // ones neither holds
1115    const uint64_t experts = expert_bytes();
1116    const uint64_t read = experts > complement_bytes_ ? experts - complement_bytes_ : 0;
1117    std::string w;
1118    const bool ub = file_tier_unbuffered(paths_, 0, read, w);
1119    char head[96];
1120    std::snprintf(head, sizeof head, "re-checked with the RAM copy built (%.2f GiB): ",
1121                  (double) complement_bytes_ / 1073741824.0);
1122    why = head + w;
1123    if (ub == !direct_.empty()) return ub;
1124    if (ub) return open_direct(why);
1125    // through the file cache after all: the mapped reads take over (staged() stays true for the GGUF in place)
1126    for (void* d : direct_) close_direct(d);
1127    direct_.clear();
1128    return false;
1129#else
1130    why = "through the file cache (no unbuffered reads on this platform)";
1131    return false;
1132#endif
1133}
1134
1135bool FileExpertSource::read_direct(const Fill* fills, size_t n) const {
1136#if defined(_WIN32)
1137    // NTFS runs the unbuffered reads of a file one at a time while the file is mapped or cached anywhere (the engine
1138    // maps the GGUF shards for the token embedding and the PLE table): measured on a PCIe 5 drive, 512 KiB reads at
1139    // 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
1140    // windows less than kGap apart (the same role of nearby experts) are merged into requests of up to kMerge bytes.
1141    constexpr uint64_t kSector = 4096, kGap = 1ull << 20, kMerge = 32ull << 20;
1142    struct Window { int file; uint64_t a0, size, skip, n, at; uint8_t* dst; size_t req; uint64_t in_req; };
1143    struct Req { HANDLE h; uint64_t a0, size, pos; };
1144    // this thread's aligned buffer and events, kept for its next batch
1145    struct Scratch {
1146        uint8_t* buf = nullptr;
1147        size_t cap = 0;
1148        std::vector<HANDLE> ev;
1149        std::vector<OVERLAPPED> ov;
1150        std::vector<Window> win;
1151        std::vector<size_t> order;
1152        std::vector<Req> req;
1153        std::vector<DWORD> got;
1154        ~Scratch() {
1155            if (buf != nullptr) VirtualFree(buf, 0, MEM_RELEASE);
1156            for (HANDLE e : ev) CloseHandle(e);
1157        }
1158    };
1159    thread_local Scratch sc;
1160    sc.win.clear();
1161    for (size_t k = 0; k < n; ++k) {
1162        const Fill& f = fills[k];
1163        if (f.dst == nullptr || f.layer < 0 || f.e < 0 || f.layer >= n_layers_ || f.e >= n_expert_) return false;
1164        if (role_ptr_.empty()) {   // experts.bin: the blob is one contiguous range
1165            const uint64_t per = layer_blob_bytes_[(size_t) f.layer];
1166            const uint64_t off = layer_offsets_[(size_t) f.layer] + (uint64_t) f.e * per;
1167            const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
1168            sc.win.push_back({0, a0, a1 - a0, off - a0, per, 0, f.dst, 0, 0});
1169            continue;
1170        }
1171        uint64_t at = 0;
1172        for (int r = 0; r < 3; ++r) {
1173            const size_t i = (size_t) (3 * f.layer + r);
1174            const uint64_t per = role_bytes_[i];
1175            const Map& m = maps_[(size_t) role_file_[i]];
1176            const uint64_t off = (uint64_t) (role_ptr_[i] - m.base) + (uint64_t) f.e * per;
1177            const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
1178            sc.win.push_back({role_file_[i], a0, a1 - a0, off - a0, per, at, f.dst, 0, 0});
1179            at += per;
1180        }
1181    }
1182    sc.order.resize(sc.win.size());
1183    for (size_t w = 0; w < sc.win.size(); ++w) sc.order[w] = w;
1184    std::sort(sc.order.begin(), sc.order.end(), [&](size_t a, size_t b) {
1185        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;
1186    });
1187    sc.req.clear();
1188    uint64_t total = 0;
1189    int last_file = -1;
1190    for (size_t w : sc.order) {
1191        Window& x = sc.win[w];
1192        if (!sc.req.empty() && x.file == last_file) {
1193            Req& q = sc.req.back();
1194            const uint64_t end = q.a0 + q.size, xend = x.a0 + x.size;
1195            if (x.a0 <= end + kGap && std::max(end, xend) - q.a0 <= kMerge) {
1196                if (xend > end) {
1197                    total += xend - end;
1198                    q.size = xend - q.a0;
1199                }
1200                x.req = sc.req.size() - 1;
1201                x.in_req = x.a0 - q.a0;
1202                continue;
1203            }
1204        }
1205        sc.req.push_back({(HANDLE) direct_[(size_t) x.file], x.a0, x.size, total});
1206        total += x.size;
1207        last_file = x.file;
1208        x.req = sc.req.size() - 1;
1209        x.in_req = 0;
1210    }
1211    if (total > sc.cap) {
1212        if (sc.buf != nullptr) VirtualFree(sc.buf, 0, MEM_RELEASE);
1213        sc.cap = (size_t) ((total + (1u << 20) - 1) >> 20 << 20);
1214        sc.buf = (uint8_t*) VirtualAlloc(nullptr, sc.cap, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
1215        if (sc.buf == nullptr) { sc.cap = 0; return false; }
1216    }
1217    while (sc.ev.size() < sc.req.size()) {
1218        HANDLE e = CreateEventW(nullptr, TRUE, FALSE, nullptr);
1219        if (e == nullptr) return false;
1220        sc.ev.push_back(e);
1221    }
1222    sc.ov.assign(sc.req.size(), OVERLAPPED{});
1223    // every request in flight before the first wait: the drive sees the whole batch as one queue
1224    size_t issued = 0;
1225    bool ok = true;
1226    for (size_t q = 0; q < sc.req.size(); ++q) {
1227        const Req& r = sc.req[q];
1228        OVERLAPPED& o = sc.ov[q];
1229        o.Offset = (DWORD) r.a0;
1230        o.OffsetHigh = (DWORD) (r.a0 >> 32);
1231        o.hEvent = sc.ev[q];
1232        if (!ReadFile(r.h, sc.buf + r.pos, (DWORD) r.size, nullptr, &o) && GetLastError() != ERROR_IO_PENDING) {
1233            ok = false;
1234            break;
1235        }
1236        ++issued;
1237    }
1238    std::vector<DWORD>& got = sc.got;
1239    got.assign(sc.req.size(), 0);
1240    for (size_t q = 0; q < issued; ++q)
1241        if (!GetOverlappedResult(sc.req[q].h, &sc.ov[q], &got[q], TRUE)) ok = false;
1242    if (!ok || issued < sc.req.size()) return false;
1243    for (const Window& x : sc.win) {
1244        // a request may run past the end of the file: only the role's own bytes have to arrive
1245        if ((uint64_t) got[x.req] < x.in_req + x.skip + x.n) return false;
1246        std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n);
1247    }
1248    return true;
1249#elif defined(__linux__)
1250    // Linux: O_DIRECT descriptors (open_direct) and the kernel's asynchronous reads - every window of the batch is
1251    // queued with one io_submit before the first wait, so the drive sees the batch as one queue, as the overlapped
1252    // ReadFiles above do.  No NTFS here: windows are merged only where they touch (the 4 KiB rounding of adjacent
1253    // slices, consecutive experts of a role), never across a gap that would be read for nothing.  Each thread has its
1254    // own context and aligned buffer, kept for its next batch, so concurrent batches never see each other's events.
1255    constexpr uint64_t kSector = 4096, kMerge = 32ull << 20;
1256    constexpr long kDepth = 256;   // requests in flight per thread; a larger batch is read in waves of this many
1257    struct Window { int file; uint64_t a0, size, skip, n, at; uint8_t* dst; size_t req; uint64_t in_req; };
1258    struct Req { int fd; uint64_t a0, size, pos; };
1259    struct Scratch {
1260        uint8_t* buf = nullptr;
1261        size_t cap = 0;
1262        aio_context_t ctx = 0;
1263        std::vector<Window> win;
1264        std::vector<size_t> order;
1265        std::vector<Req> req;
1266        std::vector<int64_t> got;
1267        std::vector<iocb> cb;
1268        std::vector<iocb*> cbp;
1269        std::vector<io_event> ev;
1270        ~Scratch() {
1271            std::free(buf);
1272            if (ctx != 0) (void) syscall(SYS_io_destroy, ctx);
1273        }
1274    };
1275    thread_local Scratch sc;
1276    if (sc.ctx == 0 && syscall(SYS_io_setup, kDepth, &sc.ctx) != 0) {
1277        sc.ctx = 0;
1278        return false;   // no AIO (a seccomp profile, aio-max-nr): the caller falls back to the mapped copy
1279    }
1280    sc.win.clear();
1281    for (size_t k = 0; k < n; ++k) {
1282        const Fill& f = fills[k];
1283        if (f.dst == nullptr || f.layer < 0 || f.e < 0 || f.layer >= n_layers_ || f.e >= n_expert_) return false;
1284        if (role_ptr_.empty()) {   // experts.bin: the blob is one contiguous range
1285            const uint64_t per = layer_blob_bytes_[(size_t) f.layer];
1286            const uint64_t off = layer_offsets_[(size_t) f.layer] + (uint64_t) f.e * per;
1287            const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
1288            sc.win.push_back({0, a0, a1 - a0, off - a0, per, 0, f.dst, 0, 0});
1289            continue;
1290        }
1291        uint64_t at = 0;
1292        for (int r = 0; r < 3; ++r) {
1293            const size_t i = (size_t) (3 * f.layer + r);
1294            const uint64_t per = role_bytes_[i];
1295            const Map& m = maps_[(size_t) role_file_[i]];
1296            const uint64_t off = (uint64_t) (role_ptr_[i] - m.base) + (uint64_t) f.e * per;
1297            const uint64_t a0 = off / kSector * kSector, a1 = (off + per + kSector - 1) / kSector * kSector;
1298            sc.win.push_back({role_file_[i], a0, a1 - a0, off - a0, per, at, f.dst, 0, 0});
1299            at += per;
1300        }
1301    }
1302    sc.order.resize(sc.win.size());
1303    for (size_t w = 0; w < sc.win.size(); ++w) sc.order[w] = w;
1304    std::sort(sc.order.begin(), sc.order.end(), [&](size_t a, size_t b) {
1305        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;
1306    });
1307    sc.req.clear();
1308    uint64_t total = 0;
1309    int last_file = -1;
1310    for (size_t w : sc.order) {
1311        Window& x = sc.win[w];
1312        if (!sc.req.empty() && x.file == last_file) {
1313            Req& q = sc.req.back();
1314            const uint64_t end = q.a0 + q.size, xend = x.a0 + x.size;
1315            if (x.a0 <= end && std::max(end, xend) - q.a0 <= kMerge) {
1316                if (xend > end) {
1317                    total += xend - end;
1318                    q.size = xend - q.a0;
1319                }
1320                x.req = sc.req.size() - 1;
1321                x.in_req = x.a0 - q.a0;
1322                continue;
1323            }
1324        }
1325        sc.req.push_back({(int) (intptr_t) direct_[(size_t) x.file], x.a0, x.size, total});
1326        total += x.size;
1327        last_file = x.file;
1328        x.req = sc.req.size() - 1;
1329        x.in_req = 0;
1330    }
1331    if (total > sc.cap) {
1332        std::free(sc.buf);
1333        sc.cap = (size_t) ((total + (1u << 20) - 1) >> 20 << 20);
1334        void* p = nullptr;
1335        sc.buf = posix_memalign(&p, (size_t) kSector, sc.cap) == 0 ? (uint8_t*) p : nullptr;
1336        if (sc.buf == nullptr) { sc.cap = 0; return false; }
1337    }
1338    sc.got.assign(sc.req.size(), -1);
1339    sc.cb.resize(std::min<size_t>(sc.req.size(), (size_t) kDepth));
1340    sc.cbp.resize(sc.cb.size());
1341    sc.ev.resize(sc.cb.size());
1342    bool ok = true;
1343    for (size_t w0 = 0; ok && w0 < sc.req.size(); w0 += (size_t) kDepth) {
1344        const size_t wn = std::min<size_t>((size_t) kDepth, sc.req.size() - w0);
1345        for (size_t j = 0; j < wn; ++j) {
1346            const Req& r = sc.req[w0 + j];
1347            iocb& c = sc.cb[j];
1348            std::memset(&c, 0, sizeof c);
1349            c.aio_lio_opcode = IOCB_CMD_PREAD;
1350            c.aio_fildes = (uint32_t) r.fd;
1351            c.aio_buf = (uint64_t) (uintptr_t) (sc.buf + r.pos);
1352            c.aio_nbytes = r.size;
1353            c.aio_offset = (int64_t) r.a0;
1354            c.aio_data = (uint64_t) (w0 + j);
1355            sc.cbp[j] = &c;
1356        }
1357        // every request of the wave queued; a refused submit ends the batch once what was queued has completed
1358        // (the kernel still writes into the buffer until then)
1359        size_t queued = 0;
1360        while (queued < wn) {
1361            const long r = syscall(SYS_io_submit, sc.ctx, (long) (wn - queued), sc.cbp.data() + queued);
1362            if (r > 0) { queued += (size_t) r; continue; }
1363            if (r < 0 && errno == EINTR) continue;
1364            ok = false;
1365            break;
1366        }
1367        for (size_t done = 0; done < queued;) {
1368            const long r = syscall(SYS_io_getevents, sc.ctx, 1L, (long) (queued - done), sc.ev.data(), nullptr);
1369            if (r < 0) {
1370                if (errno == EINTR) continue;
1371                // the context is in an unknown state: drop it (io_destroy waits for what is still in flight)
1372                (void) syscall(SYS_io_destroy, sc.ctx);
1373                sc.ctx = 0;
1374                return false;
1375            }
1376            for (long j = 0; j < r; ++j) {
1377                const io_event& e = sc.ev[(size_t) j];
1378                sc.got[(size_t) e.data] = e.res;
1379                if (e.res < 0) ok = false;
1380            }
1381            done += (size_t) r;
1382        }
1383    }
1384    if (!ok) return false;
1385    for (const Window& x : sc.win) {
1386        // a request may run past the end of the file: only the role's own bytes have to arrive
1387        if (sc.got[x.req] < 0 || (uint64_t) sc.got[x.req] < x.in_req + x.skip + x.n) return false;
1388        std::memcpy(x.dst + x.at, sc.buf + sc.req[x.req].pos + x.in_req + x.skip, (size_t) x.n);
1389    }
1390    return true;
1391#else
1392    (void) fills; (void) n;
1393    return false;
1394#endif
1395}
1396
1397void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) {
1398    if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return;
1399    uint32_t stamp;
1400    {
1401        std::lock_guard<std::mutex> lk(stage_mu_);
1402        stamp = (uint32_t) epoch_ + 1;
1403    }
1404#if defined(_WIN32)
1405    using Pvm = BOOL(WINAPI*)(HANDLE, ULONG_PTR, PWIN32_MEMORY_RANGE_ENTRY, ULONG);
1406    static const Pvm pvm = (Pvm) (void*) GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "PrefetchVirtualMemory");
1407    std::vector<WIN32_MEMORY_RANGE_ENTRY> ranges;
1408#endif
1409    for (int64_t j = 0; j < n; ++j) {
1410        const int64_t e = experts[j];
1411        if (e < 0 || e >= n_expert_) continue;
1412        const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
1413        if (complement_ready_ && resident_blob(index) != nullptr)
1414            continue;                                                    // in the RAM copy
1415        if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed);
1416        warm_count_.fetch_add(1, std::memory_order_relaxed);
1417        for (int r = 0; r < 3; ++r) {
1418            const size_t i = (size_t) (3 * layer + r);
1419            const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) e * role_bytes_[i]);
1420#if defined(_WIN32)
1421            ranges.push_back({(PVOID) p, (SIZE_T) role_bytes_[i]});
1422#else
1423            const uintptr_t pg = 4096, a = (uintptr_t) p & ~(pg - 1);
1424            (void) madvise((void*) a, (size_t) ((uintptr_t) p + role_bytes_[i] - a), MADV_WILLNEED);
1425#endif
1426        }
1427    }
1428#if defined(_WIN32)
1429    if (pvm != nullptr && !ranges.empty()) (void) pvm(GetCurrentProcess(), (ULONG_PTR) ranges.size(), ranges.data(), 0);
1430#endif
1431}
1432
1433RouterLookahead::~RouterLookahead() {
1434    {
1435        std::lock_guard<std::mutex> lk(mu_);
1436        quit_ = true;
1437    }
1438    cv_.notify_all();
1439    if (thread_.joinable()) thread_.join();
1440}
1441
1442bool RouterLookahead::start(std::vector<std::vector<uint16_t>> routers, int64_t n_embd, int64_t n_expert, int k,
1443                            ExpertSource* src, std::string& err) {
1444    if (src == nullptr || !src->warms()) { err = "RouterLookahead: the expert source does not warm"; return false; }
1445    if (n_embd % 8 != 0) { err = "RouterLookahead: n_embd is not a multiple of 8"; return false; }
1446    for (const auto& r : routers)
1447        if (r.size() != (size_t) (n_embd * n_expert)) { err = "RouterLookahead: a router of another shape"; return false; }
1448    routers_ = std::move(routers);
1449    n_embd_ = n_embd;
1450    n_expert_ = n_expert;
1451    k_ = k < 1 ? 1 : k > (int) n_expert ? (int) n_expert : k;
1452    src_ = src;
1453    x_.assign((size_t) (8 * n_embd), 0.f);
1454    thread_ = std::thread([this] { run(); });
1455    return true;
1456}
1457
1458void RouterLookahead::submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res) {
1459    if (layer + 1 >= (int64_t) routers_.size() || n_tok <= 0 || x == nullptr) return;
1460    {
1461        std::lock_guard<std::mutex> lk(mu_);
1462        if (busy_ || pending_) { skipped_.fetch_add(1, std::memory_order_relaxed); return; }
1463        n_tok_ = std::min<int64_t>(n_tok, 8);
1464        std::memcpy(x_.data(), x, (size_t) (n_tok_ * n_embd_) * sizeof(float));
1465        layer_ = layer + 1;
1466        host_res_ = host_res;
1467        pending_ = true;
1468    }
1469    cv_.notify_one();
1470}
1471
1472void RouterLookahead::run() {
1473    std::vector<float> logits((size_t) (8 * n_expert_));
1474    std::vector<int32_t> order((size_t) n_expert_);
1475    std::vector<int64_t> want;
1476    for (;;) {
1477        int64_t layer, nt;
1478        const int32_t* host_res;
1479        {
1480            std::unique_lock<std::mutex> lk(mu_);
1481            cv_.wait(lk, [&] { return quit_ || pending_; });
1482            if (quit_) return;
1483            pending_ = false;
1484            busy_ = true;
1485            layer = layer_;
1486            nt = n_tok_;
1487            host_res = host_res_;
1488        }
1489        const auto t0 = std::chrono::steady_clock::now();
1490        want.clear();
1491        // The router dot is AVX2 (kq_avx2.cpp); a CPU without AVX2 (the experimental older-CPU builds) takes the AVX1
1492        // one (kq_avx1.cpp) or, without AVX, the same sums in plain C++.  From the Strata_Dirigo fork (rwkeyes): an
1493        // AVX-only Xeon E5-2687W died here (vpmovzxwd) on its first request.  An estimate only (which experts to
1494        // prefetch); the order of the additions differs between the three, the output does not depend on it.
1495        if (strata::kernels::cpu::cpu_avx2_ok()) {
1496            strata::kernels::cpu::bf16_rows_dot_multi(routers_[(size_t) layer].data(), (int) n_expert_, (int) n_embd_,
1497                                                      x_.data(), (int) nt, logits.data());
1498        } else if (strata::kernels::cpu::cpu_avx1_ok()) {
1499            strata::kernels::cpu::bf16_rows_dot_multi_avx1(routers_[(size_t) layer].data(), (int) n_expert_,
1500                                                           (int) n_embd_, x_.data(), (int) nt, logits.data());
1501        } else {
1502            // a mul and an add, not std::fma: without an FMA instruction that is a libm call per element (74x
1503            // slower on a Xeon E5-2665, measured by the fork)
1504            const uint16_t* rw = routers_[(size_t) layer].data();
1505            for (int64_t r = 0; r < n_expert_; ++r) {
1506                const uint16_t* wr = rw + (size_t) r * (size_t) n_embd_;
1507                for (int64_t t = 0; t < nt; ++t) {
1508                    const float* xr = x_.data() + (size_t) t * (size_t) n_embd_;
1509                    float acc = 0.0f;
1510                    for (int64_t c = 0; c < n_embd_; ++c) {
1511                        const uint32_t bits = (uint32_t) wr[c] << 16;
1512                        float wf;
1513                        std::memcpy(&wf, &bits, sizeof wf);
1514                        acc += wf * xr[c];
1515                    }
1516                    logits[(size_t) t * (size_t) n_expert_ + (size_t) r] = acc;
1517                }
1518            }
1519        }
1520        for (int64_t t = 0; t < nt; ++t) {
1521            const float* lt = logits.data() + (size_t) (t * n_expert_);
1522            for (int64_t e = 0; e < n_expert_; ++e) order[(size_t) e] = (int32_t) e;
1523            std::partial_sort(order.begin(), order.begin() + k_, order.end(),
1524                              [&](int32_t a, int32_t b) { return lt[(size_t) a] > lt[(size_t) b]; });
1525            for (int j = 0; j < k_; ++j) {
1526                const int64_t e = order[(size_t) j];
1527                if (host_res != nullptr && host_res[(size_t) (layer * n_expert_ + e)] >= 0) continue;   // on the GPU
1528                if (std::find(want.begin(), want.end(), e) == want.end()) want.push_back(e);
1529            }
1530        }
1531        src_->warm(layer, want.data(), (int64_t) want.size());
1532        predicted_.fetch_add((int64_t) want.size(), std::memory_order_relaxed);
1533        busy_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
1534                           std::memory_order_relaxed);
1535        {
1536            std::lock_guard<std::mutex> lk(mu_);
1537            busy_ = false;
1538        }
1539    }
1540}
1541
1542void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) {
1543    (void) ids;
1544    (void) k;
1545    if (!staged()) return;
1546    std::lock_guard<std::mutex> lk(stage_mu_);
1547    if (layer != last_layer_) {
1548        ++epoch_;
1549        last_layer_ = layer;
1550    }
1551}
1552
1553bool FileExpertSource::transient(int64_t layer, int64_t expert) const {
1554    if (!staged() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
1555    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
1556    if (complement_ready_ && resident_blob(index) != nullptr)
1557        return false;
1558    return override_.empty() || override_[index] == nullptr;
1559}
1560
1561bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
1562    if (base_ == nullptr || dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_)
1563        return false;
1564    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
1565    const uint64_t bytes = layer_blob_bytes_[(size_t) layer];
1566    if (complement_ready_) {
1567        const uint8_t* held =
1568            resident_blob(index);
1569        if (held == nullptr && !override_.empty()) held = override_[index];
1570        if (held != nullptr) {
1571            std::memcpy(dst, held, (size_t) bytes);
1572            return true;
1573        }
1574    }
1575    const auto t0 = std::chrono::steady_clock::now();
1576    if (!copy_from_files(layer, expert, dst)) return false;
1577    file_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
1578                       std::memory_order_relaxed);
1579    file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed);
1580    return true;
1581}
1582
1583const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) const {
1584    if (!role_ptr_.empty()) return nullptr;   // the GGUF in place: no contiguous blob in any file
1585    if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr;
1586    const size_t i = (size_t) layer;
1587    if (i >= layer_offsets_.size() || i >= layer_blob_bytes_.size()) return nullptr;
1588    const uint64_t blob_bytes = layer_blob_bytes_[i];
1589    if (blob_bytes == 0 || (uint64_t) expert > std::numeric_limits<uint64_t>::max() / blob_bytes) return nullptr;
1590    const uint64_t expert_offset = (uint64_t) expert * blob_bytes;
1591    const uint64_t layer_offset = layer_offsets_[i];
1592    if (layer_offset > mapped_bytes_ || expert_offset > mapped_bytes_ - layer_offset) return nullptr;
1593    const uint64_t offset = layer_offset + expert_offset;
1594    if (blob_bytes > mapped_bytes_ - offset) return nullptr;
1595    return base_ + (size_t) offset;
1596}
1597
1598uint64_t FileExpertSource::release(int64_t layer, int64_t expert) {
1599#if defined(_WIN32)
1600    static const bool enabled = [] {
1601        const char* v = std::getenv("STRATA_FILE_RELEASE");
1602        return v != nullptr && std::strcmp(v, "1") == 0;
1603    }();
1604    if (!enabled || base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_)
1605        return 0;
1606    static const uint64_t page = [] {
1607        SYSTEM_INFO info{};
1608        GetSystemInfo(&info);
1609        return (uint64_t) info.dwPageSize;
1610    }();
1611    // These read-only file views are not CUDA-registered. blob() may instead return pinned RAM or an exchange
1612    // buffer, so resolve the file spans directly. A shared boundary page stays for the neighboring expert.
1613    auto trim = [&](const uint8_t* p, uint64_t bytes) -> uint64_t {
1614        const uint64_t misalignment = (uintptr_t) p % page;
1615        const uint64_t skip = misalignment == 0 ? 0 : page - misalignment;
1616        if (bytes <= skip) return 0;
1617        const uint64_t whole = (bytes - skip) / page * page;
1618        if (whole == 0) return 0;
1619        SetLastError(ERROR_SUCCESS);
1620        if (!VirtualUnlock((LPVOID) (p + (size_t) skip), (SIZE_T) whole)) {
1621            const DWORD error = GetLastError();
1622            // VirtualUnlock trims an unlocked range and reports FALSE / ERROR_NOT_LOCKED for that success.
1623            if (error != ERROR_NOT_LOCKED) {
1624                std::fprintf(stderr, "FileExpertSource: cannot trim mapped pages for layer %lld expert %lld "
1625                                     "(%llu bytes, Windows error %lu)\n",
1626                             (long long) layer, (long long) expert, (unsigned long long) whole,
1627                             (unsigned long) error);
1628                std::fflush(stderr);
1629                return 0;
1630            }
1631        }
1632        return whole;   // bytes advised, not a measurement of physical RAM reclaimed
1633    };
1634    if (role_ptr_.empty()) {
1635        const uint8_t* p = mapped_blob(layer, expert);
1636        return p == nullptr ? 0 : trim(p, layer_blob_bytes_[(size_t) layer]);
1637    }
1638    uint64_t bytes = 0;
1639    for (int r = 0; r < 3; ++r) {
1640        const size_t i = (size_t) (3 * layer + r);
1641        bytes += trim(role_ptr_[i] + (size_t) ((uint64_t) expert * role_bytes_[i]), role_bytes_[i]);
1642    }
1643    return bytes;
1644#else
1645    (void) layer; (void) expert;
1646    return 0;
1647#endif
1648}
1649
1650bool FileExpertSource::pin_cache_complement(
1651    const ExpertCache &cache, std::string &err, bool pin,
1652    const std::vector<std::pair<int32_t, int32_t>> &additional_gpu_pairs,
1653    int64_t lend_from_slot, uint64_t headroom_bytes, uint64_t budget_bytes,
1654    const std::vector<std::pair<int32_t, int32_t>> *rank) try {
1655    err.clear();
1656    const auto pin_t0 = std::chrono::steady_clock::now();
1657    if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; }
1658    if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; }
1659    if (!cache.valid()) { err = "FileExpertSource: the GPU expert cache is not open"; return false; }
1660    if (cache.fills() != cache.resident()) {
1661        err = "FileExpertSource: the GPU expert cache is not fully filled";
1662        return false;
1663    }
1664    const dpct::err0 sync =
1665        DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw());
1666    /*
1667    DPCT1000: Error handling if-stmt was detected but could not be
1668    rewritten.
1669    */
1670    if (sync != 0) {
1671        /*
1672        DPCT1009: SYCL reports errors using exceptions and does not use
1673        error codes. Please replace the "get_error_string_dummy(...)" with a
1674        real error-handling function.
1675        */
1676        /*
1677        DPCT1001: The statement could not be removed.
1678        */
1679        err = std::string("FileExpertSource: GPU expert cache is not ready: ") +
1680              dpct::get_error_string_dummy(sync);
1681        /*
1682        DPCT1010: SYCL uses exceptions to report errors and does not use
1683        the error codes. The cudaGetLastError function call was replaced with 0.
1684        You need to rewrite this code.
1685        */
1686        (void)0;
1687        return false;
1688    }
1689
1690    // The GPU cache's experts, and the bytes each slot's expert takes here (for the lend region below).
1691    const int64_t n_slots = cache.slots();
1692    std::vector<std::pair<int32_t, int32_t>> primary_gpu_pairs;
1693    std::vector<int32_t> pair_slot;
1694    std::vector<uint64_t> slot_bytes((size_t) std::max<int64_t>(n_slots, 0), 0);
1695    primary_gpu_pairs.reserve((size_t) cache.resident());
1696    pair_slot.reserve((size_t) cache.resident());
1697    for (int64_t layer = 0; layer < n_layers_; ++layer) {
1698        for (int64_t expert = 0; expert < n_expert_; ++expert) {
1699            const int32_t slot = cache.slot_of(layer, expert);
1700            if (slot == kNotResident) continue;
1701            primary_gpu_pairs.emplace_back((int32_t) layer, (int32_t) expert);
1702            pair_slot.push_back(slot);
1703            if (slot >= 0 && slot < n_slots) slot_bytes[(size_t) slot] = layer_blob_bytes_[(size_t) layer];
1704        }
1705    }
1706    std::vector<uint64_t> offsets;
1707    uint64_t bytes = 0;
1708    if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, primary_gpu_pairs,
1709                                            additional_gpu_pairs, offsets, bytes, err)) return false;
1710#if defined(_WIN32)
1711    // #467: the GPU cache's pre-fill touched its experts through the mapping (~19 GiB on a 24 GB card), and Windows
1712    // counts those file pages in this process's working set, not as available: a 32 GB PC read 0.44 GiB here
1713    // (20.7 GiB before the start).  Trimmed, they move to the standby list (still cached, counted as available).
1714    // Resident mode only: nothing else calls this function.  Locked/pinned pages stay; the rest fault back softly.
1715    {
1716        uint64_t before = 0, after = 0;
1717        const bool read_before = available_memory_bytes(before);
1718        (void) SetProcessWorkingSetSize(GetCurrentProcess(), (SIZE_T) -1, (SIZE_T) -1);
1719        if (read_before && available_memory_bytes(after))
1720            std::fprintf(stderr, "FileExpertSource: available RAM %.2f GiB, %.2f GiB after the mapped experts left the "
1721                                 "process working set (#467)\n",
1722                         (double) before / 1073741824.0, (double) after / 1073741824.0);
1723    }
1724#endif
1725    const bool what_fits = budget_bytes == kResidentWhatFits;   // #467: the soft mode's second try
1726    uint64_t budget_physical = 0;   // #403: reuse the memory snapshot a budget was sized from
1727    uint64_t budget_commit = std::numeric_limits<uint64_t>::max();
1728    if (budget_bytes > 0) {
1729        // CS-T: a RAM budget.  The complement's experts in `rank` order (the expert profile, hottest first) while
1730        // they fit, the rest left on the mapped files; Windows commit capacity also limits the allocation (#730).
1731        uint64_t physical = 0;
1732        if (!available_memory_bytes(physical, &budget_commit)) {
1733            err = "FileExpertSource: cannot determine available memory for --resident-budget-gib";
1734            return false;
1735        }
1736        budget_physical = physical;
1737        const uint64_t available = std::min(physical, budget_commit);
1738        const char* limit = budget_commit < physical ? "commit" : "RAM";
1739        const uint64_t clamped = detail::clamp_resident_budget(budget_bytes, physical, budget_commit, headroom_bytes);
1740        if (budget_bytes > clamped) {
1741            // #403: 256 MiB under the room, so the engine's own allocations after this reading still leave the
1742            // headroom (a budget clamped to exactly the room failed the safety check below on a reading a few MB
1743            // lower).  An unclamped budget is unchanged.
1744            if (what_fits)
1745                std::fprintf(stderr, "FileExpertSource: room for the complement: %.2f GiB (%.2f GiB available %s "
1746                                     "minus %.0f GiB headroom and a 0.25 GiB margin)\n",
1747                             (double) clamped / 1073741824.0, (double) available / 1073741824.0, limit,
1748                             (double) headroom_bytes / 1073741824.0);
1749            else
1750                std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f exceeds available %s "
1751                                     "(%.2f GiB minus %.0f GiB headroom and a 0.25 GiB margin): %.2f GiB\n",
1752                             (double) budget_bytes / 1073741824.0, limit, (double) available / 1073741824.0,
1753                             (double) headroom_bytes / 1073741824.0, (double) clamped / 1073741824.0);
1754            budget_bytes = clamped;
1755        }
1756        std::vector<uint64_t> ranked(offsets.size(), kNoComplement);
1757        uint64_t at = 0;
1758        int64_t held = 0;
1759        if (rank != nullptr)
1760            for (const auto& pr : *rank) {
1761                if (pr.first < 0 || pr.second < 0 || pr.first >= n_layers_ || pr.second >= n_expert_) continue;
1762                const size_t i = (size_t) pr.first * (size_t) n_expert_ + (size_t) pr.second;
1763                if (offsets[i] == kNoComplement || ranked[i] != kNoComplement) continue;   // on a GPU, or twice
1764                const uint64_t b = layer_blob_bytes_[(size_t) pr.first];
1765                if (b > budget_bytes - at) continue;
1766                ranked[i] = at;
1767                at += b;
1768                ++held;
1769            }
1770        if (what_fits && held == 0) {   // #467: nothing to keep - the caller's plain mmap fallback, not an empty copy
1771            err = "FileExpertSource: available memory cannot hold any expert of the complement";
1772            return false;
1773        }
1774        std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does "
1775                             "not hold, by profile rank; the rest are read from the files\n",
1776                     (double) budget_bytes / 1073741824.0, (long long) held, (double) bytes / 1073741824.0);
1777        offsets.swap(ranked);
1778        bytes = at;
1779        lend_from_slot = -1;
1780    }
1781
1782    const bool lend = lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty();
1783    uint64_t budget = std::numeric_limits<uint64_t>::max();
1784    if (bytes > 0 || lend) {
1785        // #403: with a budget, the reading it was sized from - a second reading a few MB lower (the engine's own
1786        // allocations, the file cache) failed a budget the first one had clamped.  (A budget turns `lend` off.)
1787        uint64_t physical = budget_physical;
1788        uint64_t commit = budget_commit;
1789        if (physical == 0 && !available_memory_bytes(physical, &commit)) {
1790            err = "FileExpertSource: cannot determine available memory for the resident-memory safety check";
1791            return false;
1792        }
1793        const uint64_t available = std::min(physical, commit);
1794        budget = available > headroom_bytes ? available - headroom_bytes : 0;
1795        if (bytes > budget) {
1796            char message[320];
1797            std::snprintf(message, sizeof message,
1798                          "FileExpertSource: resident complement %.2f GiB exceeds available %s (%.2f GiB) minus the "
1799                          "%.0f GiB safety headroom",
1800                          (double) bytes / 1073741824.0, commit < physical ? "commit" : "RAM",
1801                          (double) available / 1073741824.0, (double) headroom_bytes / 1073741824.0);
1802            err = message;
1803            return false;
1804        }
1805    }
1806    // The prompt path's lend region: its slots' experts are streamed from here during a prompt and copied back into
1807    // their slots after it, so the ones that fit are kept here too (from the last slot down: a short prompt lends
1808    // only the last few).  The rest keep the mapped-file fallback.
1809    int64_t keep_from = n_slots;
1810    if (lend) {
1811        keep_from = detail::choose_resident_keep_from(slot_bytes, bytes, budget, lend_from_slot);
1812        if (keep_from < 0) keep_from = n_slots;
1813        if (keep_from < n_slots) {
1814            std::vector<std::pair<int32_t, int32_t>> core;
1815            core.reserve(primary_gpu_pairs.size());
1816            for (size_t i = 0; i < primary_gpu_pairs.size(); ++i)
1817                if (pair_slot[i] < keep_from) core.push_back(primary_gpu_pairs[i]);
1818            if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, core,
1819                                                    additional_gpu_pairs, offsets, bytes, err)) return false;
1820        }
1821    }
1822
1823    void* arena = nullptr;
1824    const uint8_t* host = nullptr;
1825    const uint8_t* device = nullptr;
1826    bool pinned_ok = false;
1827    uint64_t locked = 0;
1828    uint64_t partial_pin = 0;   ///< CS-T: a registered prefix of a locked arena
1829    uint64_t lock_off = 0;      ///< where the working-set lock starts (after the registered prefix)
1830    std::string note;
1831    auto release = [&]() {
1832        try {
1833    if (arena == nullptr) return;
1834        if (pinned_ok)(void)
1835            DPCT_CHECK_ERROR(sycl::free(arena, dpct::get_in_order_queue()));
1836        else {
1837            /*
1838            DPCT1027: The call to cudaHostUnregister was replaced with 0
1839            because SYCL currently does not support registering of existing host
1840            memory for use by device. Use USM to allocate memory for use by host
1841            and device.
1842            */
1843            if (partial_pin > 0)(void) 0;
1844            if (locked > 0) strata::platform::unlock_resident((uint8_t*) arena + lock_off, locked);
1845            std::free(arena);
1846        }
1847        arena = nullptr;
1848    }
1849    catch (sycl::exception const &exc) {
1850      std::cerr << exc.what() << "Exception caught at file:" << __FILE__
1851                << ", line:" << __LINE__ << std::endl;
1852      std::exit(1);
1853    }
1854    };
1855    if (bytes > 0) {
1856        std::fprintf(stderr, "FileExpertSource: allocating %.2f GiB %s cache complement\n",
1857                     (double) bytes / 1073741824.0, pin ? "page-locked" : "pageable resident");
1858        log_complement_memory("before complement allocation", bytes);
1859        std::fflush(stderr);
1860        if (pin) {
1861            const dpct::err0 allocated = DPCT_CHECK_ERROR(
1862                arena = (void *)sycl::malloc_host((size_t)bytes,
1863                                                  dpct::get_in_order_queue()));
1864            if (allocated == 0) {
1865                void* alias = nullptr;
1866                const dpct::err0 aliased =
1867                    DPCT_CHECK_ERROR(alias = (void *)arena);
1868                if (aliased == 0 && alias != nullptr) {
1869                    device = (const uint8_t*) alias;
1870                    pinned_ok = true;
1871                    note = "page-locked and mapped";
1872                } else {
1873                    /*
1874                    DPCT1009: SYCL reports errors using exceptions and does
1875                    not use error codes. Please replace the
1876                    "get_error_string_dummy(...)" with a real error-handling
1877                    function.
1878                    */
1879                    note = std::string("no device alias (") +
1880                           dpct::get_error_string_dummy(aliased) + ")";
1881                    /*
1882                    DPCT1010: SYCL uses exceptions to report errors and
1883                    does not use the error codes. The cudaGetLastError function
1884                    call was replaced with 0. You need to rewrite this code.
1885                    */
1886                    (void)0;
1887                    (void)DPCT_CHECK_ERROR(
1888                        sycl::free(arena, dpct::get_in_order_queue()));
1889                    arena = nullptr;
1890                }
1891            } else {
1892                // Refused (the driver's page-locked limit): the same bytes in ordinary memory, locked in the working
1893                // set instead, as the arena does - resident either way, only copied by the CPU instead of by DMA.
1894                /*
1895                DPCT1009: SYCL reports errors using exceptions and does not
1896                use error codes. Please replace the
1897                "get_error_string_dummy(...)" with a real error-handling
1898                function.
1899                */
1900                note = std::string("page-locking refused (") +
1901                       dpct::get_error_string_dummy(allocated) + ")";
1902                /*
1903                DPCT1010: SYCL uses exceptions to report errors and does
1904                not use the error codes. The cudaGetLastError function call was
1905                replaced with 0. You need to rewrite this code.
1906                */
1907                (void)0;
1908                arena = nullptr;
1909            }
1910        }
1911        if (arena == nullptr) {
1912            if (!note.empty()) {
1913                std::fprintf(stderr, "FileExpertSource: %s; trying pageable memory\n", note.c_str());
1914                log_complement_memory("before pageable allocation", bytes);
1915                std::fflush(stderr);
1916            }
1917            errno = 0;
1918            arena = std::malloc((size_t) bytes);
1919            if (arena == nullptr) {
1920                const int allocation_errno = errno;
1921                err = "FileExpertSource: pageable resident complement allocation failed (malloc errno " +
1922                      std::to_string(allocation_errno) + ": " + std::strerror(allocation_errno) + ")";
1923                if (!note.empty()) err += "; " + note;
1924                log_complement_memory("after pageable allocation failure", bytes);
1925                return false;
1926            }
1927            if (pin) {
1928                // CS-T, a RAM budget: its bytes are in profile order, hottest first, so the driver is asked to
1929                // register the largest prefix it takes (from the cap down in 2 GiB steps).  Those experts can be
1930                // read by the GPU over PCIe (--pcie-frac) and copied by DMA; only the rest is locked in the working
1931                // set (the registered prefix is page-locked by the driver already - locking it twice made the next
1932                // device allocation fail).
1933                // opt-in (STRATA_PARTIAL_PIN=1): on the RTX 5070 PC the GPU's PCIe share of the misses measured no
1934                // faster than the CPU computing them (7.30 / 7.44 tok/s with 24 / 16 GiB registered against 7.05-7.74
1935                // unpinned at a 40 GiB budget), and registering adds startup time and driver memory pressure
1936                static const bool partial_on = [] {
1937                    const char* v = std::getenv("STRATA_PARTIAL_PIN");
1938                    return v != nullptr && std::atoi(v) != 0;
1939                }();
1940                // at most STRATA_PARTIAL_PIN_GIB (default 24): registering 30 GiB of a 40 GiB arena left the driver
1941                // unable to page-lock the prompt path's small buffers afterwards (RTX 5070, WDDM)
1942                static const uint64_t pin_cap = [] {
1943                    const char* v = std::getenv("STRATA_PARTIAL_PIN_GIB");
1944                    return (uint64_t) ((v != nullptr && std::atof(v) > 0 ? std::atof(v) : 24.0) * 1073741824.0);
1945                }();
1946                if (budget_bytes > 0 && partial_on) {
1947                    const uint64_t step = 2ull << 30;
1948                    for (uint64_t want = std::min(bytes, pin_cap); want >= step; want = want > step ? want - step : 0) {
1949                        // cut at an expert boundary: a blob that started inside the registered range and ran past it
1950                        // would be taken as page-locked by a cudaMemcpyAsync and refused ("adaptive refill failed")
1951                        uint64_t w = want;
1952                        for (size_t i = 0; i < offsets.size(); ++i) {
1953                            if (offsets[i] == kNoComplement) continue;
1954                            const uint64_t b = layer_blob_bytes_[i / (size_t) n_expert_];
1955                            if (offsets[i] < want && offsets[i] + b > want) { w = offsets[i]; break; }
1956                        }
1957                        if (w == 0) break;
1958                        /*
1959                        DPCT1027: The call to cudaHostRegister was replaced
1960                        with 0 because SYCL currently does not support
1961                        registering of existing host memory for use by device.
1962                        Use USM to allocate memory for use by host and device.
1963                        */
1964                        if (0 == 0) {
1965                            void* alias = nullptr;
1966                            if (DPCT_CHECK_ERROR(alias = (void *)arena) == 0 &&
1967                                alias != nullptr) {
1968                                device = (const uint8_t*) alias;
1969                                partial_pin = w;
1970                            } else {
1971                                /*
1972                                DPCT1010: SYCL uses exceptions to report
1973                                errors and does not use the error codes. The
1974                                cudaGetLastError function call was replaced with
1975                                0. You need to rewrite this code.
1976                                */
1977                                (void)0;
1978                                /*
1979                                DPCT1027: The call to cudaHostUnregister
1980                                was replaced with 0 because SYCL currently does
1981                                not support registering of existing host memory
1982                                for use by device. Use USM to allocate memory
1983                                for use by host and device.
1984                                */
1985                                (void)0;
1986                            }
1987                            break;
1988                        }
1989                        /*
1990                        DPCT1010: SYCL uses exceptions to report errors and
1991                        does not use the error codes. The cudaGetLastError
1992                        function call was replaced with 0. You need to rewrite
1993                        this code.
1994                        */
1995                        (void)0;
1996                        if (want <= step) break;
1997                    }
1998                    char msg[160];
1999                    std::snprintf(msg, sizeof msg, "%.2f GiB of it registered for the GPU (the hottest)",
2000                                  (double) partial_pin / 1073741824.0);
2001                    note += std::string("; ") + msg;
2002                }
2003                lock_off = partial_pin;
2004                const strata::platform::LockResult lr =
2005                    strata::platform::lock_resident((uint8_t*) arena + lock_off, bytes - lock_off);
2006                locked = lr.locked_bytes;
2007                note += (note.empty() ? "" : "; ") + lr.note;
2008            }
2009        }
2010        host = (const uint8_t*) arena;
2011    }
2012
2013    // Copied layer by layer on a few threads: the page faults of the mapped file are the cost, and they overlap.
2014#if !defined(_WIN32)
2015    const long page_size = sysconf(_SC_PAGESIZE);
2016    if (page_size <= 0) {
2017        err = "FileExpertSource: cannot determine page size for mapped-page release";
2018        release();
2019        return false;
2020    }
2021#endif
2022    std::atomic<int64_t> next_layer{0}, layers_done{0};
2023    std::atomic<uint64_t> copied{0};
2024    std::atomic<bool> failed{false};
2025    std::mutex fail_mu;
2026    const auto copy_t0 = std::chrono::steady_clock::now();
2027    std::string fail_msg;
2028    auto fail = [&](const std::string& m) {
2029        std::lock_guard<std::mutex> lock(fail_mu);
2030        if (fail_msg.empty()) fail_msg = m;
2031        failed.store(true);
2032    };
2033    auto worker = [&]() {
2034        for (;;) {
2035            const int64_t layer = next_layer.fetch_add(1);
2036            if (layer >= n_layers_ || failed.load()) return;
2037            const uint64_t blob_bytes = layer_blob_bytes_[(size_t) layer];
2038            std::vector<Fill> batch;   // #286, unbuffered: 32 blobs' reads in flight at once, merged where near
2039            auto flush = [&]() {
2040                if (batch.empty()) return true;
2041                bool ok = read_direct(batch.data(), batch.size());
2042                for (size_t i = 0; !ok && i < batch.size(); ++i)
2043                    if (!copy_from_files(batch[i].layer, batch[i].e, batch[i].dst)) return false;
2044                copied.fetch_add(blob_bytes * (uint64_t) batch.size());
2045                batch.clear();
2046                return true;
2047            };
2048            if (direct_.empty()) {   // mapped reads: ask for the layer's blobs before copying them
2049                std::vector<std::pair<int32_t, int32_t>> ahead;
2050                for (int64_t expert = 0; expert < n_expert_; ++expert)
2051                    if (offsets[(size_t) layer * (size_t) n_expert_ + (size_t) expert] != kNoComplement)
2052                        ahead.emplace_back((int32_t) layer, (int32_t) expert);
2053                (void) advise_pairs(ahead.data(), (int64_t) ahead.size());
2054            }
2055            for (int64_t expert = 0; expert < n_expert_; ++expert) {
2056                const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
2057                const uint64_t offset = offsets[index];
2058                if (offset == kNoComplement) continue;
2059                if (offset > bytes || blob_bytes > bytes - offset) {
2060                    fail("FileExpertSource: invalid blob bounds while building the cache complement");
2061                    return;
2062                }
2063                uint8_t* dst = (uint8_t*) host + (size_t) offset;
2064                if (!direct_.empty()) {
2065                    batch.push_back({0, layer, expert, dst});
2066                    if (batch.size() == 32 && !flush()) {
2067                        fail("FileExpertSource: an expert could not be read while building the cache complement");
2068                        return;
2069                    }
2070                    continue;
2071                }
2072                if (!copy_from_files(layer, expert, dst)) {
2073                    fail("FileExpertSource: invalid blob bounds while building the cache complement");
2074                    return;
2075                }
2076                copied.fetch_add(blob_bytes);
2077            }
2078            if (!flush()) {
2079                fail("FileExpertSource: an expert could not be read while building the cache complement");
2080                return;
2081            }
2082#if !defined(_WIN32)
2083            if (role_ptr_.empty()) {   // experts.bin; the GGUF in place leaves its pages to the OS
2084            const uint64_t layer_offset = layer_offsets_[(size_t) layer];
2085            const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_;
2086            const uint64_t layer_end = layer_offset + layer_bytes;
2087            const uint64_t page = (uint64_t) page_size;
2088            const uint64_t advice_start = layer_offset - layer_offset % page;
2089            const uint64_t end_remainder = layer_end % page;
2090            const uint64_t extra = end_remainder == 0 ? 0 : page - end_remainder;
2091            const uint64_t advice_end = extra > mapped_bytes_ - layer_end ? mapped_bytes_ : layer_end + extra;
2092            if (advice_end > advice_start &&
2093                madvise((void*) (base_ + (size_t) advice_start), (size_t) (advice_end - advice_start), MADV_DONTNEED) != 0) {
2094                fail("FileExpertSource: madvise could not release mapped expert layer " + std::to_string(layer));
2095                return;
2096            }
2097            if (posix_fadvise(fd_, (off_t) layer_offset, (off_t) layer_bytes, POSIX_FADV_DONTNEED) != 0) {
2098                fail("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer));
2099                return;
2100            }
2101            }
2102#endif
2103            const int64_t done = layers_done.fetch_add(1) + 1;
2104            if (done % 8 == 0 || done == n_layers_)
2105                std::fprintf(stderr, "FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB, %.0f s)\n",
2106                             (long long) done, (long long) n_layers_, (double) copied.load() / 1073741824.0,
2107                             std::chrono::duration<double>(std::chrono::steady_clock::now() - copy_t0).count());
2108        }
2109    };
2110    {
2111        const int threads = (int) std::max<int64_t>(1, std::min<int64_t>(6, n_layers_));
2112        std::vector<std::thread> pool;
2113        for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
2114        worker();
2115        for (auto& t : pool) t.join();
2116    }
2117    std::fflush(stderr);
2118    if (failed.load()) {
2119        err = fail_msg;
2120        release();
2121        return false;
2122    }
2123#if defined(_WIN32)
2124    // The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the
2125    // standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED).
2126    if (maps_.empty()) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_);
2127    for (const Map& m : maps_) (void) VirtualUnlock((LPVOID) m.base, (SIZE_T) m.bytes);
2128#endif
2129
2130    complement_arena_ = arena;
2131    complement_host_ = host;
2132    complement_device_ = device;
2133    complement_bytes_ = bytes;
2134    complement_offsets_ = std::move(offsets);
2135    complement_pinned_ = (pinned_ok || partial_pin > 0) && bytes > 0;
2136    complement_pin_limit_ = pinned_ok ? bytes : partial_pin;
2137    complement_partial_ = !pinned_ok && partial_pin > 0;
2138    complement_locked_ = locked;
2139    complement_lock_off_ = lock_off;
2140    complement_lent_slots_ = lend ? n_slots - keep_from : 0;
2141    complement_ready_ = true;
2142    std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB in %.0f s%s%s\n",
2143                 complement_pinned_ ? "mapped pinned" : pin ? "locked resident" : "pageable resident",
2144                 (double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0,
2145                 std::chrono::duration<double>(std::chrono::steady_clock::now() - pin_t0).count(),
2146                 note.empty() ? "" : "; ", note.c_str());
2147    if (lend)
2148        std::fprintf(stderr, "FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM "
2149                             "too%s\n", (long long) complement_lent_slots_, (long long) (n_slots - lend_from_slot),
2150                     complement_lent_slots_ < n_slots - lend_from_slot
2151                         ? " (the others are read from the file when lent: not enough RAM for them)" : "");
2152    if (lend && complement_lent_slots_ < n_slots - lend_from_slot) {
2153        // #1389: below full coverage the uncovered experts are read from the pack during a long prompt (a 74K prompt
2154        // routes through nearly all experts, so the misses repeat). The reporter measured 18% uncovered = -26% prompt
2155        // speed on a gfx1100; short prompts barely touch them. A warning, not a refusal.
2156        const long long lendable = (long long) (n_slots - lend_from_slot);
2157        const long long missing = lendable - (long long) complement_lent_slots_;
2158        std::fprintf(stderr, "FileExpertSource: WARNING: %lld of %lld lendable slots (%.0f%%) will read their experts from the pack "
2159                             "during a long prompt; expect a slower prompt read on 50K+ token prompts (one measurement: 18%% uncovered "
2160                             "cost 26%%). Free RAM or lower STRATA_RESIDENT_HEADROOM_GIB (now the RAM left free at start) and restart; "
2161                             "the line above should read N of N.\n", missing, lendable, 100.0 * (double) missing / (double) std::max<long long>(1, lendable));
2162    }
2163    if (!additional_gpu_pairs.empty()) {
2164        std::fprintf(stderr, "FileExpertSource: %zu verified additional-GPU experts remain on the mmap fallback\n",
2165                     additional_gpu_pairs.size());
2166    }
2167    std::fflush(stderr);
2168    return true;
2169}
2170catch (sycl::exception const &exc) {
2171  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2172            << ", line:" << __LINE__ << std::endl;
2173  std::exit(1);
2174}
2175
2176const uint8_t* FileExpertSource::resident_blob(size_t index) const {
2177    if (exchange_storage_.active()) return exchange_storage_.resident(index).host;
2178    return detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);
2179}
2180
2181bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const {
2182    if (!complement_ready_ || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
2183    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
2184    return resident_blob(index) != nullptr;
2185}
2186
2187bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) {
2188    err.clear();
2189    if (n <= xstage_cap_) return true;
2190    if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; }
2191    if (exchange_storage_.active()) {
2192        err = "FileExpertSource: reserve maximum exchange capacity before enabling rotation";
2193        return false; // the original exchange allocation can now contain live resident experts
2194    }
2195    uint64_t blob = 0;
2196    for (const uint64_t b : layer_blob_bytes_) blob = std::max(blob, b);
2197    if (blob == 0 || n <= 0) { err = "FileExpertSource: no expert geometry for the exchange buffers"; return false; }
2198    if (xstage_ != nullptr) {
2199        if (xstage_pinned_)(void)
2200            DPCT_CHECK_ERROR(sycl::free(xstage_, dpct::get_in_order_queue()));
2201        else std::free(xstage_);
2202        xstage_ = nullptr;
2203        xstage_cap_ = 0;
2204    }
2205    if ((uint64_t)n > std::numeric_limits<size_t>::max() / blob) {
2206        err = "FileExpertSource: exchange allocation size overflow"; return false;
2207    }
2208    const char* rotate_env = std::getenv("STRATA_EXCHANGE_ROTATE");
2209    const bool requested = rotate_env && std::strcmp(rotate_env, "1") == 0;
2210    const bool uniform = std::all_of(layer_blob_bytes_.begin(), layer_blob_bytes_.end(),
2211                                    [blob](uint64_t b) { return b == blob; });
2212    const bool eligible = requested && uniform && complement_pinned_ && !complement_partial_ &&
2213                          complement_host_ && complement_device_ && complement_bytes_ > 0;
2214    const size_t total = (size_t) n * (size_t) blob;
2215    void* p = nullptr;
2216    /*
2217    DPCT1048: The original value cudaHostAllocMapped is not meaningful in the
2218    migrated code and was removed or replaced with 0. You may need to check the
2219    migrated code.
2220    */
2221    /*
2222    DPCT1048: The original value cudaHostAllocDefault is not meaningful in the
2223    migrated code and was removed or replaced with 0. You may need to check the
2224    migrated code.
2225    */
2226    if (DPCT_CHECK_ERROR(p = (void *)sycl::malloc_host(
2227                             total, dpct::get_in_order_queue())) == 0 &&
2228        p != nullptr) {
2229        xstage_pinned_ = true;
2230    } else {
2231        /*
2232        DPCT1010: SYCL uses exceptions to report errors and does not use
2233        the error codes. The cudaGetLastError function call was replaced with 0.
2234        You need to rewrite this code.
2235        */
2236        (void)0;
2237        p = std::malloc(total);
2238        xstage_pinned_ = false;
2239        if (p == nullptr) { err = "FileExpertSource: cannot allocate the exchange buffers"; return false; }
2240    }
2241    xstage_ = (uint8_t*) p;
2242    xstage_cap_ = n;
2243    xstage_blob_ = blob;
2244    if (requested) {
2245        std::string reason = "requires equal-size expert blocks and a fully mapped/pinned RAM complement";
2246        void* device = nullptr;
2247        if (eligible && xstage_pinned_ &&
2248            DPCT_CHECK_ERROR(device = (void *)p) == 0 && device) {
2249            try {
2250                if (exchange_storage_.initialize(complement_offsets_, (uint8_t*)complement_host_, complement_device_,
2251                        complement_bytes_, xstage_, (const uint8_t*)device, (size_t)n, (size_t)blob, reason)) {
2252                    std::fprintf(stderr, "FileExpertSource: exchange buffer rotation enabled: %lld buffers, %llu bytes each; no host commit memcpy\n",
2253                                 (long long)n, (unsigned long long)blob);
2254                }
2255            } catch (const std::bad_alloc&) { reason = "buffer metadata allocation failed"; }
2256        } else if (eligible) {
2257            /*
2258            DPCT1010: SYCL uses exceptions to report errors and does not use
2259            the error codes. The cudaGetLastError function call was replaced
2260            with 0. You need to rewrite this code.
2261            */
2262            (void)0;
2263            reason = "exchange buffers could not be pinned and mapped";
2264        }
2265        if (!exchange_storage_.active())
2266            std::fprintf(stderr, "FileExpertSource: exchange rotation unavailable; retaining copy path: %s\n", reason.c_str());
2267    }
2268    return true;
2269}
2270
2271uint8_t* FileExpertSource::exchange_buffer(int64_t q) const {
2272    if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr;
2273    if (exchange_storage_.active()) return exchange_storage_.spare((size_t)q).host;
2274    return xstage_ + (size_t) q * (size_t) xstage_blob_;
2275}
2276
2277bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q) {
2278    if (out < 0 || out >= n_expert_ || !has_resident(layer, in) || has_resident(layer, out) ||
2279        exchange_buffer(q) == nullptr) return false;
2280    const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in;
2281    const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out;
2282    if (override_.empty()) override_.assign((size_t) blobs_, nullptr);
2283    if (override_[i_out] != nullptr) return false;
2284    for (const Exchange& x : staged_)
2285        if (x.in == i_in || x.q == q) return false;
2286    override_[i_out] = exchange_buffer(q);
2287    staged_.push_back({i_in, i_out, q, layer_blob_bytes_[(size_t) layer]});
2288    return true;
2289}
2290
2291int64_t FileExpertSource::commit_exchanges() {
2292    int64_t n = 0;
2293    for (const Exchange& x : staged_) {
2294        const uint8_t* src = override_[x.out];
2295        if (exchange_storage_.active()) {
2296            if (!exchange_storage_.commit(x.in, x.out, (size_t)x.q, src, (size_t)x.bytes)) {
2297                // Admitting the GPU swap after a failed RAM ownership update would lose an expert.
2298                std::fprintf(stderr, "FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n");
2299                std::abort();
2300            }
2301            ++n;
2302            override_[x.out] = nullptr;
2303            continue;
2304        }
2305        const uint64_t at = complement_offsets_[x.in];
2306        if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&
2307            complement_host_ != nullptr) {
2308            std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes);
2309            if (detail::exchange_cache_complement(complement_offsets_, x.in, x.out)) ++n;
2310        }
2311        override_[x.out] = nullptr;
2312    }
2313    staged_.clear();
2314    exchanges_ += n;
2315    return n;
2316}
2317
2318void FileExpertSource::commit_copies() {
2319    if (exchange_storage_.active()) return;   // STRATA_EXCHANGE_ROTATE: ownership moves in commit_flip, nothing to copy
2320    for (const Exchange& x : staged_) {
2321        const uint8_t* src = override_.empty() ? nullptr : override_[x.out];
2322        const uint64_t at = complement_offsets_[x.in];
2323        if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&
2324            complement_host_ != nullptr)
2325            std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes);
2326    }
2327}
2328
2329int64_t FileExpertSource::commit_flip() {
2330    int64_t n = 0;
2331    for (const Exchange& x : staged_) {
2332        const uint8_t* src = override_[x.out];
2333        if (exchange_storage_.active()) {   // STRATA_EXCHANGE_ROTATE: the same ownership transfer as commit_exchanges
2334            if (!exchange_storage_.commit(x.in, x.out, (size_t) x.q, src, (size_t) x.bytes)) {
2335                std::fprintf(stderr, "FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n");
2336                std::abort();
2337            }
2338            ++n;
2339            override_[x.out] = nullptr;
2340            continue;
2341        }
2342        const uint64_t at = complement_offsets_[x.in];
2343        // the same test as commit_copies: an exchange whose bytes were copied is the one that flips
2344        if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&
2345            complement_host_ != nullptr && detail::exchange_cache_complement(complement_offsets_, x.in, x.out))
2346            ++n;
2347        override_[x.out] = nullptr;
2348    }
2349    staged_.clear();
2350    exchanges_ += n;
2351    return n;
2352}
2353
2354const uint8_t* FileExpertSource::resident_blob(int64_t layer, int64_t expert) const {
2355    if (!complement_ready_ || complement_host_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ ||
2356        expert >= n_expert_) return nullptr;
2357    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
2358    if (index >= complement_offsets_.size()) return nullptr;
2359    return resident_blob(index);   // through the rotation's ownership table when STRATA_EXCHANGE_ROTATE is on
2360}
2361
2362const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {
2363    if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr;
2364    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
2365    const uint8_t* result = nullptr;
2366    bool from_files = true;
2367    if (complement_ready_) {
2368        result = resident_blob(index);
2369        if (result != nullptr) {
2370            ram_reads_.fetch_add(1, std::memory_order_relaxed);
2371            from_files = false;
2372        } else if (!override_.empty() && override_[index] != nullptr) {
2373            result = override_[index];
2374            from_files = false;
2375        }
2376    }
2377    if (from_files) {
2378        if (staged()) {
2379            result = staged_blob(layer, expert);          // counts its bytes
2380        } else {
2381            result = mapped_blob(layer, expert);
2382            if (result != nullptr)
2383                file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
2384        }
2385        if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed);
2386    }
2387    if (result != nullptr) ++reads_;
2388    return result;
2389}
2390
2391bool FileExpertSource::pinned(int64_t layer, int64_t expert) const {
2392    if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 ||
2393        layer >= n_layers_ || expert >= n_expert_) return false;
2394    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
2395    if (exchange_storage_.active()) return exchange_storage_.resident(index).host != nullptr;
2396    if (index >= complement_offsets_.size() || complement_offsets_[index] == kNoComplement) return false;
2397    // a partial pin (CS-T): only the registered prefix
2398    return !complement_partial_ ||
2399           complement_offsets_[index] + layer_blob_bytes_[(size_t) layer] <= complement_pin_limit_;
2400}
2401
2402const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const {
2403    if (!pinned(layer, expert) || complement_device_ == nullptr) return nullptr;
2404    const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
2405    if (exchange_storage_.active()) return exchange_storage_.resident(index).device;
2406    return complement_device_ + (size_t) complement_offsets_[index];
2407}
2408
2409bool FileExpertSource::pcie_layer(int64_t layer) const {
2410    if (complement_ready_ && complement_pinned_ && complement_device_ != nullptr)
2411        return layer >= 0 && layer < n_layers_;
2412    return device_alias(layer, 0) != nullptr;
2413}
2414
2415// ================================ THE ADAPTER ================================
2416
2417void expert_pool_dispatch(void* user, const float* x_f, const int32_t* ids, const float* weights, int64_t n_embd,
2418                          int64_t k, float* out) {
2419    (void) weights;   // clause 2: `moe_combine` applies it on the device.  Not an oversight.
2420    ExpertDispatch& d = *(ExpertDispatch*) user;
2421    if (d.failed) return;   // a previous layer already failed; do not make it worse
2422
2423    using namespace strata::kernels::cpu;
2424    // Clause 3: the blob's internal offsets are compile-time constants, so a mismatched geometry does not
2425    // produce a wrong answer - it produces a walk off the end of the blob into the next expert's bytes, which
2426    // is finite and plausible.  Refuse, name the number, and let the driver report it.
2427    if (n_embd != H) {
2428        d.failed = true;
2429        d.fail = "the expert kernel is compiled for a 2560-wide activation";
2430        d.fail_layer = d.layers;
2431        return;
2432    }
2433    if (expert_layout().native) {
2434        // plan v0.3 P6: a native pack runs its experts in verify windows only (the driver guarantees it)
2435        d.failed = true;
2436        d.fail = "the single-token expert path does not take a native (IQ) pack";
2437        d.fail_layer = d.layers;
2438        return;
2439    }
2440    if (k > (int64_t) d.jobs.size()) d.jobs.resize((size_t) k);
2441
2442    d.src->begin_layer(d.layers, ids, k);
2443
2444    // Clause 1: rebuilt from `x_f` on EVERY call.  `x_f` is mapped pinned memory whose address never changes,
2445    // so anything cached against it would be layer 0's activation reused 48 times.
2446    act_quant_q8_1(x_f, H, d.act);
2447
2448    // ---- R4.2c: THE POOL'S HALF OF THE SPLIT.  **IT DOES NOT DECIDE ANYTHING - `Launch` ALREADY DID.**
2449    //
2450    // The decision has to be made on THIS layer's ids, and `Launch` is the only callback that runs before the
2451    // pool while the ids are known (the doorbell publishes them when the ring fires).  So `expert_hit_run`
2452    // decides, and this consumes `d.is_hit`.  The first version decided here instead, which meant `Launch`
2453    // computed the PREVIOUS layer's experts into this layer's rows: C1 went from mean KL 9.69e-02 to 1.03e+00.
2454    //
2455    // `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a hit.
2456    const bool graph_hits = d.host_res != nullptr;
2457    const bool use_hits = graph_hits || (d.hits_ready() && d.decided);
2458    int64_t njobs = 0;
2459
2460    if (d.remote_count > 0) {
2461        int32_t kind[32];
2462        if (k > 32) {
2463            d.failed = true; d.fail = "remote experts: routing width exceeds 32"; return;
2464        }
2465        for (int64_t i = 0; i < k; ++i)
2466            kind[i] = use_hits && ids[i] >= 0 && ids[i] < d.n_expert && (graph_hits
2467                ? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] >= 0
2468                : d.is_hit[(size_t) i] != 0) ? 0 : -1;
2469        static thread_local std::string remote_error;
2470        for (int r = 0; r < d.remote_count; ++r)
2471            if (!d.remote[r]->begin(d.layers, x_f, ids, 1, k, kind, d.host_res, remote_error)) {
2472                d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
2473            }
2474    }
2475
2476    for (int64_t i = 0; i < k; ++i) {
2477        const int64_t e = ids[i];
2478        if (e < 0 || e >= d.n_expert) {
2479            d.failed = true;
2480            d.fail = "a routed expert id is out of range";
2481            d.fail_layer = d.layers;
2482            d.fail_expert = e;
2483            return;
2484        }
2485        const uint8_t* b = d.src->blob(d.layers, e);
2486        if (b == nullptr) {
2487            // The one failure the loop cannot see.  Leaving `out` at its previous contents would feed the NEXT
2488            // layer a stale expert vector, which `moe_combine` would weight and add - the token would still be
2489            // finite and would still be wrong, 48 layers deep.
2490            d.failed = true;
2491            d.fail = "the expert source could not produce a blob";
2492            d.fail_layer = d.layers;
2493            d.fail_expert = e;
2494            ++d.missing;
2495            return;
2496        }
2497        // A hit's row was zeroed by `Launch` and belongs to the GPU; the pool must not touch it.
2498        if (use_hits && (graph_hits ? d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0
2499                                    : d.is_hit[(size_t) i] != 0)) {
2500            if (graph_hits) ++d.cache_hits;
2501            // The GPU owns this row and `hit_out` is zeroed, so the CPU's contribution is zero - but
2502            // `y_miss` is a REUSED pinned buffer, so the row must be written, not merely skipped.
2503            std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float));
2504            continue;
2505        }
2506        if (graph_hits) ++d.cache_refused;   // token graph: a miss (nothing is admitted during a token)
2507
2508        bool remote_owns = false;
2509        for (int r = 0; r < d.remote_count; ++r) remote_owns |= d.remote[r]->owns(i);
2510        if (remote_owns) {
2511            std::memset(out + (size_t) i * (size_t) n_embd, 0, (size_t) n_embd * sizeof(float));
2512            continue;
2513        }
2514
2515        // `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a
2516        // hit, and using one for the other is how a hit's row would get two experts summed into it.
2517        ExpertJob& j = d.jobs[(size_t) njobs++];
2518        j.blob = b;
2519        j.act = &d.act;             // SHARED across the batch: one conversion serves all ten experts
2520        j.out = out + (size_t) i * (size_t) n_embd;
2521        j.weight = 1.0f;            // clause 2: a diagnostic field, NOT the router weight
2522        j.slot = (int) i;
2523    }
2524
2525    // Plan v0.3 P4: rows of every expert across all threads (bitwise the same as `run`).
2526    if (d.split_rows) d.pool->run_split(d.jobs.data(), (int) njobs);
2527    else d.pool->run(d.jobs.data(), (int) njobs);
2528    if (d.remote_count > 0) {
2529        static thread_local std::string remote_error;
2530        for (int r = 0; r < d.remote_count; ++r)
2531            if (!d.remote[r]->finish(out, remote_error)) {
2532                d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
2533            }
2534    }
2535    ++d.layers;
2536    d.experts += k;
2537}
2538
2539namespace {
2540// the verify window's per-entry tables in `expert_pool_dispatch_multi` (`kind`, `distinct`, `first_of`)
2541// are fixed arrays of this many entries: MAXT tokens of the model's 10 routed experts must fit, and a larger k is
2542// refused at run time rather than written past them.
2543constexpr int64_t kMaxWindowEntries = 128;
2544static_assert(strata::kernels::cpu::MAXT * 10 <= kMaxWindowEntries, "a verify window's entries overflow the tables");
2545}  // namespace
2546
2547void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32_t* ids, int64_t n_tok, int64_t k,
2548                                float* out) {
2549    using namespace strata::kernels::cpu;
2550    if (d.failed) return;
2551    if (n_tok < 1 || n_tok > MAXT) {
2552        d.failed = true;
2553        d.fail = "a verify window has more tokens than the multi-token expert kernel takes";
2554        d.fail_layer = d.layers;
2555        return;
2556    }
2557    if (d.lookahead != nullptr) d.lookahead->submit(d.layers, x_f, n_tok, d.host_res);   // CS-T: warm layer + 1
2558    if (k < 1 || n_tok * k > kMaxWindowEntries) {
2559        d.failed = true;
2560        d.fail = "a verify window routes more entries than the expert pool's window tables hold";
2561        d.fail_layer = d.layers;
2562        return;
2563    }
2564    if ((int64_t) d.act_multi.size() < n_tok) d.act_multi.resize((size_t) MAXT);
2565    const ExpertLayout& lay = expert_layout();
2566    const bool native = lay.native;
2567    if (native && d.nact_multi.size() < (size_t) MAXT * kNativeActBytes) d.nact_multi.resize((size_t) MAXT * kNativeActBytes);
2568    if (d.job_of.size() != (size_t) d.n_expert) d.job_of.assign((size_t) d.n_expert, (int16_t) -1);
2569    if (d.jobs_multi.size() < (size_t) (n_tok * k)) d.jobs_multi.resize((size_t) (MAXT * k));
2570    static const bool ptrace = std::getenv("STRATA_POOL_TRACE") != nullptr;
2571    auto pt = [&](const char* what, long long a = -1) {
2572        if (ptrace) { std::fprintf(stderr, "pool trace: layer %lld %s %lld\n", (long long) d.layers, what, a); std::fflush(stderr); }
2573    };
2574    const auto c0 = std::chrono::steady_clock::now();
2575    pt("begin");
2576    d.src->begin_layer(d.layers, ids, n_tok * k);
2577    pt("begun");
2578    if (!d.usage.empty())
2579        for (int64_t i = 0; i < n_tok * k; ++i)
2580            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;
2581    // ---- plan v0.3 P6: the GPU's share, decided and published FIRST so the GPU starts while the CPU works.
2582    // Distinct experts in routing order; resident ones and the last pcie_num/256 of the missed ones go to the GPU.
2583    const int64_t n = n_tok * k;
2584    int32_t kind[kMaxWindowEntries];       // per entry: -1 CPU, 0 VRAM, 1 PCIe
2585    if (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap) {
2586        int64_t distinct[kMaxWindowEntries], first_of[kMaxWindowEntries];
2587        int nd = 0, nmiss = 0;
2588        // a helper GPU (RemoteExperts) holding the expert computes it in its own VRAM once begin() claims the row: like
2589        // the peer tier's, such an expert is no miss of this plan and never part of the PCIe share, which would read it
2590        // over the primary's link instead (2x RX 6900 XT, IQ3_S, --remote-expert-opt with the probed share 0.39: ~4
2591        // helper experts per layer-window moved to PCIe, 59 ms per window against 34 ms)
2592        auto helper_holds = [&](int32_t e) {
2593            for (int r = 0; r < d.remote_count; ++r)
2594                if (d.remote[r]->holds(d.layers, e)) return true;
2595            return false;
2596        };
2597        for (int64_t i = 0; i < n; ++i) {
2598            first_of[i] = i;
2599            for (int64_t j = 0; j < i; ++j)
2600                if (ids[j] == ids[i]) { first_of[i] = first_of[j]; break; }
2601            if (first_of[i] == i) {
2602                distinct[nd++] = i;
2603                const int32_t e = ids[i];
2604                if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0 &&
2605                    !(d.peer != nullptr && d.peer->has(d.layers, e)) && !helper_holds(e)) ++nmiss;
2606            }
2607        }
2608        const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers);
2609        const int m = pcie_ok ? (nmiss * d.pcie_num) >> 8 : 0;
2610        int miss_rank = 0, groups = 0, entries = 0, fetches = 0;
2611        GpuPlanSink& P = *d.plan;
2612        const uint8_t* dma_src[64];
2613        int64_t pcie_i0[64];
2614        for (int q = 0; q < nd; ++q) {
2615            const int64_t i0 = distinct[q];
2616            const int32_t e = ids[i0];
2617            int kd = -1;
2618            unsigned long long ptr = 0;
2619            if (e >= 0 && e < d.n_expert) {
2620                const int32_t slot = d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e];
2621                if (slot >= 0) {
2622                    kd = 0;
2623                    ptr = (unsigned long long) (d.cache_base + (d.cache_slot_off ? (size_t) d.cache_slot_off[slot]
2624                                                                                 : (size_t) slot * (size_t) d.cache_blob));
2625                } else if (d.peer != nullptr && d.peer->has(d.layers, e)) {
2626                    kd = 2;                        // multi-GPU: the second GPU computes it
2627                } else if (helper_holds(e)) {
2628                    // left to the helper: kind -1 until RemoteExperts::begin() claims the row (see above)
2629                } else {
2630                    if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) {
2631                        const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr;
2632                        if (src != nullptr) {
2633                            kd = 1;
2634                            dma_src[fetches] = src;
2635                            pcie_i0[fetches] = i0;
2636                            ++fetches;
2637                        }
2638                    }
2639                    ++miss_rank;
2640                }
2641            }
2642            for (int64_t i = i0; i < n; ++i)
2643                if (first_of[i] == i0) kind[i] = kd;
2644            if (kd != 0) continue;                 // the VRAM groups first; the PCIe groups below
2645            P.ptr[groups] = ptr;
2646            P.start[groups] = entries;
2647            for (int64_t i = i0; i < n; ++i)
2648                if (first_of[i] == i0) {
2649                    P.dst[entries] = (int32_t) i;
2650                    P.tok[entries] = (int32_t) (i / k);
2651                    ++entries;
2652                }
2653            ++groups;
2654        }
2655        P.start[groups] = entries;
2656        const uint64_t bb = lay.blob_bytes(d.layers);
2657        for (int q = 0; q < fetches; ++q) {       // the PCIe groups: staging slot q, entries after the VRAM ones
2658            const int64_t i0 = pcie_i0[q];
2659            P.ptr2[q] = P.pcie_mode != 0 ? (unsigned long long) d.src->device_alias(d.layers, ids[i0])
2660                                 : P.staging + (unsigned long long) q * (unsigned long long) bb;
2661            P.start2[q] = entries;
2662            for (int64_t i = i0; i < n; ++i)
2663                if (first_of[i] == i0) {
2664                    P.dst[entries] = (int32_t) i;
2665                    P.tok[entries] = (int32_t) (i / k);
2666                    ++entries;
2667                }
2668            ++d.pcie_experts;
2669        }
2670        P.start2[fetches] = entries;
2671        P.counts[0] = groups;
2672        P.counts[1] = entries;
2673        P.counts[2] = fetches;
2674        std::atomic_thread_fence(std::memory_order_seq_cst);
2675        pt("publish", fetches);
2676        if (P.publish) P.publish(P.ctx);
2677        pt("fetch", fetches);
2678        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
2679    } else {
2680        for (int64_t i = 0; i < n; ++i) {
2681            const int32_t e = ids[i];
2682            kind[i] = (e >= 0 && e < d.n_expert && d.host_res != nullptr &&
2683                       d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] >= 0) ? 0
2684                    : (e >= 0 && e < d.n_expert && d.peer != nullptr && d.peer->has(d.layers, e)) ? 2 : -1;
2685        }
2686    }
2687    if (d.peer != nullptr) {                 // multi-GPU: start the second GPU's share before the CPU's own work
2688        std::string perr;
2689        if (!d.peer->launch(d.layers, x_f, ids, n_tok, k, kind, perr, out)) {
2690            std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers);
2691            d.failed = true;
2692            d.fail = "the peer GPU's experts could not be launched";
2693            d.fail_layer = d.layers;
2694            return;
2695        }
2696    }
2697    if (d.remote_count > 0) {
2698        static thread_local std::string remote_error;
2699        for (int r = 0; r < d.remote_count; ++r) {
2700            if (!d.remote[r]->begin(d.layers, x_f, ids, n_tok, k, kind, d.host_res, remote_error)) {
2701                d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
2702            }
2703            for (int64_t i = 0; i < n; ++i) if (d.remote[r]->owns(i)) kind[i] = 2;
2704        }
2705    }
2706    static const bool dec_batch = [] { const char* v = std::getenv("STRATA_DEC_BATCH"); return v == nullptr || std::atoi(v) != 0; }();
2707    // the GPU's copy_rows_from_mapped zeroes the rows it computed itself (dec_batch); STRATA_VERIFY_DEVICE_PLAN's
2708    // copy_or_zero_from_mapped copies every row, so there the host still zeroes them
2709    static const bool device_plan = [] { const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); return v != nullptr && std::atoi(v) != 0; }();
2710    const bool gpu_zeroes_hits = (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap && dec_batch && !device_plan);
2711    bool any_cpu = false;
2712    for (int64_t i = 0; i < n; ++i)
2713        if (kind[i] < 0) { any_cpu = true; break; }
2714    const auto c1 = std::chrono::steady_clock::now();
2715    if (any_cpu) {
2716        // #578 --remote-expert-opt: a token whose experts all run on a GPU (CUDA0 or a helper) needs no CPU activation
2717        const bool ep = d.remote_count > 0 && d.remote[0]->optimized_decode();
2718        for (int64_t t = 0; t < n_tok; ++t) {
2719            if (ep && std::all_of(kind + t * k, kind + (t + 1) * k, [](int32_t v) { return v >= 0; })) continue;
2720            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
2721                act_quant_any(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
2722            else if (native)
2723                native_quant_act(lay.fmt[(size_t) d.layers], x_f + (size_t) t * H, d.nact_multi.data() + (size_t) t * kNativeActBytes);
2724            else
2725                act_quant_q8_1(x_f + (size_t) t * H, H, d.act_multi[(size_t) t]);
2726        }
2727    }
2728    const auto c2 = std::chrono::steady_clock::now();
2729    if (any_cpu) {   // CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads)
2730        static thread_local std::vector<int64_t> miss;
2731        miss.clear();
2732        for (int64_t i = 0; i < n_tok * k; ++i)
2733            if (kind[i] < 0 && ids[i] >= 0 && ids[i] < d.n_expert &&
2734                std::find(miss.begin(), miss.end(), (int64_t) ids[i]) == miss.end())
2735                miss.push_back(ids[i]);
2736        d.src->prefetch(d.layers, miss.data(), (int64_t) miss.size());
2737    }
2738    int njobs = 0;
2739    for (int64_t t = 0; t < n_tok; ++t)
2740        for (int64_t j = 0; j < k; ++j) {
2741            const int64_t i = t * k + j;
2742            const int64_t e = ids[i];
2743            float* row = out + (size_t) i * H;
2744            if (e < 0 || e >= d.n_expert) {
2745                d.failed = true;
2746                d.fail = "a routed expert id is out of range";
2747                d.fail_layer = d.layers;
2748                d.fail_expert = e;
2749                return;
2750            }
2751            if (kind[i] >= 0) {             // CUDA0, PCIe, or a remote/peer result staged into this row below
2752                if (kind[i] == 0) ++d.cache_hits;
2753                else ++d.offload_entries;                       // #588: PCIe or another GPU
2754                if (kind[i] == 2 && d.peer != nullptr) ++d.peer_entries;
2755                // multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it;
2756                // dec_batch: copy_rows_from_mapped_kernel already zeroes kind 0/1 rows on the GPU
2757                if (!((kind[i] == 2 && d.peer != nullptr && d.peer->launched_direct()) ||
2758                      (gpu_zeroes_hits && (kind[i] == 0 || kind[i] == 1))))
2759                    std::memset(row, 0, (size_t) H * sizeof(float));
2760                continue;
2761            }
2762            ++d.cache_refused;
2763            int16_t& jo = d.job_of[(size_t) e];
2764            if (jo < 0) {
2765                const uint8_t* b = d.src->blob(d.layers, e);
2766                if (b == nullptr) {
2767                    d.failed = true;
2768                    d.fail = "the expert source could not produce a blob";
2769                    d.fail_layer = d.layers;
2770                    d.fail_expert = e;
2771                    ++d.missing;
2772                    return;
2773                }
2774                jo = (int16_t) njobs++;
2775                ExpertJobMulti& nj = d.jobs_multi[(size_t) jo];
2776                nj.blob = b;
2777                nj.nt = 0;
2778            }
2779            ExpertJobMulti& jb = d.jobs_multi[(size_t) jo];
2780            jb.act[jb.nt] = &d.act_multi[(size_t) t];
2781            jb.nact[jb.nt] = native ? d.nact_multi.data() + (size_t) t * kNativeActBytes : nullptr;
2782            jb.out[jb.nt] = row;
2783            ++jb.nt;
2784            ++d.multi_entries;
2785        }
2786    const auto c3 = std::chrono::steady_clock::now();
2787    pt("run", njobs);
2788    if (njobs > 0) {
2789        if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs);
2790        else d.pool->run_split_multi(d.jobs_multi.data(), njobs);
2791    }
2792    if (d.remote_count > 0) {
2793        static thread_local std::string remote_error;
2794        for (int r = 0; r < d.remote_count; ++r)
2795            if (!d.remote[r]->finish(out, remote_error)) {
2796                d.failed = true; d.fail = remote_error.c_str(); d.fail_layer = d.layers; return;
2797            }
2798    }
2799    if (d.peer != nullptr) {                 // multi-GPU: the second GPU's rows, into the same mapped rows
2800        std::string perr;
2801        if (!d.peer->finish(out, perr)) {
2802            std::fprintf(stderr, "strata: %s (layer %lld)\n", perr.c_str(), (long long) d.layers);
2803            d.failed = true;
2804            d.fail = "the peer GPU's experts failed";
2805            d.fail_layer = d.layers;
2806            return;
2807        }
2808    }
2809    const auto c4 = std::chrono::steady_clock::now();
2810    pt("ran");
2811    auto ms = [](auto a, auto b) { return std::chrono::duration<double, std::milli>(b - a).count(); };
2812    d.ms_plan += ms(c0, c1);
2813    d.ms_actq += ms(c1, c2);
2814    d.ms_jobs += ms(c2, c3);
2815    d.ms_run += ms(c3, c4);
2816    for (int64_t i = 0; i < n_tok * k; ++i) {
2817        const int64_t e = ids[i];
2818        if (e >= 0 && e < d.n_expert) d.job_of[(size_t) e] = -1;
2819    }
2820    d.multi_misses += njobs;
2821    ++d.layers;
2822    d.experts += n_tok * k;
2823}
2824
2825void expert_hit_run(void *user, void *stream, HitPhase phase,
2826                    const int32_t *ids, int64_t k) try {
2827    ExpertDispatch& d = *(ExpertDispatch*) user;
2828    if (d.failed) return;
2829    dpct::queue_ptr cs = strata::q_of(stream);
2830
2831    if (phase == HitPhase::Launch) {
2832        d.decided = false;
2833        d.hit_pending = false;
2834        if (!d.hits_ready() || ids == nullptr || k <= 0) return;
2835        if ((int64_t) d.is_hit.size() < k) d.is_hit.resize((size_t) k);
2836
2837        // ================================ THE DECISION, ONCE, ON THIS LAYER'S IDS ================================
2838        //
2839        // Every routed expert is asked of the cache.  Resident -> the GPU computes it.  Not resident -> it is
2840        // admitted and filled if there is room (which makes it a hit on THIS call, because the fill and the
2841        // kernel are on one stream in that order), and otherwise it stays a miss for the CPU.
2842        d.n_hits = 0;
2843        for (int64_t i = 0; i < k; ++i) {
2844            const int64_t e = ids[i];
2845            d.is_hit[(size_t) i] = 0;
2846            if (e < 0 || e >= d.n_expert) continue;   // out of range: the pool refuses it, with a message
2847            int32_t slot = d.cache->slot_of(d.layers, e);
2848            if (slot == kNotResident) {
2849                const int32_t cand = d.cache->admit(d.layers, e);
2850                if (cand == kNotResident) {
2851                    ++d.cache_refused;
2852                    continue;
2853                }
2854                // `blob` is asked ONLY for an expert about to be filled, so the source's read counter stays a
2855                // count of distinct experts moved rather than of looks.
2856                const uint8_t* b = d.src->blob(d.layers, e);
2857                std::string ferr;
2858                if (b == nullptr || !d.cache->fill_slot(cand, b, cs, ferr, (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(d.layers))) {
2859                    d.failed = true;
2860                    d.fail = "the expert cache could not fill a slot";
2861                    d.fail_layer = d.layers;
2862                    d.fail_expert = e;
2863                    return;
2864                }
2865                ++d.cache_admitted;
2866                slot = cand;
2867            } else {
2868                ++d.cache_hits;
2869            }
2870            d.is_hit[(size_t) i] = 1;
2871            d.h_slot[(size_t) d.n_hits] = slot;
2872            d.h_dst[(size_t) d.n_hits] = (int32_t) i;
2873            ++d.n_hits;
2874        }
2875        d.decided = true;
2876        if (d.n_hits <= 0) return;   // nothing resident yet: no GPU work, and nothing for `Combine` to add
2877
2878        const size_t list_bytes = (size_t) d.n_hits * sizeof(int32_t);
2879        // `hit_out` is ZEROED rather than overwritten: the kernel writes only the rows this layer's hits own,
2880        // so a row that was a hit last layer and a miss this one would still hold last layer's expert and
2881        // `add_inplace` would sum it in.  Finite, plausible, wrong.
2882        if (DPCT_CHECK_ERROR(cs->memset(
2883                d.hit_out, 0, (size_t)d.parts_elems * sizeof(float))) != 0 ||
2884            /*
2885            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
2886            API. While the origin API might be synchronous, it depends on the
2887            type of operand memory, so you may need to call wait() on event
2888            return by memcpy API to ensure synchronization behavior.
2889            */
2890            DPCT_CHECK_ERROR(
2891                cs->memcpy(d.d_slot, d.h_slot.data(), list_bytes)) != 0 ||
2892            /*
2893            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
2894            API. While the origin API might be synchronous, it depends on the
2895            type of operand memory, so you may need to call wait() on event
2896            return by memcpy API to ensure synchronization behavior.
2897            */
2898            DPCT_CHECK_ERROR(cs->memcpy(d.d_dst, d.h_dst.data(), list_bytes)) !=
2899                0) {
2900            d.hit_fail = "the hit list could not be staged";
2901            d.failed = true;
2902            d.fail = d.hit_fail;
2903            return;
2904        }
2905        // The activation is quantized HERE rather than reused from `s.moe.x_q8_0`, which `post[l-1]` wrote from
2906        // the PREVIOUS layer's `mixed`.  `pre[l]` has since overwritten `mixed`, so that buffer is a layer stale
2907        // - and a stale activation produces a perfectly finite expert for the wrong input.
2908        // **R4.2h: THE SCALED QUANTIZER, SO A HIT REPRODUCES A MISS.**  The CPU pool quantizes this same
2909        // activation with `act_quant_q8_1` and multiplies by the fp32 `ActQ::scale`; `quantize_q8_0` writes
2910        // an fp16 `d` instead, and `bench/micro/act_quant_parity.cu` measured **80 of 80 chunks differing by
2911        // up to 4.761e-04 relative**.  `quantize_q8_0_scaled` adopts the CPU's rule and scale, and the kernel
2912        // takes the fp32 array.  Falling back to the old path would silently reintroduce the divergence, so
2913        // the scales are required here rather than optional.
2914        if (d.x_q8_0_hit_scale == nullptr) {
2915            d.failed = true;
2916            d.fail = "the hit path has no fp32 activation scales (R4.2h)";
2917            return;
2918        }
2919        strata::kernels::quantize_q8_0_scaled(d.mixed, d.x_q8_0_hit, d.x_q8_0_hit_scale, strata::kernels::cpu::H,
2920                                              cs);
2921        if (d.hit_cpu_order)
2922            strata::kernels::moe_hit_grouped_s2_cpu_order(d.cache_base, d.d_slot, d.d_dst, d.n_hits,
2923                d.cache_blob, d.x_q8_0_hit, d.hit_scratch, d.hit_out, cs, d.x_q8_0_hit_scale);
2924        else
2925            strata::kernels::moe_hit_grouped_s2(d.cache_base, d.d_slot, d.d_dst, d.n_hits, d.cache_blob,
2926                d.x_q8_0_hit, d.hit_scratch, d.hit_out, cs, d.x_q8_0_hit_scale);
2927        d.hit_pending = true;
2928        if (d.hit_done != nullptr)
2929            dpct::sync_barrier((dpct::event_ptr)d.hit_done, cs);
2930        // The A/B arm: ONE driver entry here, and nothing else changes.  If the work was waiting for the host
2931        // to enter the driver, this is what lets it start while the pool runs.
2932        if (d.hit_poke && d.hit_done != nullptr)(void)
2933            dpct::sycl_event_query((dpct::event_ptr)d.hit_done);
2934        return;
2935    }
2936
2937    // Combine: `parts += hit_out`, stream-ordered after the misses were copied into `parts`.
2938    if (!d.hit_pending) return;
2939    d.hit_pending = false;
2940    // Did the GPU get the hit work done while the CPU was in the pool?  This query is itself a driver entry,
2941    // so it is the LAST chance to observe a late start: a NOT-READY here means the work had not finished by the
2942    // time the pool returned, and with no poke in front of it that can only be because it began after.
2943    if (d.hit_done != nullptr) {
2944        if (((dpct::event_ptr)d.hit_done)
2945                ->get_info<sycl::info::event::command_execution_status>() ==
2946            sycl::info::event_command_status::complete)++ d.hit_ready;
2947        else ++d.hit_late;
2948    }
2949    strata::kernels::add_inplace(d.parts_out, d.hit_out, d.parts_elems, cs);
2950}
2951catch (sycl::exception const &exc) {
2952  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
2953            << ", line:" << __LINE__ << std::endl;
2954  std::exit(1);
2955}
2956
2957// ================================ THE RESIDENT ARENA (R2.1) ================================
2958
2959namespace {
2960
2961void hash_u64(uint64_t& h, uint64_t v) {
2962    h = fnv1a64((const uint8_t*) &v, sizeof v, h);
2963}
2964
2965void hash_text(uint64_t& h, const std::string& s) {
2966    h = fnv1a64((const uint8_t*) s.data(), (uint64_t) s.size(), h);
2967}
2968
2969bool hash_small_file(const std::filesystem::path& path, uint64_t& h, std::string& err) {
2970    hash_text(h, path.filename().string());
2971    std::ifstream f(path, std::ios::binary);
2972    if (!f) {
2973        hash_u64(h, 0);
2974        return true;
2975    }
2976    hash_u64(h, 1);
2977    std::vector<uint8_t> buf(64u << 10);
2978    for (;;) {
2979        f.read((char*) buf.data(), (std::streamsize) buf.size());
2980        const std::streamsize n = f.gcount();
2981        if (n > 0) h = fnv1a64(buf.data(), (uint64_t) n, h);
2982        if (f.eof()) break;
2983        if (!f) {
2984            err = "ArenaExpertSource: cannot hash pack metadata " + path.string();
2985            return false;
2986        }
2987    }
2988    return true;
2989}
2990
2991bool hash_sampled_file(const std::filesystem::path& path, uint64_t& h, std::string& err) {
2992    std::ifstream f(path, std::ios::binary | std::ios::ate);
2993    if (!f) {
2994        err = "ArenaExpertSource: cannot sample pack source " + path.string();
2995        return false;
2996    }
2997    const std::streamoff end = f.tellg();
2998    if (end < 0) {
2999        err = "ArenaExpertSource: cannot size pack source " + path.string();
3000        return false;
3001    }
3002    const uint64_t bytes = (uint64_t) end;
3003    hash_text(h, path.filename().string());
3004    hash_u64(h, bytes);
3005    constexpr uint64_t sample = 64u << 10;
3006    const uint64_t starts[3] = {0, bytes / 2, bytes > sample ? bytes - sample : 0};
3007    std::vector<uint8_t> buf((size_t) std::min<uint64_t>(sample, bytes));
3008    for (uint64_t off : starts) {
3009        if (buf.empty()) break;
3010        const uint64_t at = std::min<uint64_t>(off, bytes - (uint64_t) buf.size());
3011        f.clear();
3012        f.seekg((std::streamoff) at);
3013        f.read((char*) buf.data(), (std::streamsize) buf.size());
3014        if ((size_t) f.gcount() != buf.size()) {
3015            err = "ArenaExpertSource: short read while hashing pack source " + path.string();
3016            return false;
3017        }
3018        hash_u64(h, at);
3019        h = fnv1a64(buf.data(), (uint64_t) buf.size(), h);
3020    }
3021    return true;
3022}
3023
3024bool shared_arena_pack_hash(const std::string& pack_dir, const std::string& experts_path,
3025                            const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay,
3026                            uint64_t& out, std::string& err) {
3027    uint64_t h = 1469598103934665603ull;
3028    hash_text(h, "strata-shared-expert-arena-pack-v1");
3029    hash_u64(h, (uint64_t) lay.n_layers);
3030    hash_u64(h, (uint64_t) lay.n_expert);
3031    hash_u64(h, lay.total);
3032    hash_u64(h, lay.max_blob);
3033    hash_u64(h, lay.native ? 1 : 0);
3034
3035    const std::filesystem::path pack(pack_dir);
3036    for (const char* name : {"manifest.json", "index.txt", "native_experts.txt"}) {
3037        if (!hash_small_file(pack / name, h, err)) return false;
3038    }
3039
3040    if (std::filesystem::exists(experts_path)) {
3041        if (!hash_sampled_file(experts_path, h, err)) return false;
3042    } else if (!gguf.empty()) {
3043        // Native packs may read experts straight from one or more GGUF shards.  Sample every distinct source
3044        // file named by native_experts.txt; this keeps the fingerprint cheap while still tying it to the model
3045        // bytes rather than only to an equal-size layout.
3046        const std::filesystem::path first(gguf);
3047        std::vector<std::filesystem::path> sources{first};
3048        for (const std::string& name : lay.gguf_file) {
3049            if (name.empty()) continue;
3050            const std::filesystem::path p = first.parent_path() / name;
3051            if (std::find(sources.begin(), sources.end(), p) == sources.end()) sources.push_back(p);
3052        }
3053        for (const auto& p : sources) {
3054            if (!hash_sampled_file(p, h, err)) return false;
3055        }
3056    }
3057
3058    out = h == 0 ? 1 : h;
3059    return true;
3060}
3061
3062}  // namespace
3063
3064namespace {
3065/// The GGUF file that holds role `r` (0 gate, 1 up, 2 down) of layer `l`: a name beside the --native shard
3066/// (native_experts.txt v3 per layer, v4 per role), or the --native shard itself.
3067std::string expert_gguf_file(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, int64_t l, int r) {
3068    const size_t i = (size_t) (3 * l + r);
3069    if (lay.gguf_file.size() <= i || lay.gguf_file[i].empty()) return gguf;
3070    const size_t cut = gguf.find_last_of("/\\");
3071    return (cut == std::string::npos ? std::string() : gguf.substr(0, cut + 1)) + lay.gguf_file[i];
3072}
3073}  // namespace
3074
3075void ExpertSource::record_inputs(const std::string& pack_experts, const std::string& gguf,
3076                                 const strata::kernels::cpu::ExpertLayout& lay, bool from_gguf) {
3077    static const char* roles[3] = {"gate", "up", "down"};
3078    inputs_.clear();
3079    if (!from_gguf) { inputs_.push_back({"pack experts.bin", pack_experts}); return; }
3080    // the same resolution open_gguf / load_experts_gguf use: every (layer, role) tensor and the file it is read from
3081    for (int64_t l = 0; l < lay.n_layers; ++l)
3082        for (int r = 0; r < 3; ++r)
3083            inputs_.push_back({"expert blk." + std::to_string(l) + ".ffn_" + roles[r], expert_gguf_file(gguf, lay, l, r)});
3084}
3085
3086bool check_experts_gguf(const std::string& gguf, const strata::kernels::cpu::ExpertLayout& lay, std::string& err) {
3087    static const char* roles[3] = {"gate", "up", "down"};
3088    if (lay.gguf_off.size() != (size_t) (3 * lay.n_layers)) {
3089        err = "native_experts.txt has no GGUF offsets (a pack older than v2): repack it with tools/iq_pack.py";
3090        return false;
3091    }
3092    try {
3093        std::map<std::string, std::unique_ptr<strata::GgufFile>> files;
3094        for (int64_t l = 0; l < lay.n_layers; ++l) {
3095            const auto& fm = lay.fmt[(size_t) l];
3096            const uint64_t blob = lay.bytes[(size_t) l];
3097            const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
3098            for (int r = 0; r < 3; ++r) {
3099                const std::string path = expert_gguf_file(gguf, lay, l, r);
3100                auto& f = files[path];
3101                if (!f) f = std::make_unique<strata::GgufFile>(path);
3102                const std::string name = "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight";
3103                const strata::TensorInfo* t = f->find(name);
3104                const uint64_t want_type = (uint64_t) (r < 2 ? fm.gu_type : fm.d_type);
3105                // GGUF order: dim 0 is the row (the input), dim 1 the rows, dim 2 the experts
3106                const uint64_t cols = (uint64_t) (r < 2 ? fm.n_embd : fm.n_ff);
3107                const uint64_t rows = (uint64_t) (r < 2 ? fm.n_ff : fm.n_embd);
3108                const uint64_t bytes = per[r] * (uint64_t) lay.n_expert;
3109                const uint64_t payload = f->file_size() - f->data_start();
3110                std::string why;
3111                if (t == nullptr) why = "is not in it";
3112                else if (t->type != want_type)
3113                    why = std::string("is ") + t->type_name() + ", the pack says type " + std::to_string(want_type);
3114                else if (t->shape.size() != 3 || t->shape[0] != cols || t->shape[1] != rows ||
3115                         t->shape[2] != (uint64_t) lay.n_expert)
3116                    why = "is not [" + std::to_string(cols) + ", " + std::to_string(rows) + ", " +
3117                          std::to_string(lay.n_expert) + "]";
3118                else if (strata::tensor_payload_bytes(*t) != bytes)
3119                    why = "is not " + std::to_string(per[r]) + " B per expert";
3120                else if (f->data_start() + t->offset != lay.gguf_off[(size_t) (3 * l + r)])
3121                    why = "starts at byte " + std::to_string(f->data_start() + t->offset) + ", the pack says " +
3122                          std::to_string(lay.gguf_off[(size_t) (3 * l + r)]);
3123                else if (t->offset > payload || bytes > payload - t->offset)
3124                    why = "runs past the end of the file (a truncated shard?)";
3125                if (!why.empty()) {
3126                    err = "the pack's native_experts.txt does not match the model: " + name + " in " + path + " " +
3127                          why + " - repack with tools/iq_pack.py from this model's shards";
3128                    return false;
3129                }
3130            }
3131        }
3132        return true;
3133    } catch (const std::exception& e) {
3134        err = std::string("native experts from the GGUF: ") + e.what();
3135        return false;
3136    }
3137}
3138
3139// Plan v0.3 P6: the arena from the model's GGUF shards.  Each layer's gate, up and down tensors hold the 512
3140// experts one after another; they are read in chunks and each expert's slice lands at its place in the blob
3141// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin.  Each role
3142// is read from its own file (native_experts.txt v4: a shard boundary can fall inside a layer; per role as in
3143// #255, gopinath87607).  The caller checks the spans first (check_experts_gguf).
3144// `unbuffered` (Windows, experts_unbuffered): each chunk's 4 KiB-aligned window is read with FILE_FLAG_NO_BUFFERING into
3145// an aligned buffer and scattered into the blobs - no copy through the file cache when the drive is read anyway.
3146LoadStats load_experts_gguf(const std::string& gguf, uint8_t* dst, const strata::kernels::cpu::ExpertLayout& lay,
3147                            int threads, bool unbuffered, const std::atomic<int>* ready) {
3148    // `ready`: layer l is written only once *ready > l + 1 (a PinnedArena registering its slices meanwhile; the next
3149    // slice too, since its registration starts on the page that may hold this layer's tail)
3150    auto wait_ready = [ready](int64_t l) {
3151        if (ready != nullptr)
3152            while (ready->load(std::memory_order_acquire) <= l + 1) std::this_thread::yield();
3153    };
3154    LoadStats st;
3155    st.layers = (uint64_t) lay.n_layers;
3156    const auto t0 = std::chrono::steady_clock::now();
3157    std::atomic<int64_t> next{0};
3158    std::atomic<bool> bad{false};
3159#if defined(_WIN32)
3160    if (unbuffered) {
3161        uint64_t max_chunk = 0;
3162        for (int64_t l = 0; l < lay.n_layers; ++l) {
3163            const auto& fm = lay.fmt[(size_t) l];
3164            max_chunk = std::max<uint64_t>(max_chunk, std::max<uint64_t>(fm.up_off, lay.bytes[(size_t) l] - fm.down_off) * 16);
3165        }
3166        std::mutex err_mu;
3167        std::string err;
3168        auto worker = [&]() {
3169            constexpr uint64_t kSector = 4096;
3170            const uint64_t cap = (max_chunk + 2 * kSector + kSector - 1) / kSector * kSector;
3171            uint8_t* buf = (uint8_t*) VirtualAlloc(nullptr, (size_t) cap, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
3172            HANDLE h = INVALID_HANDLE_VALUE;
3173            std::string open_name;
3174            auto fail = [&](const std::string& what) {
3175                std::lock_guard<std::mutex> g(err_mu);
3176                if (err.empty()) err = what;
3177                bad = true;
3178            };
3179            if (buf == nullptr) fail("cannot allocate a read buffer");
3180            for (;;) {
3181                const int64_t l = next.fetch_add(1);
3182                if (l >= lay.n_layers || bad) break;
3183                wait_ready(l);
3184                const auto& fm = lay.fmt[(size_t) l];
3185                const uint64_t blob = lay.bytes[(size_t) l];
3186                const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
3187                const uint64_t at[3] = {0, fm.up_off, fm.down_off};
3188                for (int r = 0; r < 3 && !bad; ++r) {
3189                    // the handle is kept while consecutive roles share a file (every layer of a v3 pack)
3190                    const std::string name = expert_gguf_file(gguf, lay, l, r);
3191                    if (name != open_name) {
3192                        if (h != INVALID_HANDLE_VALUE) CloseHandle(h);
3193                        const int wide = MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, nullptr, 0);
3194                        std::vector<wchar_t> w((size_t) std::max(wide, 1), L'\0');
3195                        if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, name.c_str(), -1, w.data(), wide);
3196                        h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
3197                                        FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
3198                        if (h == INVALID_HANDLE_VALUE) {
3199                            fail("cannot open " + name + " (error " + std::to_string((unsigned long long) GetLastError()) + ")");
3200                            break;
3201                        }
3202                        open_name = name;
3203                    }
3204                    const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)];
3205                    const uint64_t total = per[r] * (uint64_t) lay.n_expert;
3206                    const uint64_t chunk = per[r] * 16;           // 16 experts per read
3207                    for (uint64_t done = 0; done < total; done += chunk) {
3208                        const uint64_t n = std::min<uint64_t>(chunk, total - done);
3209                        const uint64_t a0 = (src + done) / kSector * kSector;
3210                        const uint64_t a1 = (src + done + n + kSector - 1) / kSector * kSector;
3211                        OVERLAPPED ov{};
3212                        ov.Offset = (DWORD) a0;
3213                        ov.OffsetHigh = (DWORD) (a0 >> 32);
3214                        DWORD got = 0;
3215                        // the window may run past the end of the file: only the tensor's own bytes have to arrive
3216                        if (!ReadFile(h, buf, (DWORD) (a1 - a0), &got, &ov) || (uint64_t) got < src + done - a0 + n) {
3217                            fail("short unbuffered read of layer " + std::to_string(l) + " in " + name + " (error " +
3218                                 std::to_string((unsigned long long) GetLastError()) + ")");
3219                            break;
3220                        }
3221                        const uint8_t* q = buf + (src + done - a0);
3222                        for (uint64_t k = 0; k < n / per[r]; ++k) {
3223                            const uint64_t e = done / per[r] + k;
3224                            std::memcpy(dst + lay.blob_offset(l, (int64_t) e) + at[r], q + k * per[r], (size_t) per[r]);
3225                        }
3226                    }
3227                }
3228            }
3229            if (h != INVALID_HANDLE_VALUE) CloseHandle(h);
3230            if (buf != nullptr) VirtualFree(buf, 0, MEM_RELEASE);
3231        };
3232        std::vector<std::thread> pool;
3233        for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
3234        worker();
3235        for (auto& t : pool) t.join();
3236        if (bad) {
3237            st.seconds = -1.0;
3238            st.ok = false;
3239            st.error = err.empty() ? "unreadable shard while reading the experts from the GGUF" : err;
3240            return st;
3241        }
3242        st.bytes = lay.total;
3243        st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
3244        return st;
3245    }
3246#else
3247    (void) unbuffered;
3248#endif
3249    auto worker = [&]() {
3250        // #230: `fread` on a `FILE*`, as load_experts_ranges (#89): MSVC's `std::ifstream::read` splits a request
3251        // into 4095-byte freads, which took this path to 0.02 GiB/s on a Windows install without experts.bin.
3252        // The guard closes the handle on every return.
3253        struct Closer {
3254            FILE* f = nullptr;
3255            ~Closer() { if (f != nullptr) std::fclose(f); }
3256        } file;
3257        std::string open_name;
3258        std::vector<uint8_t> buf;
3259        for (;;) {
3260            const int64_t l = next.fetch_add(1);
3261            if (l >= lay.n_layers || bad) break;
3262            wait_ready(l);
3263            const auto& fm = lay.fmt[(size_t) l];
3264            const uint64_t blob = lay.bytes[(size_t) l];
3265            const uint64_t per[3] = {fm.up_off, fm.up_off, blob - fm.down_off};
3266            const uint64_t at[3] = {0, fm.up_off, fm.down_off};
3267            for (int r = 0; r < 3; ++r) {
3268                // the handle is kept while consecutive roles share a file (every layer of a v3 pack)
3269                const std::string name = expert_gguf_file(gguf, lay, l, r);
3270                if (name != open_name) {
3271                    if (file.f != nullptr) std::fclose(file.f);
3272                    file.f = std::fopen(name.c_str(), "rb");
3273                    if (file.f == nullptr) { bad = true; return; }
3274                    open_name = name;
3275                }
3276                FILE* const f = file.f;
3277                const uint64_t src = lay.gguf_off[(size_t) (3 * l + r)];
3278                const uint64_t total = per[r] * (uint64_t) lay.n_expert;
3279                const uint64_t chunk = per[r] * 16;           // 16 experts per read
3280                buf.resize((size_t) chunk);
3281                for (uint64_t done = 0; done < total; done += chunk) {
3282                    const uint64_t n = std::min<uint64_t>(chunk, total - done);
3283                    // 64-bit seek: a shard is tens of GB
3284                    if (STRATA_FSEEK64(f, src + done) != 0) { bad = true; return; }
3285                    if (std::fread(buf.data(), 1, (size_t) n, f) != (size_t) n) { bad = true; return; }
3286                    for (uint64_t k = 0; k < n / per[r]; ++k) {
3287                        const uint64_t e = done / per[r] + k;
3288                        std::memcpy(dst + lay.blob_offset(l, (int64_t) e) + at[r], buf.data() + k * per[r], (size_t) per[r]);
3289                    }
3290                }
3291            }
3292        }
3293    };
3294    std::vector<std::thread> pool;
3295    for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
3296    worker();
3297    for (auto& t : pool) t.join();
3298    if (bad) {
3299        st.seconds = -1.0;
3300        st.ok = false;
3301        st.error = "short read or unreadable shard while reading the experts from the GGUF";
3302        return st;
3303    }
3304    st.bytes = lay.total;
3305    st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
3306    return st;
3307}
3308
3309ArenaExpertSource::~ArenaExpertSource() { close(); }
3310
3311bool ArenaExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, int threads,
3312                             std::string& err, uint64_t max_pinned_bytes,
3313                             const std::string& shared_arena_file) {
3314    close();
3315    const std::string path = pack_dir + "/experts.bin";
3316    // plan v0.3 P6: the layout (canonical, or a native pack's per-layer blobs) was loaded by the driver
3317    const strata::kernels::cpu::ExpertLayout& lay = strata::kernels::cpu::expert_layout();
3318    if (lay.n_layers != n_layers || lay.n_expert != n_expert) {
3319        err = "ArenaExpertSource: the expert layout was loaded for a different geometry";
3320        return false;
3321    }
3322    const int64_t blob = (int64_t) lay.max_blob;
3323    const uint64_t want = lay.total;
3324
3325    // plan v0.3 P6: no experts.bin in a native pack -> the experts come straight from the GGUF
3326    const bool from_gguf = !std::ifstream(path, std::ios::binary) && lay.native && !lay.gguf_off.empty() && !gguf_.empty();
3327    // SIZE CHECK BEFORE THE ALLOCATION, not after.  A wrong pack should name the two numbers rather than spend
3328    // 34 GB and a minute of loading first.
3329    if (from_gguf) {
3330        // every (file, offset) of native_experts.txt must be the tensor it claims, of the pack's type and
3331        // dimensions and inside its file - before the allocation, so a pack of another model or a truncated
3332        // shard is a message rather than an arena of plausible wrong experts
3333        if (!check_experts_gguf(gguf_, lay, err)) { err = "ArenaExpertSource: " + err; return false; }
3334    } else {
3335        std::ifstream f(path, std::ios::binary | std::ios::ate);
3336        if (!f) { err = "ArenaExpertSource: cannot open " + path; return false; }
3337        const uint64_t got = (uint64_t) f.tellg();
3338        if (got != want && got != want + (uint64_t) blob) {   // + one blob: STRATA_ARENA_MMAP's padded file
3339            char buf[400];
3340            std::snprintf(buf, sizeof buf,
3341                          "ArenaExpertSource: %s is %llu B but %lld layers x %lld experts (blobs up to %lld B) "
3342                          "make %llu B - this is not the pack this geometry came from",
3343                          path.c_str(), (unsigned long long) got, (long long) n_layers, (long long) n_expert,
3344                          (long long) blob, (unsigned long long) want);
3345            err = buf;
3346            return false;
3347        }
3348    }
3349
3350    // STRATA_ARENA_MMAP=1 (a small-RAM machine whose GPUs hold most experts): the arena is the pack's experts.bin
3351    // mapped READ-ONLY - not locked, not pinned.  The page cache keeps what the CPU pool and the prompt path
3352    // actually read (the experts no VRAM cache holds) and gives back the rest under memory pressure; a page
3353    // dropped is re-read from the file, so a result never depends on what is resident.  The GPUs then get no
3354    // mapped alias: run with --pcie-frac 0.  The first start writes experts.bin (arena layout, padded by one blob
3355    // so a whole-slot copy may start at any expert), later ones map it.
3356#if defined(_WIN32)
3357    static const bool arena_mmap = false;   // POSIX mmap/madvise: Linux only for now
3358#else
3359    static const bool arena_mmap = [] { const char* v = std::getenv("STRATA_ARENA_MMAP"); return v && v[0] == '1'; }();
3360    if (arena_mmap) {
3361        const uint64_t file_bytes = want + (uint64_t) blob;
3362        uint64_t have = 0;
3363        {
3364            std::ifstream f(path, std::ios::binary | std::ios::ate);
3365            if (f) have = (uint64_t) f.tellg();
3366        }
3367        if (have == file_bytes) {
3368            const int fd = ::open(path.c_str(), O_RDONLY);
3369            void* v = fd >= 0 ? mmap(nullptr, (size_t) file_bytes, PROT_READ, MAP_SHARED, fd, 0) : MAP_FAILED;
3370            if (fd >= 0) ::close(fd);
3371            if (v == MAP_FAILED) { err = "ArenaExpertSource: mmap of " + path + " failed"; return false; }
3372            map_ = v;
3373            map_bytes_ = file_bytes;
3374            base_ = (const uint8_t*) v;
3375            pinned_bytes_ = 0;
3376            dev_slice_.clear();
3377            slice_bytes_ = 0;
3378            blobs_ = n_layers * n_expert;
3379            n_expert_ = n_expert;
3380            reads_ = 0;
3381            note_ = "mapped read-only from " + path + " (STRATA_ARENA_MMAP: not locked, not pinned)";
3382            gib_per_s_ = 0.0;
3383            load_seconds_ = load_read_s_ = load_copy_s_ = 0.0;
3384            record_inputs(path, gguf_, lay, from_gguf);   // session files: the mapped experts.bin is a model input
3385            return true;
3386        }
3387    }
3388#endif
3389
3390    // #633: THE RAM BEFORE THE ALLOCATION.  On Linux the arena is an anonymous mapping that succeeds whatever the host
3391    // has; its pages are committed as the load writes them, so a container whose memory limit is below the arena was
3392    // killed by the OOM killer part-way through the load, without a message.  A hard cgroup limit below it is
3393    // certain to end that way: refused, with the numbers.  Less RAM available than the arena (another program, an
3394    // engine still exiting) is only a warning - the OS may make room - per the recommend-not-force rule.
3395    ram_warning_.clear();
3396    // (a shared arena, --shared-expert-arena, may already be in RAM for another engine: not checked)
3397    if (detail::HostMemory hm; shared_arena_file.empty() && detail::host_available_memory(hm)) {
3398        const uint64_t need = want + (uint64_t) blob;
3399        const double gib = 1073741824.0;
3400        char buf[512];
3401        if (hm.cgroup_limit < need) {
3402            std::snprintf(buf, sizeof buf,
3403                          "ArenaExpertSource: the expert arena needs %.2f GiB of RAM but this process's memory limit "
3404                          "(cgroup memory.max / memory.limit_in_bytes) is %.2f GiB: it would be killed while loading. "
3405                          "Raise the container's limit, or run with less RAM: --mmap-experts with "
3406                          "--resident-budget-gib N keeps only the hottest experts in RAM",
3407                          (double) need / gib, (double) hm.cgroup_limit / gib);
3408            err = buf;
3409            return false;
3410        }
3411        if (hm.available < need) {
3412            std::snprintf(buf, sizeof buf,
3413                          "the expert arena needs %.2f GiB of RAM but %.2f GiB is available (%.2f GiB short): the load "
3414                          "may swap or be stopped by the OS. Close other programs (or wait for an engine that is "
3415                          "still exiting), or run with less RAM: --mmap-experts with --resident-budget-gib N",
3416                          (double) need / gib, (double) hm.available / gib, (double) (need - hm.available) / gib);
3417            ram_warning_ = buf;
3418        }
3419    }
3420
3421    uint64_t pack_hash = 0;
3422    if (!shared_arena_file.empty() &&
3423        !shared_arena_pack_hash(pack_dir, path, gguf_, lay, pack_hash, err)) return false;
3424
3425    // one layer per registration slice, so no expert straddles two registrations.  The arena is one blob
3426    // longer than the file: a copy of a whole VRAM slot (the largest blob) may then start at any expert.
3427    std::vector<uint64_t> bounds, loff, lbytes;
3428    for (int64_t l = 0; l < n_layers; ++l) {
3429        bounds.push_back(lay.layer_offset(l));
3430        loff.push_back(lay.layer_offset(l));
3431        lbytes.push_back(lay.blob_bytes(l) * (uint64_t) n_expert);
3432    }
3433    bounds.push_back(want);
3434    // #285: on Windows the per-layer registration runs on a thread ahead of the readers, which wait for their
3435    // layer's slice (the whole arena registered before the load cost ~2.5 s at 33 GiB of 4 KB pages, not hidden).
3436    // Only where the whole arena would be registered: no cap (STRATA_ARENA_PIN_GIB, multi-GPU), no shared arena.
3437    // Linux keeps the whole-arena pin (#253). OPT-IN (STRATA_DEFERRED_REGISTER=1): on the RTX 5070 / Windows the
3438    // arena registered per layer before it is filled decoded ~10% slower than the old order (whole-arena try, sliced
3439    // fallback after the load) with identical output; the start-time gain does not pay for that.
3440#ifdef _WIN32
3441    const char* defer_env = std::getenv("STRATA_DEFERRED_REGISTER");
3442    const bool deferred = max_pinned_bytes == 0 && arena_pin_cap_gib() == -1 && shared_arena_file.empty() &&
3443                          (defer_env != nullptr && defer_env[0] != 0 && defer_env[0] != '0');
3444#else
3445    const bool deferred = false;
3446#endif
3447    PinnedArena* a = deferred ? new PinnedArena(want + (uint64_t) blob, bounds, PinnedArena::Deferred{})
3448                              : new PinnedArena(want + (uint64_t) blob, bounds, max_pinned_bytes,
3449                                                shared_arena_file, pack_hash);
3450    if (!a->valid()) {
3451        const std::string why = a->note;
3452        delete a;
3453        err = "ArenaExpertSource: the arena could not be reserved (" +
3454              std::to_string(want + (uint64_t) blob) + " B)" +
3455              (why.empty() ? std::string{} : ": " + why);
3456        return false;
3457    }
3458    // #285: unbuffered when the drive is read anyway and the file cache could not keep the experts for the next
3459    // start either (a 64 GB PC); otherwise the buffered readers, which a warm restart serves from the cache
3460    std::vector<std::string> files;
3461    if (from_gguf) {
3462        for (int64_t l = 0; l < n_layers; ++l)
3463            for (int r = 0; r < 3; ++r) {
3464                const std::string f = expert_gguf_file(gguf_, lay, l, r);
3465                if (std::find(files.begin(), files.end(), f) == files.end()) files.push_back(f);
3466            }
3467    } else {
3468        files.push_back(path);
3469    }
3470    std::string why;
3471    const bool unbuffered = experts_unbuffered(files, want + (uint64_t) blob, why);
3472    const int readers = unbuffered ? std::max(threads, 16) : threads;   // 16 keep a PCIe 5 drive's queue full
3473    LoadStats st;
3474    std::atomic<int> ready{0};
3475    std::thread reg;
3476    if (deferred) {
3477        int dev = 0;
3478        dev = dpct::get_current_device_id();
3479        reg = std::thread([a, &ready, dev] {
3480            /*
3481            DPCT1093: The "dev" device may be not the one intended for use.
3482            Adjust the selected device if needed.
3483            */
3484            dpct::select_device(dev);
3485            a->register_slices(ready);
3486        });
3487    }
3488    const std::atomic<int>* rp = deferred ? &ready : nullptr;
3489    if (from_gguf) {
3490        st = load_experts_gguf(gguf_, a->data(), lay, readers, unbuffered, rp);
3491    } else {
3492        if (unbuffered) st = load_experts_direct(path, a->data(), loff, lbytes, readers, /*chunk=*/8u << 20, rp);
3493        if (!unbuffered || (!st.ok && st.error.empty()))   // unaligned ranges: the buffered reader
3494            st = load_experts_ranges(path, a->data(), loff, lbytes, threads, /*chunk=*/8u << 20, rp);
3495    }
3496    if (reg.joinable()) reg.join();
3497    std::fprintf(stderr, "strata generate: expert arena read %s (%s)\n", unbuffered ? "unbuffered" : "through the file cache",
3498                 why.c_str());
3499    if (!st.ok) {
3500        delete a;
3501        err = "ArenaExpertSource: the expert load was refused: " + (st.error.empty() ? std::string("unknown") : st.error);
3502        return false;
3503    }
3504    if (st.bytes != want) {
3505        delete a;
3506        err = "ArenaExpertSource: the load read " + std::to_string(st.bytes) + " B of " + std::to_string(want);
3507        return false;
3508    }
3509    if (std::getenv("STRATA_VERIFY_ARENA") != nullptr) {   // tests: the loaded arena's checksum, any loader
3510        std::fprintf(stderr, "strata generate: expert arena checksum %016llx (%.2f GiB)\n",
3511                     (unsigned long long) fnv1a64(a->data(), want), (double) want / (1ull << 30));
3512    }
3513    // the first start: write experts.bin for the mapped starts after this one - only when the drive has room for it
3514    // and 2 GiB more (a full drive fails other writes too); otherwise this start says so and runs pinned as before
3515    std::error_code space_ec;
3516    const uint64_t free_disk = arena_mmap && from_gguf ? (uint64_t) std::filesystem::space(
3517        std::filesystem::path(path).parent_path(), space_ec).available : 0;
3518    const bool room = !space_ec && free_disk >= want + (uint64_t) blob + (2ull << 30);
3519    if (arena_mmap && from_gguf && !room)
3520        std::fprintf(stderr, "strata generate: STRATA_ARENA_MMAP: NOT writing %s - %.1f GiB free on that drive, it needs "
3521                             "%.1f GiB plus 2 GiB to spare; this start keeps the arena in RAM\n", path.c_str(),
3522                     (double) free_disk / 1073741824.0, (double) (want + (uint64_t) blob) / 1073741824.0);
3523    if (arena_mmap && from_gguf && room) {
3524        const std::string tmp = path + ".tmp";
3525        std::FILE* f = std::fopen(tmp.c_str(), "wb");
3526        bool ok = f != nullptr && std::fwrite(a->data(), 1, (size_t) want, f) == (size_t) want;
3527        if (ok) {
3528            std::vector<uint8_t> pad((size_t) blob, 0);
3529            ok = std::fwrite(pad.data(), 1, pad.size(), f) == pad.size();
3530        }
3531        if (f) ok = std::fclose(f) == 0 && ok;
3532        if (ok) ok = std::rename(tmp.c_str(), path.c_str()) == 0;
3533        if (!ok) std::remove(tmp.c_str());
3534        std::fprintf(stderr, "strata generate: STRATA_ARENA_MMAP: %s %s (the next start maps it)\n",
3535                     ok ? "wrote" : "could NOT write", path.c_str());
3536    }
3537    arena_ = a;
3538    base_ = a->data();
3539    pinned_bytes_ = a->registered_bytes;
3540    // plan v0.3 P6: device aliases of the mapped registration, for the PCIe share of the misses
3541    dev_slice_.clear();
3542    slice_bytes_ = a->slice_bytes;
3543    if (a->registered_bytes > 0) {
3544        std::vector<uint64_t> starts = a->slice_bytes > 0 ? a->slice_starts : std::vector<uint64_t>{0};
3545        for (uint64_t off : starts) {
3546            void* d = nullptr;
3547            if (DPCT_CHECK_ERROR(d = (void *)(void *)(base_ + off)) != 0) {
3548                /*
3549                DPCT1010: SYCL uses exceptions to report errors and does
3550                not use the error codes. The cudaGetLastError function call was
3551                replaced with 0. You need to rewrite this code.
3552                */
3553                (void)0;
3554                dev_slice_.clear();
3555                break;
3556            }
3557            dev_slice_.push_back((const uint8_t*) d);
3558        }
3559    }
3560    blobs_ = n_layers * n_expert;
3561    n_expert_ = n_expert;
3562    reads_ = 0;
3563    note_ = a->note;
3564    gib_per_s_ = st.gib_per_second();
3565    load_seconds_ = st.seconds;
3566    load_read_s_ = st.read_seconds;
3567    load_copy_s_ = st.copy_seconds;
3568    record_inputs(path, gguf_, lay, from_gguf);
3569    return true;
3570}
3571
3572void ArenaExpertSource::close() {
3573#if !defined(_WIN32)
3574    if (map_ != nullptr) munmap(map_, (size_t) map_bytes_);
3575#endif
3576    map_ = nullptr;
3577    map_bytes_ = 0;
3578    inputs_.clear();
3579    if (arena_ != nullptr) {
3580        delete (PinnedArena*) arena_;
3581        arena_ = nullptr;
3582    }
3583    base_ = nullptr;
3584    blobs_ = 0;
3585    n_expert_ = 0;
3586}
3587
3588void ArenaExpertSource::prefetch(int64_t layer, int64_t expert) {
3589#if defined(_WIN32)
3590    (void) layer; (void) expert;
3591#else
3592    if (map_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return;
3593    const auto& lay = strata::kernels::cpu::expert_layout();
3594    const uint64_t off = lay.blob_offset(layer, expert) & ~(uint64_t) 4095;
3595    const uint64_t end = lay.blob_offset(layer, expert) + lay.blob_bytes(layer);
3596    madvise((uint8_t*) map_ + off, (size_t) (end - off), MADV_WILLNEED);
3597#endif
3598}
3599
3600// Only the pages wholly inside the blob: a page shared with a neighbour the CPU may still read stays.  MADV_DONTNEED
3601// unmaps them from this process; they stay in the page cache as clean, unmapped pages - the first the kernel takes
3602// back under pressure, and a minor fault away when the CPU needs the expert again (an adaptive swap evicts it).
3603// Dropping them from the cache too (POSIX_FADV_DONTNEED) made every eviction a re-read from the disk: ~200 major
3604// faults a second in decode, +8 ms a window.  The memory the arena used to hold was never the cache itself but
3605// ROCclr's pin-in-place locks on it (see main) - locked pages are the ones the kernel cannot take back.
3606uint64_t ArenaExpertSource::release(int64_t layer, int64_t expert) {
3607#if defined(_WIN32)
3608    (void) layer; (void) expert;
3609    return 0;
3610#else
3611    if (map_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return 0;
3612    const auto& lay = strata::kernels::cpu::expert_layout();
3613    const uint64_t off = (lay.blob_offset(layer, expert) + 4095) & ~(uint64_t) 4095;
3614    const uint64_t end = (lay.blob_offset(layer, expert) + lay.blob_bytes(layer)) & ~(uint64_t) 4095;
3615    if (end <= off) return 0;
3616    if (madvise((uint8_t*) map_ + off, (size_t) (end - off), MADV_DONTNEED) != 0) return 0;
3617    return end - off;
3618#endif
3619}
3620
3621bool ArenaExpertSource::pinned(int64_t layer, int64_t expert) const {
3622    if (base_ == nullptr || layer < 0 || expert < 0 || expert >= n_expert_) return false;
3623    const auto& lay = strata::kernels::cpu::expert_layout();
3624    return lay.blob_offset(layer, expert) + lay.blob_bytes(layer) <= pinned_bytes_;
3625}
3626
3627const uint8_t* ArenaExpertSource::device_alias(int64_t layer, int64_t expert) const {
3628    if (dev_slice_.empty() || !pinned(layer, expert)) return nullptr;
3629    const auto& lay = strata::kernels::cpu::expert_layout();
3630    if (slice_bytes_ == 0) return dev_slice_[0] + lay.blob_offset(layer, expert);
3631    // one registration slice per layer
3632    if ((size_t) layer >= dev_slice_.size()) return nullptr;
3633    return dev_slice_[(size_t) layer] + (uint64_t) expert * lay.blob_bytes(layer);
3634}
3635
3636const uint8_t* ArenaExpertSource::blob(int64_t layer, int64_t expert) {
3637    if (base_ == nullptr) return nullptr;
3638    if (layer < 0 || expert < 0 || expert >= n_expert_) return nullptr;
3639    const int64_t idx = layer * n_expert_ + expert;
3640    if (idx < 0 || idx >= blobs_) return nullptr;
3641    ++reads_;
3642    // Pointer arithmetic into resident memory.  No fault, no copy, no mapping - which is the entire point of
3643    // this class over `FileExpertSource`.
3644    return base_ + strata::kernels::cpu::expert_layout().blob_offset(layer, expert);
3645}
3646
3647}  // namespace strata::core