okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
29ebb7926
main
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 { 47char magic [16 ]; 48uint32_t version ; 49uint32_t header_bytes ; 50uint64_t arena_bytes ; 51uint64_t pack_hash ; 52uint64_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 , 61uint64_t shared_pack_hash ,void *& mapping_base ,uint64_t & mapping_bytes ) { 62mapping_base = nullptr ; 63mapping_bytes = 0 ; 64#ifdef _WIN32 65if (!shared_file .empty ()) { 66note = "shared-file arena backing is not implemented on Windows" ; 67return 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 { 74HANDLE tok = nullptr ; 75if (OpenProcessToken (GetCurrentProcess (),TOKEN_ADJUST_PRIVILEGES |TOKEN_QUERY ,& tok )) { 76TOKEN_PRIVILEGES tp {}; 77tp .PrivilegeCount = 1 ; 78if (LookupPrivilegeValueW (nullptr ,L"SeLockMemoryPrivilege" ,& tp .Privileges [0 ].Luid )) { 79tp .Privileges [0 ].Attributes = SE_PRIVILEGE_ENABLED ; 80if (!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 } 83CloseHandle (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. 88SIZE_T large = GetLargePageMinimum (); 89// A/B switch: STRATA_NO_LARGEPAGES=1 skips the large-page attempt, same run, same boot. 90if (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. 94const SIZE_T lbytes = (SIZE_T ) (((SIZE_T )bytes + large - 1 ) /large * large ); 95void * p = VirtualAlloc (nullptr ,lbytes ,MEM_RESERVE |MEM_COMMIT |MEM_LARGE_PAGES , 96PAGE_READWRITE ); 97if (p ) { 98got = PageBacking ::LargePages ; 99note = "large pages (" + std::to_string ((unsigned long long )large )+ " B)" ; 100return 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. 104note = "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 ) { 108note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages" ; 109 }else { 110note = "this system has no large-page minimum; using 4 KB pages" ; 111 } 112void * p = VirtualAlloc (nullptr , (SIZE_T )bytes ,MEM_RESERVE |MEM_COMMIT ,PAGE_READWRITE ); 113got = PageBacking ::NormalPages ; 114return p ; 115#else 116if (!shared_file .empty ()) { 117if (shared_pack_hash == 0 ) { 118note = "shared arena requires a nonzero pack hash" ; 119return nullptr ; 120 } 121if (bytes > UINT64_MAX - kSharedArenaHeaderBytes ) { 122note = "shared arena size overflows its header" ; 123return nullptr ; 124 } 125const uint64_t file_bytes = kSharedArenaHeaderBytes + bytes ; 126const int fd = open (shared_file .c_str (),O_RDWR |O_CREAT |O_CLOEXEC ,0600 ); 127if (fd < 0 ) { 128note = "cannot open shared arena " + shared_file + ": " + std::strerror (errno ); 129return nullptr ; 130 } 131struct stat st {}; 132if (fstat (fd ,& st )!= 0 ) { 133const int e = errno ; 134close (fd ); 135note = "cannot stat shared arena " + shared_file + ": " + std::strerror (e ); 136return nullptr ; 137 } 138 139const bool fresh = st .st_size == 0 ; 140if (fresh ) { 141if (ftruncate (fd , (off_t )file_bytes )!= 0 ) { 142const int e = errno ; 143close (fd ); 144note = "cannot size shared arena " + shared_file + ": " + std::strerror (e ); 145return nullptr ; 146 } 147SharedArenaHeader hdr {}; 148 std::memcpy (hdr .magic ,kSharedArenaMagic ,sizeof hdr .magic ); 149hdr .version = 1 ; 150hdr .header_bytes = (uint32_t )kSharedArenaHeaderBytes ; 151hdr .arena_bytes = bytes ; 152hdr .pack_hash = shared_pack_hash ; 153const ssize_t written = pwrite (fd ,& hdr ,sizeof hdr ,0 ); 154if (written != (ssize_t )sizeof hdr ) { 155const int e = errno ; 156close (fd ); 157note = "cannot write shared arena header " + shared_file + ": " + 158 (written < 0 ? std::string (std::strerror (e )) : std::string ("short write" )); 159return nullptr ; 160 } 161 }else { 162if (st .st_size < 0 || (uint64_t )st .st_size != file_bytes ) { 163close (fd ); 164note = "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" ; 167return nullptr ; 168 } 169SharedArenaHeader hdr {}; 170const ssize_t got_header = pread (fd ,& hdr ,sizeof hdr ,0 ); 171if (got_header != (ssize_t )sizeof hdr || 172 std::memcmp (hdr .magic ,kSharedArenaMagic ,sizeof hdr .magic )!= 0 || 173hdr .version != 1 || hdr .header_bytes != kSharedArenaHeaderBytes || hdr .arena_bytes != bytes ) { 174close (fd ); 175note = "shared arena " + shared_file + " has an incompatible or missing header" ; 176return nullptr ; 177 } 178if (hdr .pack_hash != shared_pack_hash ) { 179close (fd ); 180char b [256 ]; 181 std::snprintf (b ,sizeof b , 182"shared arena %s was written for pack hash %016llx, expected %016llx" , 183shared_file .c_str (), (unsigned long long )hdr .pack_hash , 184 (unsigned long long )shared_pack_hash ); 185note = b ; 186return nullptr ; 187 } 188 } 189 190void * map = mmap (nullptr , (size_t )file_bytes ,PROT_READ |PROT_WRITE ,MAP_SHARED ,fd ,0 ); 191const int e = errno ; 192close (fd ); 193if (map == MAP_FAILED ) { 194note = "cannot map shared arena " + shared_file + ": " + std::strerror (e ); 195return nullptr ; 196 } 197mapping_base = map ; 198mapping_bytes = file_bytes ; 199got = PageBacking ::NormalPages ; 200note = "MAP_SHARED file " + shared_file + " (pack hash checked)" ; 201return (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. 206if (std::getenv ("STRATA_NO_LARGEPAGES" )!= nullptr ) { 207note = "large pages skipped (STRATA_NO_LARGEPAGES); using 4 KB pages" ; 208 }else { 209void * p = mmap (nullptr ,bytes ,PROT_READ |PROT_WRITE , 210MAP_PRIVATE |MAP_ANONYMOUS |MAP_HUGETLB |MAP_HUGE_2MB ,-1 ,0 ); 211if (p != MAP_FAILED ) { 212got = PageBacking ::LargePages ; 213note = "hugetlb 2 MB pages" ; 214return 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. 219const unsigned long long need = ((unsigned long long )bytes + (1ull <<21 )- 1 ) / (1ull <<21 ); 220unsigned long long pool = 0 ; 221bool have_pool = false; 222if (std::FILE * f = std::fopen ("/proc/sys/vm/nr_hugepages" ,"r" )) { 223have_pool = std::fscanf (f ,"%llu" ,& pool )== 1 ; 224 std::fclose (f ); 225 } 226note = "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. 232constexpr uint64_t kAlign = 2ull <<20 ; 233const uint64_t padded = bytes + kAlign ; 234void * raw = mmap (nullptr ,padded ,PROT_READ |PROT_WRITE ,MAP_PRIVATE |MAP_ANONYMOUS ,-1 ,0 ); 235got = PageBacking ::NormalPages ; 236if (raw == MAP_FAILED )return nullptr ; 237const uintptr_t start = (uintptr_t )raw ; 238const uintptr_t aligned = (start + kAlign - 1 )& ~(uintptr_t ) (kAlign - 1 ); 239if (aligned > start )munmap (raw ,aligned - start ); 240const uintptr_t end = aligned + bytes ,raw_end = start + padded ; 241if (raw_end > end )munmap ((void * )end ,raw_end - end ); 242void * 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 ; 248if (std::FILE * f = std::fopen ("/sys/kernel/mm/transparent_hugepage/enabled" ,"r" )) { 249char line [128 ]= {0 }; 250if (std::fgets (line ,sizeof line ,f )!= nullptr ) { 251const char * open = std::strchr (line ,'[' ); 252const char * close = open ? std::strchr (open ,']' ) :nullptr ; 253if (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 258const char * no_thp = std::getenv ("STRATA_NO_ARENA_THP" ); 259const bool user_no_thp = no_thp != nullptr && no_thp [0 ]!= '0' ; 260const bool skip_thp_request = user_no_thp || thp_mode == "always" ; 261if (std::getenv ("STRATA_NO_LARGEPAGES" )== nullptr && skip_thp_request ) { 262const std::string four_k = "; using 4 KB pages" ; 263if (note .size () >=four_k .size ()&& note .compare (note .size ()- four_k .size (),four_k .size (),four_k )== 0 ) 264note .resize (note .size ()- four_k .size ()); 265note += 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 ) { 269const std::string four_k = "; using 4 KB pages" ; 270if (note .size () >=four_k .size ()&& note .compare (note .size ()- four_k .size (),four_k .size (),four_k )== 0 ) 271note .resize (note .size ()- four_k .size ()); 272note += "; transparent huge pages requested (MADV_HUGEPAGE)" ; 273 } 274return p ; 275#endif 276} 277 278void release (void * p ,uint64_t bytes ) { 279if (!p )return ; 280#ifdef _WIN32 281 (void )bytes ; 282VirtualFree (p ,0 ,MEM_RELEASE ); 283#else 284munmap (p ,bytes ); 285#endif 286} 287 288}// namespace 289 290uint64_t fnv1a64 (const uint8_t * p ,uint64_t n ,uint64_t seed ) { 291uint64_t h = seed ; 292for (uint64_t i = 0 ;i < n ;++ i ) { 293h ^=p [i ]; 294h *=1099511628211ull ; 295 } 296return 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 () { 309const char * e = std::getenv ("STRATA_ARENA_PIN_GIB" ); 310if (e == nullptr || * e == '\0' )return -1 ; 311if (std::string (e )== "auto" )return -2 ;// #243: the Windows shared-memory budget sets the sliced pin's cap 312const int v = std::atoi (e ); 313return 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 ) { 324constexpr uint64_t GiB = 1ull <<30 ; 325char buf [256 ]; 326int dev = 0 ; 327cudaDeviceProp p {}; 328uint64_t budget = 0 ,usage = 0 ; 329 std::string err = "no CUDA device properties" ; 330if (cudaGetDevice (& dev )== cudaSuccess && cudaGetDeviceProperties (& p ,dev )== cudaSuccess && 331 strata::platform::gpu_shared_memory_budget (p .luid ,budget ,usage ,err )) { 332limit = 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 ); 335why = buf ; 336return true; 337 } 338 (void )cudaGetLastError (); 339const uint64_t ram = strata::platform::total_physical_memory (); 340if (ram == 0 )return false; 341limit = 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 ); 343why = buf ; 344return 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 ; 352if (slice == 0 )return b ; 353for (uint64_t off = 0 ;off + slice <=bytes ;off += slice )b .push_back (off ); 354if (!b .empty ())b .push_back (b .back ()+ slice ); 355return b ; 356} 357}// namespace 358 359PinnedArena ::PinnedArena (uint64_t bytes ,uint64_t slice ) :PinnedArena (bytes ,uniform_bounds (bytes ,slice )) { 360if (slice_bytes )slice_bytes = slice ;// sliced registration: record the uniform size 361} 362 363PinnedArena ::PinnedArena (uint64_t bytes ,const std::vector < uint64_t > & bounds , 364uint64_t max_pinned_bytes , 365const std::string & shared_file , 366uint64_t shared_pack_hash )try 367 :capacity (bytes ) { 368if (bytes == 0 )return ; 369base = reserve (bytes ,backing ,note ,shared_file ,shared_pack_hash ,mapping_base ,mapping_bytes ); 370if (base != nullptr && mapping_base == nullptr ) { 371mapping_base = base ; 372mapping_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. 377if (base ) { 378// #243: STRATA_ARENA_PIN_GIB=N caps the registration from the start where the caller set no cap 379const int env_gib = arena_pin_cap_gib (); 380uint64_t cap = max_pinned_bytes ; 381 std::string cap_why = "by the engine (multi-GPU under WDDM, or remote experts)" ; 382if (cap == 0 && env_gib > 0 ) { 383cap = (uint64_t )env_gib <<30 ; 384cap_why = "by STRATA_ARENA_PIN_GIB" ; 385 } 386const bool capped = cap > 0 && cap < bytes && bounds .size () >=2 ; 387const dpct::err0 e = 388capped ?0 : 389/* 390DPCT1027: The call to cudaHostRegister was replaced with 3910 because SYCL currently does not support registering of 392existing host memory for use by device. Use USM to allocate 393memory for use by host and device. 394*/ 3950 ; 396if (!capped && e == 0 ) { 397note = "cudaHostRegister PORTABLE ok; " + note ; 398registered_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.) 402slice_bytes = 1 ;// sliced; the uniform constructor records the size 403bool limited = capped ; 404uint64_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. 410if (!capped && env_gib == -2 )limited = sliced_pin_limit (limit ,limit_why ); 411#endif 412for (size_t i = 0 ;i + 1 < bounds .size ();++ i ) { 413const uint64_t off = bounds [i ],n = bounds [i + 1 ]- bounds [i ]; 414if (limited && (off > limit || n > limit - off ))break ; 415/* 416DPCT1027: The call to cudaHostRegister was replaced with 0 417because SYCL currently does not support registering of existing 418host memory for use by device. Use USM to allocate memory for 419use by host and device. 420*/ 421if (0 != 0 ) { 422/* 423DPCT1010: SYCL uses exceptions to report errors and 424does not use the error codes. The cudaGetLastError function 425call was replaced with 0. You need to rewrite this code. 426*/ 427 (void )0 ; 428break ; 429 } 430slice_starts .push_back (off ); 431registered_bytes = off + n ; 432++ registered_slices ; 433 } 434char gib [32 ]; 435 std::snprintf (gib ,sizeof gib ,"%.1f" , (double )limit / (double ) (1ull <<30 )); 436note = 437 (capped 438 ?"cudaHostRegister limited to " + 439 std::to_string (cap >>30 )+ " GiB " + cap_why + "; " 440 : 441/* 442DPCT1009: SYCL reports errors using exceptions and 443does not use error codes. Please replace the 444"get_error_string_dummy(...)" with a real error-handling 445function. 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 ; 456if (registered_bytes < bytes ) { 457const char * env = std::getenv ("STRATA_ARENA_LOCK" ); 458if (backing == PageBacking ::LargePages ) {// #779: large pages cannot be paged out: nothing to lock 459note = "large pages are resident without a lock; " + note ; 460 }else if (env == nullptr || std::string (env )!= "0" ) { 461const strata::platform::LockResult lr = 462 strata::platform::lock_resident ((uint8_t * )base + registered_bytes ,bytes - registered_bytes ); 463locked_bytes = lr .locked_bytes ; 464note = lr .note + "; " + note ; 465 } 466 } 467 }else { 468/* 469DPCT1009: SYCL reports errors using exceptions and does not use 470error codes. Please replace the "get_error_string_dummy(...)" with a 471real error-handling function. 472*/ 473note = std::string ("cudaHostRegister FAILED (" )+ 474 dpct::get_error_string_dummy (e )+ 475") - the arena is NOT pinned, so copies will be slow; " + 476note ; 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/* 489DPCT1010: SYCL uses exceptions to report errors and does not 490use the error codes. The cudaGetLastError function call was replaced 491with 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. 497const char * env = std::getenv ("STRATA_ARENA_LOCK" ); 498if (backing == PageBacking ::LargePages ) {// #779: large pages cannot be paged out: nothing to lock 499note = "large pages are resident without a lock; " + note ; 500 }else if (env == nullptr || std::string (env )!= "0" ) { 501const strata::platform::LockResult lr = strata::platform::lock_resident (base ,bytes ); 502locked_bytes = lr .locked_bytes ; 503note = lr .note + "; " + note ; 504 }else { 505note = "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 ) { 518if (bytes == 0 || bounds .size ()< 2 )return ; 519base = reserve (bytes ,backing ,note , std::string {},0 ,mapping_base ,mapping_bytes ); 520if (base != nullptr && mapping_base == nullptr ) { 521mapping_base = base ; 522mapping_bytes = bytes ; 523 } 524slice_bytes = 1 ;// sliced: one registration per layer 525} 526 527void PinnedArena ::register_slices (std::atomic < int > & ready )try { 528const int n = (int )bounds_ .size ()- 1 ; 529int i = 0 ; 530for (;base != nullptr && i < n ;++ i ) { 531const uint64_t off = bounds_ [(size_t )i ],len = bounds_ [(size_t )i + 1 ]- off ; 532/* 533DPCT1027: The call to cudaHostRegister was replaced with 0 because 534SYCL currently does not support registering of existing host memory for 535use by device. Use USM to allocate memory for use by host and device. 536*/ 537if (0 != 0 ) { 538/* 539DPCT1010: SYCL uses exceptions to report errors and does not use 540the error codes. The cudaGetLastError function call was replaced 541with 0. You need to rewrite this code. 542*/ 543 (void )0 ; 544break ; 545 } 546slice_starts .push_back (off ); 547registered_bytes = off + len ; 548++ registered_slices ; 549ready .store (i + 1 , std::memory_order_release ); 550 } 551note = "cudaHostRegister per layer, pipelined with the load: " + std::to_string (registered_slices )+ " of " + 552 std::to_string (n )+ " slices pinned; " + note ; 553if (i < n && base != nullptr ) {// the rest stays resident through the working-set lock, as the sliced fallback does 554const char * env = std::getenv ("STRATA_ARENA_LOCK" ); 555if (backing == PageBacking ::LargePages ) {// #779: large pages cannot be paged out: nothing to lock 556note = "large pages are resident without a lock; " + note ; 557 }else if (env == nullptr || std::string (env )!= "0" ) { 558const strata::platform::LockResult lr = 559 strata::platform::lock_resident ((uint8_t * )base + registered_bytes ,capacity - registered_bytes ); 560locked_bytes = lr .locked_bytes ; 561note = lr .note + "; " + note ; 562 } 563 } 564ready .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 () { 573if (base ) { 574if (locked_bytes ) strata::platform::unlock_resident ((uint8_t * )base + (slice_bytes ?registered_bytes :0 ),locked_bytes ); 575if (slice_bytes ) { 576/* 577DPCT1027: The call to cudaHostUnregister was replaced with 0 578because SYCL currently does not support registering of existing host 579memory for use by device. Use USM to allocate memory for use by host 580and device. 581*/ 582for (uint64_t off :slice_starts )0 ; 583 }else { 584/* 585DPCT1026: The call to cudaHostUnregister was removed because 586SYCL currently does not support registering of existing host memory 587for use by device. Use USM to allocate memory for use by host and 588device. 589*/ 590 } 591release (mapping_base ?mapping_base :base ,mapping_bytes ?mapping_bytes :capacity ); 592base = nullptr ; 593mapping_base = nullptr ; 594mapping_bytes = 0 ; 595 } 596} 597 598LoadStats load_experts (const std::string & path ,uint8_t * dst ,uint64_t blob_bytes ,uint64_t blobs_per_layer , 599uint64_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 ); 601for (uint64_t L = 0 ;L < layers ;++ L )off [(size_t )L ]= L * blobs_per_layer * blob_bytes ; 602return 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 , 606const std::vector < uint64_t >& layer_bytes ,int threads ,uint64_t chunk , 607const std::atomic < int >* ready ) { 608LoadStats st ; 609st .ok = false; 610#ifdef _WIN32 611constexpr uint64_t kAlign = 4096 ; 612if (((uintptr_t )dst %kAlign )!= 0 || chunk == 0 || chunk %kAlign != 0 )return st ; 613struct Piece {uint64_t off ,n ;int layer ; }; 614 std::vector < Piece > pieces ; 615uint64_t bytes = 0 ; 616for (size_t L = 0 ;L < layer_off .size ();++ L ) { 617if (layer_off [L ] %kAlign != 0 || layer_bytes [L ] %kAlign != 0 )return st ; 618for (uint64_t p = 0 ;p < layer_bytes [L ];p += chunk ) 619pieces .push_back ({layer_off [L ]+ p , std::min < uint64_t > (chunk ,layer_bytes [L ]- p ), (int )L }); 620bytes += layer_bytes [L ]; 621 } 622if (threads < 1 )threads = 1 ; 623const auto t0 = std::chrono::steady_clock::now (); 624 std::atomic < size_t > next {0 }; 625 std::mutex err_mu ; 626 std::string err ; 627const 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' ); 629if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,wpath .data (),wide ); 630auto worker = [& ]() { 631HANDLE h = CreateFileW (wpath .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 632FILE_FLAG_NO_BUFFERING |FILE_FLAG_SEQUENTIAL_SCAN ,nullptr ); 633if (h == INVALID_HANDLE_VALUE ) { 634 std::lock_guard < std::mutex > g (err_mu ); 635if (err .empty ()) 636err = "cannot open " + path + " unbuffered (error " + std::to_string ((unsigned long long )GetLastError ())+ ")" ; 637next = pieces .size (); 638return ; 639 } 640for (;;) { 641const size_t i = next .fetch_add (1 ); 642if (i >=pieces .size ())break ; 643if (ready != nullptr )// the slice must be registered before its pages are touched 644while (ready -> load (std::memory_order_acquire ) <=pieces [i ].layer + 1 ) std::this_thread::yield (); 645OVERLAPPED ov {}; 646ov .Offset = (DWORD )pieces [i ].off ; 647ov .OffsetHigh = (DWORD ) (pieces [i ].off >>32 ); 648DWORD got = 0 ; 649if (!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 ); 651if (err .empty ()) 652err = "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 ())+ ")" ; 655next = pieces .size (); 656break ; 657 } 658 } 659CloseHandle (h ); 660 }; 661 std::vector < std::thread > pool ; 662for (int i = 1 ;i < threads ;++ i )pool .emplace_back (worker ); 663worker (); 664for (auto & t :pool )t .join (); 665st .layers = layer_off .size (); 666if (!err .empty ()) { 667st .seconds = -1.0 ; 668st .error = err ; 669return st ; 670 } 671st .ok = true; 672st .bytes = bytes ; 673st .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 677return st ; 678} 679 680bool experts_unbuffered (const std::vector < std::string >& files ,uint64_t arena_bytes , std::string & why , 681bool cache_counts ,uint64_t read_bytes ) { 682const char * env = std::getenv ("STRATA_UNBUFFERED_LOAD" ); 683if (env != nullptr && env [0 ]!= '\0' ) { 684why = std::string ("STRATA_UNBUFFERED_LOAD=" )+ env ; 685return env [0 ]!= '0' ; 686 } 687#ifdef _WIN32 688LARGE_INTEGER freq {},a {},b {}; 689QueryPerformanceFrequency (& freq ); 690constexpr DWORD kRead = 64 <<10 ; 691constexpr int kSamples = 16 ; 692 std::vector < uint8_t > buf (kRead ); 693uint64_t total_bytes = 0 ; 694int fast = 0 ,n = 0 ; 695uint64_t seed = (uint64_t )GetTickCount64 ()* 6364136223846793005ull + 1442695040888963407ull ; 696for (const std::string & f :files ) { 697const 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' ); 699if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,f .c_str (),-1 ,w .data (),wide ); 700HANDLE h = CreateFileW (w .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING ,FILE_FLAG_RANDOM_ACCESS , 701nullptr ); 702if (h == INVALID_HANDLE_VALUE )continue ; 703LARGE_INTEGER size {}; 704GetFileSizeEx (h ,& size ); 705total_bytes += (uint64_t )size .QuadPart ; 706// random offsets: a probe must not find the blocks an earlier probe put into the cache 707for (int i = 0 ;i < kSamples && (uint64_t )size .QuadPart > 2ull * kRead ;++ i ) { 708seed = seed * 6364136223846793005ull + 1442695040888963407ull ; 709const uint64_t off = ((seed >>17 ) % ((uint64_t )size .QuadPart - kRead )) /kRead * kRead ; 710OVERLAPPED ov {}; 711ov .Offset = (DWORD )off ; 712ov .OffsetHigh = (DWORD ) (off >>32 ); 713DWORD got = 0 ; 714QueryPerformanceCounter (& a ); 715const BOOL ok = ReadFile (h ,buf .data (),kRead ,& got ,& ov ); 716QueryPerformanceCounter (& b ); 717if (!ok )continue ; 718++ n ; 719fast += (double ) (b .QuadPart - a .QuadPart )* 1e6 / (double )freq .QuadPart < 30.0 ; 720 } 721CloseHandle (h ); 722 } 723const bool cached = n > 0 && fast * 4 >=n * 3 ; 724MEMORYSTATUSEX ms {}; 725ms .dwLength = sizeof ms ; 726GlobalMemoryStatusEx (& ms ); 727const uint64_t avail = ms .ullAvailPhys ; 728// what the cache could keep beside the arena (~4 GiB for everything else) 729const uint64_t need = read_bytes == kAllFileBytes ?total_bytes :read_bytes ; 730const bool keepable = strata::platform::file_cache_keeps (avail ,arena_bytes ,need ); 731char msg [256 ]; 732if (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" , 734fast ,n , (double )avail / (1ull <<30 ), (double )total_bytes / (1ull <<30 )); 735else 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 ), 739keepable ?"can" :"cannot" ); 740why = msg ; 741return (!cached || !cache_counts )&& !keepable ; 742#else 743 (void )files ; (void )arena_bytes ; (void )cache_counts ; (void )read_bytes ; 744why = "buffered (not Windows)" ; 745return false; 746#endif 747} 748 749LoadStats load_experts_ranges (const std::string & path ,uint8_t * dst ,const std::vector < uint64_t >& layer_off , 750const std::vector < uint64_t >& layer_bytes ,int threads ,uint64_t chunk , 751const std::atomic < int >* ready ) { 752LoadStats st ; 753const uint64_t layers = (uint64_t )layer_off .size (); 754st .layers = layers ; 755st .bytes = 0 ; 756for (uint64_t b :layer_bytes )st .bytes += b ; 757if (threads < 1 )threads = 1 ; 758 759const 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 767auto 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. 776FILE * f = std::fopen (path .c_str (),"rb" ); 777if (f == nullptr ) { 778 std::lock_guard < std::mutex > g (err_mu ); 779err = "cannot open " + path ; 780return ; 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. 784struct Closer { 785FILE * f ; 786 ~Closer () {if (f != nullptr ) std::fclose (f ); } 787 }closer {f }; 788uint64_t read_ns = 0 ,copy_ns = 0 ; 789for (;;) { 790const uint64_t L = next_layer .fetch_add (1 ); 791if (L >=layers )break ; 792if (ready != nullptr )// the slice must be registered before its pages are touched 793while (ready -> load (std::memory_order_acquire ) <= (int )L + 1 ) std::this_thread::yield (); 794const uint64_t off = layer_off [(size_t )L ]; 795uint64_t remaining = layer_bytes [(size_t )L ]; 796uint64_t pos = 0 ; 797uint64_t h = 1469598103934665603ull ; 798// 64-bit seek: the pack is 42.9 GB, so the 32-bit `fseek` would wrap past 4 GiB 799if (STRATA_FSEEK64 (f ,off )!= 0 ) { 800 std::lock_guard < std::mutex > g (err_mu ); 801err = "seek to " + std::to_string (off )+ " B failed in layer " + std::to_string (L ); 802return ; 803 } 804while (remaining > 0 ) { 805const uint64_t n = remaining < chunk ?remaining :chunk ; 806const auto t_read = std::chrono::steady_clock::now (); 807const size_t got = std::fread (buf .data (),1 , (size_t )n ,f ); 808read_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. 812if (got != (size_t )n ) { 813 std::lock_guard < std::mutex > g (err_mu ); 814err = "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)" :"" ); 817return ; 818 } 819const auto t_copy = std::chrono::steady_clock::now (); 820 std::memcpy (dst + off + pos ,buf .data (), (size_t )n ); 821h = fnv1a64 (buf .data (),n ,h ); 822copy_ns += (uint64_t ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 823 std::chrono::steady_clock::now ()- t_copy ).count (); 824pos += n ; 825remaining -= n ; 826 } 827layer_hash [(size_t )L ]= h ; 828 } 829read_ns_sum .fetch_add (read_ns ); 830copy_ns_sum .fetch_add (copy_ns ); 831 }; 832 833 std::vector < std::thread > pool ; 834for (int i = 1 ;i < threads ;++ i )pool .emplace_back (worker ); 835worker (); 836for (auto & t :pool )t .join (); 837 838if (!err .empty ()) { 839 std::fprintf (stderr ,"load_experts: %s\n" ,err .c_str ()); 840st .seconds = -1.0 ; 841st .ok = false; 842st .error = err ; 843return st ; 844 } 845st .read_seconds = (double )read_ns_sum .load () /1e9 ; 846st .copy_seconds = (double )copy_ns_sum .load () /1e9 ; 847st .layer_checksums = std::move (layer_hash ); 848st .seconds = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 849return st ; 850} 851 852StreamStats stream_bandwidth (const uint8_t * src ,uint64_t bytes ,uint64_t chunk , 853int iters )try { 854StreamStats st ; 855st .bytes = bytes * (uint64_t )iters ; 856st .chunk = chunk ; 857uint8_t * dst = nullptr ; 858 dpct::queue_ptr s {}; 859if (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 ); 862st .seconds = -1.0 ; 863return st ; 864 } 865s = 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 868for (uint64_t off = 0 ;off + chunk <=bytes ;off += chunk ) { 869/* 870DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 871While the origin API might be synchronous, it depends on the type of 872operand memory, so you may need to call wait() on event return by memcpy 873API to ensure synchronization behavior. 874*/ 875s -> memcpy (dst ,src + off , (size_t )chunk ); 876 } 877s -> wait (); 878 879const auto t0 = std::chrono::steady_clock::now (); 880for (int it = 0 ;it < iters ;++ it ) { 881for (uint64_t off = 0 ;off + chunk <=bytes ;off += chunk ) { 882/* 883DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 884API. While the origin API might be synchronous, it depends on the 885type of operand memory, so you may need to call wait() on event 886return by memcpy API to ensure synchronization behavior. 887*/ 888s -> memcpy (dst ,src + off , (size_t )chunk ); 889 } 890 } 891s -> wait (); 892st .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 ()); 896return 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