okami.mom/strata

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

Niko1221Merge f-gfx11-arrival 0ee263992 into f-p4-int (integrated AMD graphics under Linux: no huge-page request for the expert arena, a settle before READY, the model files' page cache given back after the expert load)29ebb7926

main
42.7 KiB904 linesraw
1// src/core/pinned.cu - P2.S1: the pinned host arena and the parallel expert load.
2#define DPCT_PROFILING_ENABLED
3#include <sycl/sycl.hpp>
4#include <dpct/dpct.hpp>
5#include "strata/core/pinned.hpp"
6#include "strata/platform/memory.hpp"
7
8#include <atomic>
9#include <climits>
10#include <cerrno>
11#include <cstdlib>
12#include <cstdio>
13#include <cstring>
14#include <fstream>
15#include <mutex>
16#include <thread>
17
18// Loader fix: `fseek`/`ftell` are 32-bit on Windows by default (and the pack is 42.9 GB), and the 64-bit
19// spelling is not the same on the two platforms the engine builds for.
20#ifdef _WIN32
21#define STRATA_FSEEK64(f, o) _fseeki64((f), (long long) (o), SEEK_SET)
22#else
23#define STRATA_FSEEK64(f, o) fseeko((f), (off_t) (o), SEEK_SET)
24#endif
25
26#ifdef _WIN32
27#include <windows.h>
28#else
29#include <fcntl.h>
30#include <sys/mman.h>
31#include <sys/stat.h>
32#include <unistd.h>
33#include <linux/mman.h>
34#ifndef MAP_HUGE_2MB
35#define MAP_HUGE_2MB (21 << 26)
36#endif
37#endif
38
39namespace strata::core {
40
41namespace {
42
43constexpr uint64_t kSharedArenaHeaderBytes = 4096;
44constexpr char kSharedArenaMagic[16] = "STRATA-ARENA-V1";
45
46struct SharedArenaHeader {
47    char magic[16];
48    uint32_t version;
49    uint32_t header_bytes;
50    uint64_t arena_bytes;
51    uint64_t pack_hash;
52    uint64_t reserved[4];
53};
54static_assert(sizeof(SharedArenaHeader) <= kSharedArenaHeaderBytes);
55
56// A 2 MB-aligned reservation.  Large pages first, then the largest alignment the OS will give us for free.
57// A non-empty shared_file instead maps one file whose first 4 KiB identify the pack and whose remaining bytes
58// are the resident arena.  This shared-file layout is intended for tmpfs (/dev/shm); hugetlbfs would need
59// hugepage-aligned file size and arena offset rather than the 4 KiB header layout used here.
60void* reserve(uint64_t bytes, PageBacking& got, std::string& note, const std::string& shared_file,
61              uint64_t shared_pack_hash, void*& mapping_base, uint64_t& mapping_bytes) {
62    mapping_base = nullptr;
63    mapping_bytes = 0;
64#ifdef _WIN32
65    if (!shared_file.empty()) {
66        note = "shared-file arena backing is not implemented on Windows";
67        return nullptr;
68    }
69    // MEM_LARGE_PAGES needs SeLockMemoryPrivilege.  Having it assigned to the account is not enough: the
70    // PROCESS must enable it in its own token (AdjustTokenPrivileges) before VirtualAlloc, or the call fails.
71    // An account without the assignment, or a failure to enable, leaves the process as it was: VirtualAlloc
72    // then refuses and the 4 KB fallback below runs - that is the EXPECTED outcome on a desktop.
73    {
74        HANDLE tok = nullptr;
75        if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tok)) {
76            TOKEN_PRIVILEGES tp{};
77            tp.PrivilegeCount = 1;
78            if (LookupPrivilegeValueW(nullptr, L"SeLockMemoryPrivilege", &tp.Privileges[0].Luid)) {
79                tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
80                if (!AdjustTokenPrivileges(tok, FALSE, &tp, 0, nullptr, nullptr) && GetLastError() != ERROR_NOT_ALL_ASSIGNED)
81                    (void) 0;   // nothing actionable: the large-page attempt below reports the outcome
82            }
83            CloseHandle(tok);
84        }
85    }
86    // MEM_LARGE_PAGES needs SeLockMemoryPrivilege; a normal account does not have it and VirtualAlloc then
87    // fails with ERROR_PRIVILEGE_NOT_HELD.  That is the EXPECTED outcome on a desktop, not an error.
88    SIZE_T large = GetLargePageMinimum();
89    // A/B switch: STRATA_NO_LARGEPAGES=1 skips the large-page attempt, same run, same boot.
90    if (large > 0 && std::getenv("STRATA_NO_LARGEPAGES") == nullptr) {
91        // MEM_LARGE_PAGES requires the allocation size to be an exact multiple of the large page size -
92        // anything else is ERROR_INVALID_PARAMETER (87), which reads like a privilege problem but is not.
93        // Round up: the slack is under 2 MB and the tail stays unused.
94        const SIZE_T lbytes = (SIZE_T) (((SIZE_T) bytes + large - 1) / large * large);
95        void* p = VirtualAlloc(nullptr, lbytes, MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES,
96                               PAGE_READWRITE);
97        if (p) {
98            got = PageBacking::LargePages;
99            note = "large pages (" + std::to_string((unsigned long long) large) + " B)";
100            return p;
101        }
102        // 1450 (ERROR_NO_SYSTEM_RESOURCES) is the large-page pool saying no, 87 is a size that is not a
103        // multiple of the minimum, 1314 is the privilege: without the byte count the three read as one bug.
104        note = "large pages refused for " + std::to_string((unsigned long long) lbytes) + " B (GetLargePageMinimum=" +
105               std::to_string((unsigned long long) large) + ", VirtualAlloc error " +
106               std::to_string((unsigned long long) GetLastError()) + "); using 4 KB pages";
107    } else if (std::getenv("STRATA_NO_LARGEPAGES") != nullptr) {
108        note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages";
109    } else {
110        note = "this system has no large-page minimum; using 4 KB pages";
111    }
112    void* p = VirtualAlloc(nullptr, (SIZE_T) bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
113    got = PageBacking::NormalPages;
114    return p;
115#else
116    if (!shared_file.empty()) {
117        if (shared_pack_hash == 0) {
118            note = "shared arena requires a nonzero pack hash";
119            return nullptr;
120        }
121        if (bytes > UINT64_MAX - kSharedArenaHeaderBytes) {
122            note = "shared arena size overflows its header";
123            return nullptr;
124        }
125        const uint64_t file_bytes = kSharedArenaHeaderBytes + bytes;
126        const int fd = open(shared_file.c_str(), O_RDWR | O_CREAT | O_CLOEXEC, 0600);
127        if (fd < 0) {
128            note = "cannot open shared arena " + shared_file + ": " + std::strerror(errno);
129            return nullptr;
130        }
131        struct stat st{};
132        if (fstat(fd, &st) != 0) {
133            const int e = errno;
134            close(fd);
135            note = "cannot stat shared arena " + shared_file + ": " + std::strerror(e);
136            return nullptr;
137        }
138
139        const bool fresh = st.st_size == 0;
140        if (fresh) {
141            if (ftruncate(fd, (off_t) file_bytes) != 0) {
142                const int e = errno;
143                close(fd);
144                note = "cannot size shared arena " + shared_file + ": " + std::strerror(e);
145                return nullptr;
146            }
147            SharedArenaHeader hdr{};
148            std::memcpy(hdr.magic, kSharedArenaMagic, sizeof hdr.magic);
149            hdr.version = 1;
150            hdr.header_bytes = (uint32_t) kSharedArenaHeaderBytes;
151            hdr.arena_bytes = bytes;
152            hdr.pack_hash = shared_pack_hash;
153            const ssize_t written = pwrite(fd, &hdr, sizeof hdr, 0);
154            if (written != (ssize_t) sizeof hdr) {
155                const int e = errno;
156                close(fd);
157                note = "cannot write shared arena header " + shared_file + ": " +
158                       (written < 0 ? std::string(std::strerror(e)) : std::string("short write"));
159                return nullptr;
160            }
161        } else {
162            if (st.st_size < 0 || (uint64_t) st.st_size != file_bytes) {
163                close(fd);
164                note = "shared arena " + shared_file + " is " +
165                       std::to_string((unsigned long long) st.st_size) + " B, expected " +
166                       std::to_string((unsigned long long) file_bytes) + " B including its header";
167                return nullptr;
168            }
169            SharedArenaHeader hdr{};
170            const ssize_t got_header = pread(fd, &hdr, sizeof hdr, 0);
171            if (got_header != (ssize_t) sizeof hdr ||
172                std::memcmp(hdr.magic, kSharedArenaMagic, sizeof hdr.magic) != 0 ||
173                hdr.version != 1 || hdr.header_bytes != kSharedArenaHeaderBytes || hdr.arena_bytes != bytes) {
174                close(fd);
175                note = "shared arena " + shared_file + " has an incompatible or missing header";
176                return nullptr;
177            }
178            if (hdr.pack_hash != shared_pack_hash) {
179                close(fd);
180                char b[256];
181                std::snprintf(b, sizeof b,
182                              "shared arena %s was written for pack hash %016llx, expected %016llx",
183                              shared_file.c_str(), (unsigned long long) hdr.pack_hash,
184                              (unsigned long long) shared_pack_hash);
185                note = b;
186                return nullptr;
187            }
188        }
189
190        void* map = mmap(nullptr, (size_t) file_bytes, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
191        const int e = errno;
192        close(fd);
193        if (map == MAP_FAILED) {
194            note = "cannot map shared arena " + shared_file + ": " + std::strerror(e);
195            return nullptr;
196        }
197        mapping_base = map;
198        mapping_bytes = file_bytes;
199        got = PageBacking::NormalPages;
200        note = "MAP_SHARED file " + shared_file + " (pack hash checked)";
201        return (uint8_t*) map + kSharedArenaHeaderBytes;
202    }
203
204    // STRATA_NO_LARGEPAGES=1 is the same-run A/B switch the Windows branch documents; honor it
205    // here too, so the large-page path can be compared without changing the pool or rebooting.
206    if (std::getenv("STRATA_NO_LARGEPAGES") != nullptr) {
207        note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages";
208    } else {
209        void* p = mmap(nullptr, bytes, PROT_READ | PROT_WRITE,
210                       MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB, -1, 0);
211        if (p != MAP_FAILED) {
212            got = PageBacking::LargePages;
213            note = "hugetlb 2 MB pages";
214            return p;
215        }
216        // MAP_HUGETLB is all-or-nothing: a pool smaller than the mapping fails exactly like an absent
217        // one, and the old message guessed "no hugetlb pool configured" either way. Name the shortfall:
218        // how many 2 MiB pages the mapping needs against what vm.nr_hugepages actually holds.
219        const unsigned long long need = ((unsigned long long) bytes + (1ull << 21) - 1) / (1ull << 21);
220        unsigned long long pool = 0;
221        bool have_pool = false;
222        if (std::FILE* f = std::fopen("/proc/sys/vm/nr_hugepages", "r")) {
223            have_pool = std::fscanf(f, "%llu", &pool) == 1;
224            std::fclose(f);
225        }
226        note = "MAP_HUGETLB unavailable (needed " + std::to_string(need) + " 2 MiB pages, vm.nr_hugepages=" +
227               (have_pool ? std::to_string(pool) : std::string("?")) + "); using 4 KB pages";
228    }
229    // No hugetlb mapping: a 2 MiB-aligned anonymous mapping with MADV_HUGEPAGE, so transparent huge pages back
230    // it where THP is "madvise" (the common distro default). The CPU expert pool streams whole experts out of
231    // this arena; with 4 KB pages every 3 MB expert costs ~750 TLB misses.
232    constexpr uint64_t kAlign = 2ull << 20;
233    const uint64_t padded = bytes + kAlign;
234    void* raw = mmap(nullptr, padded, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
235    got = PageBacking::NormalPages;
236    if (raw == MAP_FAILED) return nullptr;
237    const uintptr_t start = (uintptr_t) raw;
238    const uintptr_t aligned = (start + kAlign - 1) & ~(uintptr_t) (kAlign - 1);
239    if (aligned > start) munmap(raw, aligned - start);
240    const uintptr_t end = aligned + bytes, raw_end = start + padded;
241    if (raw_end > end) munmap((void*) end, raw_end - end);
242    void* p = (void*) aligned;
243    // #771: with THP "always" the kernel already backs this mapping with huge pages where it can; the extra
244    // MADV_HUGEPAGE only adds direct reclaim and compaction on every fault (defrag=madvise), which on a fragmented
245    // machine stretched a 25 s start to 432 s.  So it is not asked for there.  STRATA_NO_ARENA_THP=1 skips it
246    // anywhere (the request alone; STRATA_NO_LARGEPAGES also skips the hugetlb try).
247    std::string thp_mode;
248    if (std::FILE* f = std::fopen("/sys/kernel/mm/transparent_hugepage/enabled", "r")) {
249        char line[128] = {0};
250        if (std::fgets(line, sizeof line, f) != nullptr) {
251            const char* open = std::strchr(line, '[');
252            const char* close = open ? std::strchr(open, ']') : nullptr;
253            if (open && close) thp_mode.assign(open + 1, close);
254        }
255        std::fclose(f);
256    }
257    // STRATA_NO_ARENA_THP=0 asks for the huge pages (the same meaning as in src/core/pinned.cu); any other value skips the request
258    const char* no_thp = std::getenv("STRATA_NO_ARENA_THP");
259    const bool user_no_thp = no_thp != nullptr && no_thp[0] != '0';
260    const bool skip_thp_request = user_no_thp || thp_mode == "always";
261    if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && skip_thp_request) {
262        const std::string four_k = "; using 4 KB pages";
263        if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0)
264            note.resize(note.size() - four_k.size());
265        note += user_no_thp
266                    ? "; transparent huge pages skipped (STRATA_NO_ARENA_THP)"
267                    : "; transparent huge pages are on for every mapping (THP always): MADV_HUGEPAGE not requested";
268    } else if (std::getenv("STRATA_NO_LARGEPAGES") == nullptr && madvise(p, bytes, MADV_HUGEPAGE) == 0) {
269        const std::string four_k = "; using 4 KB pages";
270        if (note.size() >= four_k.size() && note.compare(note.size() - four_k.size(), four_k.size(), four_k) == 0)
271            note.resize(note.size() - four_k.size());
272        note += "; transparent huge pages requested (MADV_HUGEPAGE)";
273    }
274    return p;
275#endif
276}
277
278void release(void* p, uint64_t bytes) {
279    if (!p) return;
280#ifdef _WIN32
281    (void) bytes;
282    VirtualFree(p, 0, MEM_RELEASE);
283#else
284    munmap(p, bytes);
285#endif
286}
287
288}  // namespace
289
290uint64_t fnv1a64(const uint8_t* p, uint64_t n, uint64_t seed) {
291    uint64_t h = seed;
292    for (uint64_t i = 0; i < n; ++i) {
293        h ^= p[i];
294        h *= 1099511628211ull;
295    }
296    return h;
297}
298
299namespace {
300/*
301DPCT1010: SYCL uses exceptions to report errors and does not use the error
302codes. The cudaGetLastError function call was replaced with 0. You need to
303rewrite this code.
304*/
305bool clear_error() {(void)0; return true; }
306}  // namespace
307
308int arena_pin_cap_gib() {
309    const char* e = std::getenv("STRATA_ARENA_PIN_GIB");
310    if (e == nullptr || *e == '\0') return -1;
311    if (std::string(e) == "auto") return -2;   // #243: the Windows shared-memory budget sets the sliced pin's cap
312    const int v = std::atoi(e);
313    return v < 0 ? -1 : v;
314}
315
316namespace {
317#ifdef _WIN32
318// #243: how much of the arena the sliced registration may pin on Windows when the whole arena was refused.
319// Page-locked memory the GPU maps is charged to its shared (non-local) WDDM segment; pinned slice by slice until
320// the driver refused one (28 GiB of a 63 GB PC), that segment was left full and every later cudaMalloc failed
321// "out of memory".  4 GiB of the budget stay free for what the engine allocates after the arena; without the DXGI
322// numbers, RAM/2 - 8 GiB (the budget is about half the RAM).  False: no limit could be worked out.
323bool sliced_pin_limit(uint64_t& limit, std::string& why) {
324    constexpr uint64_t GiB = 1ull << 30;
325    char buf[256];
326    int dev = 0;
327    cudaDeviceProp p{};
328    uint64_t budget = 0, usage = 0;
329    std::string err = "no CUDA device properties";
330    if (cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&p, dev) == cudaSuccess &&
331        strata::platform::gpu_shared_memory_budget(p.luid, budget, usage, err)) {
332        limit = budget > usage + 4 * GiB ? budget - usage - 4 * GiB : 0;
333        std::snprintf(buf, sizeof buf, "the GPU's shared-memory budget %.1f GiB - %.1f GiB in use - 4 GiB",
334                      (double) budget / GiB, (double) usage / GiB);
335        why = buf;
336        return true;
337    }
338    (void) cudaGetLastError();
339    const uint64_t ram = strata::platform::total_physical_memory();
340    if (ram == 0) return false;
341    limit = ram / 2 > 8 * GiB ? ram / 2 - 8 * GiB : 0;
342    std::snprintf(buf, sizeof buf, "%s: RAM/2 - 8 GiB of %.1f GiB", err.c_str(), (double) ram / GiB);
343    why = buf;
344    return true;
345}
346#endif
347}  // namespace
348
349namespace {
350std::vector<uint64_t> uniform_bounds(uint64_t bytes, uint64_t slice) {
351    std::vector<uint64_t> b;
352    if (slice == 0) return b;
353    for (uint64_t off = 0; off + slice <= bytes; off += slice) b.push_back(off);
354    if (!b.empty()) b.push_back(b.back() + slice);
355    return b;
356}
357}  // namespace
358
359PinnedArena::PinnedArena(uint64_t bytes, uint64_t slice) : PinnedArena(bytes, uniform_bounds(bytes, slice)) {
360    if (slice_bytes) slice_bytes = slice;   // sliced registration: record the uniform size
361}
362
363PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t> &bounds,
364                         uint64_t max_pinned_bytes,
365                         const std::string &shared_file,
366                         uint64_t shared_pack_hash) try
367    : capacity(bytes) {
368    if (bytes == 0) return;
369    base = reserve(bytes, backing, note, shared_file, shared_pack_hash, mapping_base, mapping_bytes);
370    if (base != nullptr && mapping_base == nullptr) {
371        mapping_base = base;
372        mapping_bytes = bytes;
373    }
374
375    // Register with CUDA BEFORE any page is touched: cudaHostRegister pins what is resident now, and a region
376    // that has already been faulted in page by page is far more expensive to register and may fail outright.
377    if (base) {
378        // #243: STRATA_ARENA_PIN_GIB=N caps the registration from the start where the caller set no cap
379        const int env_gib = arena_pin_cap_gib();
380        uint64_t cap = max_pinned_bytes;
381        std::string cap_why = "by the engine (multi-GPU under WDDM, or remote experts)";
382        if (cap == 0 && env_gib > 0) {
383            cap = (uint64_t) env_gib << 30;
384            cap_why = "by STRATA_ARENA_PIN_GIB";
385        }
386        const bool capped = cap > 0 && cap < bytes && bounds.size() >= 2;
387        const dpct::err0 e =
388            capped ? 0 :
389                   /*
390                   DPCT1027: The call to cudaHostRegister was replaced with
391                   0 because SYCL currently does not support registering of
392                   existing host memory for use by device. Use USM to allocate
393                   memory for use by host and device.
394                   */
395                0;
396        if (!capped && e == 0) {
397            note = "cudaHostRegister PORTABLE ok; " + note;
398            registered_bytes = bytes;
399        } else if (bounds.size() >= 2 && (capped || clear_error())) {
400            // Plan v0.3 P5: the whole range is refused, so pin it slice by slice from the start.  The rest stays
401            // resident through the working-set lock below.  (P6: slices may differ in size, one per layer.)
402            slice_bytes = 1;   // sliced; the uniform constructor records the size
403            bool limited = capped;
404            uint64_t limit = cap;
405            std::string limit_why;
406#ifdef _WIN32
407            // #243 (opt-in, STRATA_ARENA_PIN_GIB=auto): not up to the driver's refusal but below the shared-memory
408            // budget, for a PC where the full sliced pin leaves WDDM refusing later allocations.  Not the default: a
409            // 64 GB PC pins 30 GiB past that budget without trouble, and capping it at 26 cost ~20% prompt speed.
410            if (!capped && env_gib == -2) limited = sliced_pin_limit(limit, limit_why);
411#endif
412            for (size_t i = 0; i + 1 < bounds.size(); ++i) {
413                const uint64_t off = bounds[i], n = bounds[i + 1] - bounds[i];
414                if (limited && (off > limit || n > limit - off)) break;
415                /*
416                DPCT1027: The call to cudaHostRegister was replaced with 0
417                because SYCL currently does not support registering of existing
418                host memory for use by device. Use USM to allocate memory for
419                use by host and device.
420                */
421                if (0 != 0) {
422                    /*
423                    DPCT1010: SYCL uses exceptions to report errors and
424                    does not use the error codes. The cudaGetLastError function
425                    call was replaced with 0. You need to rewrite this code.
426                    */
427                    (void)0;
428                    break;
429                }
430                slice_starts.push_back(off);
431                registered_bytes = off + n;
432                ++registered_slices;
433            }
434            char gib[32];
435            std::snprintf(gib, sizeof gib, "%.1f", (double) limit / (double) (1ull << 30));
436            note =
437                (capped
438                     ? "cudaHostRegister limited to " +
439                           std::to_string(cap >> 30) + " GiB " + cap_why + "; "
440                     :
441                     /*
442                     DPCT1009: SYCL reports errors using exceptions and
443                     does not use error codes. Please replace the
444                     "get_error_string_dummy(...)" with a real error-handling
445                     function.
446                     */
447                     "cudaHostRegister of the whole arena FAILED (" +
448                         std::string(dpct::get_error_string_dummy(e)) + "); " +
449                         (limited ? "slices capped at " + std::string(gib) +
450                                        " GiB (" + limit_why +
451                                        "; STRATA_ARENA_PIN_GIB=auto; N sets a "
452                                        "cap; #243); "
453                                  : std::string())) +
454                std::to_string(registered_slices) + " slices pinned (" +
455                std::to_string(registered_bytes >> 30) + " GiB); " + note;
456            if (registered_bytes < bytes) {
457                const char* env = std::getenv("STRATA_ARENA_LOCK");
458                if (backing == PageBacking::LargePages) {   // #779: large pages cannot be paged out: nothing to lock
459                    note = "large pages are resident without a lock; " + note;
460                } else if (env == nullptr || std::string(env) != "0") {
461                    const strata::platform::LockResult lr =
462                        strata::platform::lock_resident((uint8_t*) base + registered_bytes, bytes - registered_bytes);
463                    locked_bytes = lr.locked_bytes;
464                    note = lr.note + "; " + note;
465                }
466            }
467        } else {
468            /*
469            DPCT1009: SYCL reports errors using exceptions and does not use
470            error codes. Please replace the "get_error_string_dummy(...)" with a
471            real error-handling function.
472            */
473            note = std::string("cudaHostRegister FAILED (") +
474                   dpct::get_error_string_dummy(e) +
475                   ") - the arena is NOT pinned, so copies will be slow; " +
476                   note;
477            // **CONSUME THE ERROR, OR IT LIES ABOUT SOMETHING ELSE LATER.**
478            //
479            // `cudaGetLastError()` returns the last error and CLEARS it; until something reads it, the error
480            // state is sticky.  This failure is caught and handled right here - the arena is simply not pinned -
481            // but leaving it set meant the next `cudaGetLastError()` in the engine, which is `gr_read`'s launch
482            // check, reported "out of memory" for kernels that allocate nothing.  That cost a round: the arena
483            // was written off as not fitting the machine when in fact the only thing wrong was a stale error
484            // from this line.
485            //
486            // It is the same trap `gr.cu` warns about for ASYNC faults, in the other direction: a synchronous
487            // failure is sticky too, and it lies about where it happened just as convincingly.
488            /*
489            DPCT1010: SYCL uses exceptions to report errors and does not
490            use the error codes. The cudaGetLastError function call was replaced
491            with 0. You need to rewrite this code.
492            */
493            (void)0;
494            // Plan v0.3 P0.1: keep it RESIDENT instead. Unpinned, Windows trims the arena under memory pressure
495            // and the CPU pool's rate then depends on the OS; locking it through the working set needs no
496            // special privilege. STRATA_ARENA_LOCK=0 is the A/B arm.
497            const char* env = std::getenv("STRATA_ARENA_LOCK");
498            if (backing == PageBacking::LargePages) {       // #779: large pages cannot be paged out: nothing to lock
499                note = "large pages are resident without a lock; " + note;
500            } else if (env == nullptr || std::string(env) != "0") {
501                const strata::platform::LockResult lr = strata::platform::lock_resident(base, bytes);
502                locked_bytes = lr.locked_bytes;
503                note = lr.note + "; " + note;
504            } else {
505                note = "arena lock disabled (STRATA_ARENA_LOCK=0); " + note;
506            }
507        }
508    }
509}
510catch (sycl::exception const &exc) {
511  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
512            << ", line:" << __LINE__ << std::endl;
513  std::exit(1);
514}
515
516PinnedArena::PinnedArena(uint64_t bytes, const std::vector<uint64_t>& bounds, Deferred)
517    : capacity(bytes), bounds_(bounds) {
518    if (bytes == 0 || bounds.size() < 2) return;
519    base = reserve(bytes, backing, note, std::string{}, 0, mapping_base, mapping_bytes);
520    if (base != nullptr && mapping_base == nullptr) {
521        mapping_base = base;
522        mapping_bytes = bytes;
523    }
524    slice_bytes = 1;   // sliced: one registration per layer
525}
526
527void PinnedArena::register_slices(std::atomic<int> &ready) try {
528    const int n = (int) bounds_.size() - 1;
529    int i = 0;
530    for (; base != nullptr && i < n; ++i) {
531        const uint64_t off = bounds_[(size_t) i], len = bounds_[(size_t) i + 1] - off;
532        /*
533        DPCT1027: The call to cudaHostRegister was replaced with 0 because
534        SYCL currently does not support registering of existing host memory for
535        use by device. Use USM to allocate memory for use by host and device.
536        */
537        if (0 != 0) {
538            /*
539            DPCT1010: SYCL uses exceptions to report errors and does not use
540            the error codes. The cudaGetLastError function call was replaced
541            with 0. You need to rewrite this code.
542            */
543            (void)0;
544            break;
545        }
546        slice_starts.push_back(off);
547        registered_bytes = off + len;
548        ++registered_slices;
549        ready.store(i + 1, std::memory_order_release);
550    }
551    note = "cudaHostRegister per layer, pipelined with the load: " + std::to_string(registered_slices) + " of " +
552           std::to_string(n) + " slices pinned; " + note;
553    if (i < n && base != nullptr) {   // the rest stays resident through the working-set lock, as the sliced fallback does
554        const char* env = std::getenv("STRATA_ARENA_LOCK");
555        if (backing == PageBacking::LargePages) {           // #779: large pages cannot be paged out: nothing to lock
556            note = "large pages are resident without a lock; " + note;
557        } else if (env == nullptr || std::string(env) != "0") {
558            const strata::platform::LockResult lr =
559                strata::platform::lock_resident((uint8_t*) base + registered_bytes, capacity - registered_bytes);
560            locked_bytes = lr.locked_bytes;
561            note = lr.note + "; " + note;
562        }
563    }
564    ready.store(INT_MAX, std::memory_order_release);   // every slice done (or given up on)
565}
566catch (sycl::exception const &exc) {
567  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
568            << ", line:" << __LINE__ << std::endl;
569  std::exit(1);
570}
571
572PinnedArena::~PinnedArena() {
573    if (base) {
574        if (locked_bytes) strata::platform::unlock_resident((uint8_t*) base + (slice_bytes ? registered_bytes : 0), locked_bytes);
575        if (slice_bytes) {
576            /*
577            DPCT1027: The call to cudaHostUnregister was replaced with 0
578            because SYCL currently does not support registering of existing host
579            memory for use by device. Use USM to allocate memory for use by host
580            and device.
581            */
582            for (uint64_t off : slice_starts) 0;
583        } else {
584            /*
585            DPCT1026: The call to cudaHostUnregister was removed because
586            SYCL currently does not support registering of existing host memory
587            for use by device. Use USM to allocate memory for use by host and
588            device.
589            */
590        }
591        release(mapping_base ? mapping_base : base, mapping_bytes ? mapping_bytes : capacity);
592        base = nullptr;
593        mapping_base = nullptr;
594        mapping_bytes = 0;
595    }
596}
597
598LoadStats load_experts(const std::string& path, uint8_t* dst, uint64_t blob_bytes, uint64_t blobs_per_layer,
599                       uint64_t layers, int threads, uint64_t chunk) {
600    std::vector<uint64_t> off((size_t) layers), n((size_t) layers, blobs_per_layer * blob_bytes);
601    for (uint64_t L = 0; L < layers; ++L) off[(size_t) L] = L * blobs_per_layer * blob_bytes;
602    return load_experts_ranges(path, dst, off, n, threads, chunk);
603}
604
605LoadStats load_experts_direct(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,
606                              const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk,
607                              const std::atomic<int>* ready) {
608    LoadStats st;
609    st.ok = false;
610#ifdef _WIN32
611    constexpr uint64_t kAlign = 4096;
612    if (((uintptr_t) dst % kAlign) != 0 || chunk == 0 || chunk % kAlign != 0) return st;
613    struct Piece { uint64_t off, n; int layer; };
614    std::vector<Piece> pieces;
615    uint64_t bytes = 0;
616    for (size_t L = 0; L < layer_off.size(); ++L) {
617        if (layer_off[L] % kAlign != 0 || layer_bytes[L] % kAlign != 0) return st;
618        for (uint64_t p = 0; p < layer_bytes[L]; p += chunk)
619            pieces.push_back({layer_off[L] + p, std::min<uint64_t>(chunk, layer_bytes[L] - p), (int) L});
620        bytes += layer_bytes[L];
621    }
622    if (threads < 1) threads = 1;
623    const auto t0 = std::chrono::steady_clock::now();
624    std::atomic<size_t> next{0};
625    std::mutex err_mu;
626    std::string err;
627    const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
628    std::vector<wchar_t> wpath((size_t) (std::max)(wide, 1), L'\0');
629    if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);
630    auto worker = [&]() {
631        HANDLE h = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,
632                               FILE_FLAG_NO_BUFFERING | FILE_FLAG_SEQUENTIAL_SCAN, nullptr);
633        if (h == INVALID_HANDLE_VALUE) {
634            std::lock_guard<std::mutex> g(err_mu);
635            if (err.empty())
636                err = "cannot open " + path + " unbuffered (error " + std::to_string((unsigned long long) GetLastError()) + ")";
637            next = pieces.size();
638            return;
639        }
640        for (;;) {
641            const size_t i = next.fetch_add(1);
642            if (i >= pieces.size()) break;
643            if (ready != nullptr)      // the slice must be registered before its pages are touched
644                while (ready->load(std::memory_order_acquire) <= pieces[i].layer + 1) std::this_thread::yield();
645            OVERLAPPED ov{};
646            ov.Offset = (DWORD) pieces[i].off;
647            ov.OffsetHigh = (DWORD) (pieces[i].off >> 32);
648            DWORD got = 0;
649            if (!ReadFile(h, dst + pieces[i].off, (DWORD) pieces[i].n, &got, &ov) || got != pieces[i].n) {
650                std::lock_guard<std::mutex> g(err_mu);
651                if (err.empty())
652                    err = "short unbuffered read at offset " + std::to_string(pieces[i].off) + ": got " + std::to_string(got) +
653                          " of " + std::to_string(pieces[i].n) + " B (error " +
654                          std::to_string((unsigned long long) GetLastError()) + ")";
655                next = pieces.size();
656                break;
657            }
658        }
659        CloseHandle(h);
660    };
661    std::vector<std::thread> pool;
662    for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
663    worker();
664    for (auto& t : pool) t.join();
665    st.layers = layer_off.size();
666    if (!err.empty()) {
667        st.seconds = -1.0;
668        st.error = err;
669        return st;
670    }
671    st.ok = true;
672    st.bytes = bytes;
673    st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
674#else
675    (void) path; (void) dst; (void) layer_off; (void) layer_bytes; (void) threads; (void) chunk; (void) ready;
676#endif
677    return st;
678}
679
680bool experts_unbuffered(const std::vector<std::string>& files, uint64_t arena_bytes, std::string& why,
681                        bool cache_counts, uint64_t read_bytes) {
682    const char* env = std::getenv("STRATA_UNBUFFERED_LOAD");
683    if (env != nullptr && env[0] != '\0') {
684        why = std::string("STRATA_UNBUFFERED_LOAD=") + env;
685        return env[0] != '0';
686    }
687#ifdef _WIN32
688    LARGE_INTEGER freq{}, a{}, b{};
689    QueryPerformanceFrequency(&freq);
690    constexpr DWORD kRead = 64 << 10;
691    constexpr int kSamples = 16;
692    std::vector<uint8_t> buf(kRead);
693    uint64_t total_bytes = 0;
694    int fast = 0, n = 0;
695    uint64_t seed = (uint64_t) GetTickCount64() * 6364136223846793005ull + 1442695040888963407ull;
696    for (const std::string& f : files) {
697        const int wide = MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, nullptr, 0);
698        std::vector<wchar_t> w((size_t) (std::max)(wide, 1), L'\0');
699        if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, f.c_str(), -1, w.data(), wide);
700        HANDLE h = CreateFileW(w.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS,
701                               nullptr);
702        if (h == INVALID_HANDLE_VALUE) continue;
703        LARGE_INTEGER size{};
704        GetFileSizeEx(h, &size);
705        total_bytes += (uint64_t) size.QuadPart;
706        // random offsets: a probe must not find the blocks an earlier probe put into the cache
707        for (int i = 0; i < kSamples && (uint64_t) size.QuadPart > 2ull * kRead; ++i) {
708            seed = seed * 6364136223846793005ull + 1442695040888963407ull;
709            const uint64_t off = ((seed >> 17) % ((uint64_t) size.QuadPart - kRead)) / kRead * kRead;
710            OVERLAPPED ov{};
711            ov.Offset = (DWORD) off;
712            ov.OffsetHigh = (DWORD) (off >> 32);
713            DWORD got = 0;
714            QueryPerformanceCounter(&a);
715            const BOOL ok = ReadFile(h, buf.data(), kRead, &got, &ov);
716            QueryPerformanceCounter(&b);
717            if (!ok) continue;
718            ++n;
719            fast += (double) (b.QuadPart - a.QuadPart) * 1e6 / (double) freq.QuadPart < 30.0;
720        }
721        CloseHandle(h);
722    }
723    const bool cached = n > 0 && fast * 4 >= n * 3;
724    MEMORYSTATUSEX ms{};
725    ms.dwLength = sizeof ms;
726    GlobalMemoryStatusEx(&ms);
727    const uint64_t avail = ms.ullAvailPhys;
728    // what the cache could keep beside the arena (~4 GiB for everything else)
729    const uint64_t need = read_bytes == kAllFileBytes ? total_bytes : read_bytes;
730    const bool keepable = strata::platform::file_cache_keeps(avail, arena_bytes, need);
731    char msg[256];
732    if (read_bytes == kAllFileBytes)
733        std::snprintf(msg, sizeof msg, "%d of %d probe reads from the file cache; %.1f GiB available, %.1f GiB of files",
734                      fast, n, (double) avail / (1ull << 30), (double) total_bytes / (1ull << 30));
735    else
736        std::snprintf(msg, sizeof msg, "%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB "
737                      "of experts read from the files: the file cache %s keep them",
738                      (double) avail / (1ull << 30), (double) arena_bytes / (1ull << 30), (double) need / (1ull << 30),
739                      keepable ? "can" : "cannot");
740    why = msg;
741    return (!cached || !cache_counts) && !keepable;
742#else
743    (void) files; (void) arena_bytes; (void) cache_counts; (void) read_bytes;
744    why = "buffered (not Windows)";
745    return false;
746#endif
747}
748
749LoadStats load_experts_ranges(const std::string& path, uint8_t* dst, const std::vector<uint64_t>& layer_off,
750                              const std::vector<uint64_t>& layer_bytes, int threads, uint64_t chunk,
751                              const std::atomic<int>* ready) {
752    LoadStats st;
753    const uint64_t layers = (uint64_t) layer_off.size();
754    st.layers = layers;
755    st.bytes = 0;
756    for (uint64_t b : layer_bytes) st.bytes += b;
757    if (threads < 1) threads = 1;
758
759    const auto t0 = std::chrono::steady_clock::now();
760    std::vector<uint64_t> layer_hash((size_t) layers, 1469598103934665603ull);
761    std::atomic<uint64_t> next_layer{0};
762    std::atomic<uint64_t> read_ns_sum{0};   // summed over the threads: see LoadStats::read_seconds
763    std::atomic<uint64_t> copy_ns_sum{0};
764    std::mutex err_mu;
765    std::string err;
766
767    auto worker = [&]() {
768        std::vector<uint8_t> buf((size_t) chunk);
769        // One handle per thread, seeked once per layer: a shared handle would need a lock around the seek and
770        // would serialise the very thing the threads are here to parallelise.  `fread` on a `FILE*` rather than
771        // `std::ifstream`: see the header - MSVC's `basic_filebuf::xsgetn` splits any request larger than
772        // `_INTERNAL_BUFSIZ - 1` into 4095-byte freads, which turned one 8 MiB chunk into ~2048 4 KiB reads.
773        // `fread` sees a request bigger than the stream buffer and passes it to `_read()`/
774        // `ReadFile()` unchanged, so the chunk size reaches the disk.  Buffered, not `FILE_FLAG_NO_BUFFERING`:
775        // the cache should still hold what it can.
776        FILE* f = std::fopen(path.c_str(), "rb");
777        if (f == nullptr) {
778            std::lock_guard<std::mutex> g(err_mu);
779            err = "cannot open " + path;
780            return;
781        }
782        // A `FILE*` has no destructor that closes it, and this function has early returns below (open, seek and
783        // short-read failures), so the guard is what keeps the closing correct on every path.
784        struct Closer {
785            FILE* f;
786            ~Closer() { if (f != nullptr) std::fclose(f); }
787        } closer{f};
788        uint64_t read_ns = 0, copy_ns = 0;
789        for (;;) {
790            const uint64_t L = next_layer.fetch_add(1);
791            if (L >= layers) break;
792            if (ready != nullptr)      // the slice must be registered before its pages are touched
793                while (ready->load(std::memory_order_acquire) <= (int) L + 1) std::this_thread::yield();
794            const uint64_t off = layer_off[(size_t) L];
795            uint64_t remaining = layer_bytes[(size_t) L];
796            uint64_t pos = 0;
797            uint64_t h = 1469598103934665603ull;
798            // 64-bit seek: the pack is 42.9 GB, so the 32-bit `fseek` would wrap past 4 GiB
799            if (STRATA_FSEEK64(f, off) != 0) {
800                std::lock_guard<std::mutex> g(err_mu);
801                err = "seek to " + std::to_string(off) + " B failed in layer " + std::to_string(L);
802                return;
803            }
804            while (remaining > 0) {
805                const uint64_t n = remaining < chunk ? remaining : chunk;
806                const auto t_read = std::chrono::steady_clock::now();
807                const size_t got = std::fread(buf.data(), 1, (size_t) n, f);
808                read_ns += (uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds>(
809                               std::chrono::steady_clock::now() - t_read).count();
810                // A short read is EOF or an I/O error, never a silent zero fill: say WHERE and HOW SHORT, and
811                // keep going no further - the caller turns this into a refused load, not a wrong answer.
812                if (got != (size_t) n) {
813                    std::lock_guard<std::mutex> g(err_mu);
814                    err = "short read in layer " + std::to_string(L) + ": got " + std::to_string(got) + " of "
815                          + std::to_string(n) + " B at offset " + std::to_string(off + pos)
816                          + (std::ferror(f) != 0 ? " (ferror set)" : "");
817                    return;
818                }
819                const auto t_copy = std::chrono::steady_clock::now();
820                std::memcpy(dst + off + pos, buf.data(), (size_t) n);
821                h = fnv1a64(buf.data(), n, h);
822                copy_ns += (uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds>(
823                               std::chrono::steady_clock::now() - t_copy).count();
824                pos += n;
825                remaining -= n;
826            }
827            layer_hash[(size_t) L] = h;
828        }
829        read_ns_sum.fetch_add(read_ns);
830        copy_ns_sum.fetch_add(copy_ns);
831    };
832
833    std::vector<std::thread> pool;
834    for (int i = 1; i < threads; ++i) pool.emplace_back(worker);
835    worker();
836    for (auto& t : pool) t.join();
837
838    if (!err.empty()) {
839        std::fprintf(stderr, "load_experts: %s\n", err.c_str());
840        st.seconds = -1.0;
841        st.ok = false;
842        st.error = err;
843        return st;
844    }
845    st.read_seconds = (double) read_ns_sum.load() / 1e9;
846    st.copy_seconds = (double) copy_ns_sum.load() / 1e9;
847    st.layer_checksums = std::move(layer_hash);
848    st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
849    return st;
850}
851
852StreamStats stream_bandwidth(const uint8_t *src, uint64_t bytes, uint64_t chunk,
853                             int iters) try {
854    StreamStats st;
855    st.bytes = bytes * (uint64_t) iters;
856    st.chunk = chunk;
857    uint8_t* dst = nullptr;
858    dpct::queue_ptr s{};
859    if (DPCT_CHECK_ERROR(dst = (uint8_t *)sycl::malloc_device(
860                             (size_t)chunk, dpct::get_in_order_queue())) != 0) {
861        std::fprintf(stderr, "stream_bandwidth: cudaMalloc failed for %llu B\n", (unsigned long long) chunk);
862        st.seconds = -1.0;
863        return st;
864    }
865    s = dpct::get_current_device().create_queue(true);
866
867    // one untimed pass so the first transfer's page-fault and setup cost is not in the measurement
868    for (uint64_t off = 0; off + chunk <= bytes; off += chunk) {
869        /*
870        DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API.
871        While the origin API might be synchronous, it depends on the type of
872        operand memory, so you may need to call wait() on event return by memcpy
873        API to ensure synchronization behavior.
874        */
875        s->memcpy(dst, src + off, (size_t)chunk);
876    }
877    s->wait();
878
879    const auto t0 = std::chrono::steady_clock::now();
880    for (int it = 0; it < iters; ++it) {
881        for (uint64_t off = 0; off + chunk <= bytes; off += chunk) {
882            /*
883            DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy
884            API. While the origin API might be synchronous, it depends on the
885            type of operand memory, so you may need to call wait() on event
886            return by memcpy API to ensure synchronization behavior.
887            */
888            s->memcpy(dst, src + off, (size_t)chunk);
889        }
890    }
891    s->wait();
892    st.seconds = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
893
894    dpct::get_current_device().destroy_queue(s);
895    sycl::free(dst, dpct::get_in_order_queue());
896    return st;
897}
898catch (sycl::exception const &exc) {
899  std::cerr << exc.what() << "Exception caught at file:" << __FILE__
900            << ", line:" << __LINE__ << std::endl;
901  std::exit(1);
902}
903
904}  // namespace strata::core