okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a00d88938
main
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 ) { 70bytes = 0 ; 71if (!stat .valid )return false; 72 73// memory.stat's inactive_file can race memory.current, so bound it to charged usage first. 74uint64_t reclaimable = std::min (stat .inactive_file ,stat .current ); 75reclaimable = stat .file_dirty >=reclaimable ?0 :reclaimable - stat .file_dirty ; 76reclaimable = 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. 79const uint64_t usage_after_reclaim = stat .current - reclaimable ; 80bytes = usage_after_reclaim < limit ?limit - usage_after_reclaim :0 ; 81return true; 82} 83 84uint64_t clamp_resident_budget (uint64_t requested ,uint64_t physical ,uint64_t commit ,uint64_t headroom ) { 85const uint64_t available = std::min (physical ,commit ); 86const uint64_t room = available > headroom ?available - headroom :0 ; 87if (requested <=room )return requested ; 88const uint64_t margin = 256ull <<20 ; 89return room > margin ?room - margin :0 ; 90} 91 92bool make_cache_complement_plan ( 93int64_t n_layers ,int64_t n_expert ,const std::vector < uint64_t >& layer_blob_bytes , 94const std::vector < std::pair < int32_t ,int32_t >>& primary_gpu_pairs , 95const std::vector < std::pair < int32_t ,int32_t >>& additional_gpu_pairs , 96 std::vector < uint64_t >& offsets ,uint64_t & bytes , std::string & err ) { 97offsets .clear (); 98bytes = 0 ; 99err .clear (); 100if (n_layers <=0 || n_expert <=0 || layer_blob_bytes .size ()!= (size_t )n_layers ) { 101err = "FileExpertSource: invalid geometry for the cache complement plan" ; 102return false; 103 } 104if ((uint64_t )n_layers > (uint64_t ) std::numeric_limits < size_t > ::max () / (uint64_t )n_expert ) { 105err = "FileExpertSource: cache complement index table is too large" ; 106return false; 107 } 108const size_t count = (size_t )n_layers * (size_t )n_expert ; 109 std::vector < uint8_t > omitted (count ,0 ); 110auto mark_pairs = [& ](const std::vector < std::pair < int32_t ,int32_t >>& pairs ,uint8_t bit , 111const char * label )-> bool { 112for (const auto & pair :pairs ) { 113if (pair .first < 0 || pair .second < 0 || pair .first >=n_layers || pair .second >=n_expert ) { 114err = std::string ("FileExpertSource: " )+ label + " pair is outside the expert geometry" ; 115return false; 116 } 117const size_t index = (size_t )pair .first * (size_t )n_expert + (size_t )pair .second ; 118if ((omitted [index ]& bit )!= 0 ) { 119err = std::string ("FileExpertSource: duplicate " )+ label + " pair in the cache complement plan" ; 120return false; 121 } 122if (bit == 2 && (omitted [index ]& 1 )!= 0 ) { 123err = "FileExpertSource: the primary and additional GPU expert tiers overlap" ; 124return false; 125 } 126omitted [index ] |=bit ; 127 } 128return true; 129 }; 130if (!mark_pairs (primary_gpu_pairs ,1 ,"primary GPU" )|| 131 !mark_pairs (additional_gpu_pairs ,2 ,"additional GPU" ))return false; 132for (uint64_t blob_bytes :layer_blob_bytes ) { 133if (blob_bytes == 0 ) { 134err = "FileExpertSource: cache complement layer has zero-sized expert blobs" ; 135return false; 136 } 137 } 138 139offsets .assign (count ,kNoCacheComplement ); 140for (int64_t layer = 0 ;layer < n_layers ;++ layer ) { 141const uint64_t blob_bytes = layer_blob_bytes [(size_t )layer ]; 142for (int64_t expert = 0 ;expert < n_expert ;++ expert ) { 143const size_t index = (size_t )layer * (size_t )n_expert + (size_t )expert ; 144if (omitted [index ]!= 0 )continue ; 145if (bytes > std::numeric_limits < uint64_t > ::max ()- blob_bytes ) { 146offsets .clear (); 147bytes = 0 ; 148err = "FileExpertSource: cache complement size overflows" ; 149return false; 150 } 151offsets [index ]= bytes ; 152bytes += blob_bytes ; 153 } 154 } 155if (bytes > (uint64_t ) std::numeric_limits < size_t > ::max ()) { 156offsets .clear (); 157bytes = 0 ; 158err = "FileExpertSource: cache complement exceeds the host address space" ; 159return false; 160 } 161return true; 162} 163 164const uint8_t * cache_complement_blob_or_fallback ( 165size_t index ,const std::vector < uint64_t >& offsets ,const uint8_t * complement_host , 166const uint8_t * mapped_fallback ) { 167if (complement_host != nullptr && index < offsets .size ()&& offsets [index ]!= kNoCacheComplement ) 168return complement_host + (size_t )offsets [index ]; 169return mapped_fallback ; 170} 171 172int64_t choose_resident_keep_from (const std::vector < uint64_t >& slot_bytes ,uint64_t base_bytes ,uint64_t budget , 173int64_t lend_from ) { 174if (base_bytes > budget )return -1 ; 175const int64_t slots = (int64_t )slot_bytes .size (); 176if (lend_from < 0 || lend_from > slots )lend_from = slots ;// no lend region: only the experts no slot holds 177int64_t keep = slots ; 178uint64_t bytes = base_bytes ; 179while (keep > lend_from ) { 180const uint64_t b = slot_bytes [(size_t )keep - 1 ]; 181if (b > budget - bytes )break ; 182bytes += b ; 183-- keep ; 184 } 185return keep ; 186} 187 188bool exchange_cache_complement (std::vector < uint64_t >& offsets ,size_t in ,size_t out ) { 189if (in == out || in >=offsets .size ()|| out >=offsets .size ()|| offsets [in ]== kNoCacheComplement || 190offsets [out ]!= kNoCacheComplement )return false; 191offsets [out ]= offsets [in ]; 192offsets [in ]= kNoCacheComplement ; 193return 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" ); 204if (!input )return false; 205 206bool inactive_file = false,file_dirty = false,file_writeback = false; 207 std::string line ; 208while (std::getline (input ,line )) { 209 std::istringstream fields (line ); 210 std::string key ; 211uint64_t value = 0 ; 212if (!(fields >>key >>value ))return false; 213fields >> std::ws ; 214if (!fields .eof ())return false; 215 216if (key == "inactive_file" ) { 217if (inactive_file )return false; 218inactive_file = true; 219stat .inactive_file = value ; 220 }else if (key == "file_dirty" ) { 221if (file_dirty )return false; 222file_dirty = true; 223stat .file_dirty = value ; 224 }else if (key == "file_writeback" ) { 225if (file_writeback )return false; 226file_writeback = true; 227stat .file_writeback = value ; 228 } 229 } 230if (!input .eof ()|| !inactive_file || !file_dirty || !file_writeback )return false; 231stat .current = current ; 232stat .valid = true; 233return 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 , 242const std::string & cgroup_root ) { 243m = HostMemory {}; 244#if defined(_WIN32 ) 245 (void )meminfo ; (void )self_cgroup ; (void )cgroup_root ; 246MEMORYSTATUSEX status {}; 247status .dwLength = sizeof (status ); 248if (!GlobalMemoryStatusEx (& status ))return false; 249m .available = (uint64_t )status .ullAvailPhys ; 250m .commit = (uint64_t )status .ullAvailPageFile ; 251return 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 ; 256uint64_t bytes = 0 ; 257while (std::getline (info ,line )) { 258 std::istringstream fields (line ); 259 std::string key ,unit ; 260uint64_t value = 0 ; 261if (fields >>key >>value >>unit && key == "MemAvailable:" && unit == "kB" && 262value <= std::numeric_limits < uint64_t > ::max () /1024 )bytes = value * 1024 ; 263 } 264if (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 ); 268if (!groups )return false; 269const std::filesystem::path root (cgroup_root ); 270bool v2 = false; 271 std::string v1_path ;// the memory controller's group (cgroup v1), when there is no v2 line 272while (std::getline (groups ,line )) { 273if (line .rfind ("0::/" ,0 )!= 0 ) { 274// v1: "N:controller[,controller]:/path" 275const size_t c1 = line .find (':' ),c2 = c1 == std::string::npos ?c1 :line .find (':' ,c1 + 1 ); 276if (c2 == std::string::npos )continue ; 277 std::istringstream ctl (line .substr (c1 + 1 ,c2 - c1 - 1 )); 278for (std::string c ; std::getline (ctl ,c ,',' );) 279if (c == "memory" )v1_path = line .substr (c2 + 1 ); 280continue ; 281 } 282auto path = (root /line .substr (4 )).lexically_normal (); 283if (path .string ().rfind (root .string (),0 )!= 0 || !std::filesystem::is_directory (path ))return false; 284v2 = true; 285while (path .string ().rfind (root .string (),0 )== 0 ) { 286 std::ifstream limit_file (path /"memory.max" ),current_file (path /"memory.current" ); 287 std::string limit ; 288uint64_t current = 0 ; 289const 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. 291if (!readable && !(path == root && !std::filesystem::exists (path /"memory.max" )&& 292 std::filesystem::exists (path /"cgroup.controllers" )))return false; 293if (readable && limit != "max" ) { 294try { 295size_t consumed = 0 ; 296const uint64_t cap = std::stoull (limit ,& consumed ); 297if (consumed != limit .size ())return false; 298CgroupMemoryStat stat ; 299if (!read_cgroup_memory_stat (path ,current ,stat ))return false; 300uint64_t cgroup_available = 0 ; 301if (!cgroup_available_bytes (cap ,stat ,cgroup_available ))return false; 302bytes = std::min (bytes ,cgroup_available ); 303m .cgroup_limit = std::min (m .cgroup_limit ,cap ); 304 }catch (...) {return false; } 305 } 306if (path == root )break ; 307path = path .parent_path (); 308 } 309 } 310if (!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. 314const std::filesystem::path mroot = root /"memory" ; 315auto path = (mroot /v1_path .substr (v1_path .rfind ('/' ,0 )== 0 ?1 :0 )).lexically_normal (); 316while (path .string ().rfind (mroot .string (),0 )== 0 ) { 317 std::ifstream limit_file (path /"memory.limit_in_bytes" ),usage_file (path /"memory.usage_in_bytes" ); 318uint64_t cap = 0 ,usage = 0 ; 319if (limit_file >>cap && usage_file >>usage && cap < (1ull <<62 )) { 320bytes = std::min (bytes ,usage < cap ?cap - usage :0 ); 321m .cgroup_limit = std::min (m .cgroup_limit ,cap ); 322 } 323if (path == mroot )break ; 324path = path .parent_path (); 325 } 326 } 327m .available = bytes ; 328return true; 329#else 330 (void )meminfo ; (void )self_cgroup ; (void )cgroup_root ; 331const long pages = sysconf (_SC_AVPHYS_PAGES ); 332const long page_bytes = sysconf (_SC_PAGESIZE ); 333if (pages <=0 || page_bytes <=0 || 334 (uint64_t )pages > std::numeric_limits < uint64_t > ::max () / (uint64_t )page_bytes )return false; 335m .available = (uint64_t )pages * (uint64_t )page_bytes ; 336return 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 ; 346if (!detail::host_available_memory (m ))return false; 347bytes = m .available ; 348if (commit != nullptr )* commit = m .commit ; 349return bytes > 0 ; 350} 351 352void log_complement_memory (const char * stage ,uint64_t requested ) { 353#if defined(_WIN32 ) 354MEMORYSTATUSEX status {}; 355status .dwLength = sizeof (status ); 356if (!GlobalMemoryStatusEx (& status )) { 357 std::fprintf (stderr ,"FileExpertSource: %s: GlobalMemoryStatusEx failed (error %lu)\n" ,stage ,GetLastError ()); 358return ; 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" , 362stage , (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 ) 374CloseHandle ((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 ) 387return experts_unbuffered (paths ,arena_bytes ,why ,/*cache_counts=*/ false,read_bytes ); 388#elif defined(__linux__ ) 389 (void )paths ; 390if (const char * env = std::getenv ("STRATA_UNBUFFERED_LOAD" );env != nullptr && env [0 ]!= '\0' ) { 391why = std::string ("STRATA_UNBUFFERED_LOAD=" )+ env ; 392return env [0 ]!= '0' ; 393 } 394uint64_t avail = 0 ; 395if (!available_memory_bytes (avail )) { 396why = "the available RAM is unknown" ; 397return false; 398 } 399const bool keepable = strata::platform::file_cache_keeps (avail ,arena_bytes ,read_bytes ); 400char 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 ), 404keepable ?"can" :"cannot" ); 405why = msg ; 406return !keepable ; 407#else 408 (void )paths ; (void )arena_bytes ; (void )read_bytes ; 409why = "through the file cache (no unbuffered reads on this platform)" ; 410return 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 ) { 421close (); 422if (n_layers <=0 || n_expert <=0 ) {err = "FileExpertSource: the geometry is empty" ;return false; } 423const auto & layout = strata::kernels::cpu::expert_layout (); 424if (layout .n_layers != n_layers || layout .n_expert != n_expert ) { 425err = "FileExpertSource: the requested geometry does not match the loaded expert layout" ; 426return false; 427 } 428if ((uint64_t )n_layers > (uint64_t ) std::numeric_limits < int64_t > ::max () / (uint64_t )n_expert ) { 429err = "FileExpertSource: the expert count overflows" ; 430return false; 431 } 432const uint64_t blob_count = (uint64_t )n_layers * (uint64_t )n_expert ; 433if (blob_count > (uint64_t ) std::numeric_limits < int64_t > ::max ()|| 434 (uint64_t )n_layers > (uint64_t ) std::numeric_limits < size_t > ::max ()) { 435err = "FileExpertSource: the expert count overflows" ; 436return false; 437 } 438 439 std::vector < uint64_t > layer_offsets ((size_t )n_layers ),layer_blob_bytes ((size_t )n_layers ); 440const uint64_t want = layout .total ; 441if (want == 0 || want > (uint64_t ) std::numeric_limits < size_t > ::max ()) { 442err = "FileExpertSource: the loaded expert layout has an invalid size" ; 443return false; 444 } 445if (!layout .native ) { 446if (blob_count > std::numeric_limits < uint64_t > ::max () / (uint64_t ) strata::kernels::cpu::BLOB ) { 447err = "FileExpertSource: the canonical expert size overflows" ; 448return false; 449 } 450const uint64_t canonical_size = blob_count * (uint64_t ) strata::kernels::cpu::BLOB ; 451if (want != canonical_size ) { 452err = "FileExpertSource: the canonical expert layout has an inconsistent size" ; 453return false; 454 } 455const uint64_t bytes = (uint64_t ) strata::kernels::cpu::BLOB ; 456const uint64_t layer_bytes = (uint64_t )n_expert * bytes ; 457for (int64_t layer = 0 ;layer < n_layers ;++ layer ) { 458layer_offsets [(size_t )layer ]= (uint64_t )layer * layer_bytes ; 459layer_blob_bytes [(size_t )layer ]= bytes ; 460 } 461 }else { 462if (layout .offset .size ()!= (size_t )n_layers || layout .bytes .size ()!= (size_t )n_layers || 463layout .fmt .size ()!= (size_t )n_layers ) { 464err = "FileExpertSource: the native expert layout is incomplete" ; 465return false; 466 } 467uint64_t at = 0 ; 468for (int64_t layer = 0 ;layer < n_layers ;++ layer ) { 469const size_t i = (size_t )layer ; 470const uint64_t bytes = (uint64_t )layout .fmt [i ].bytes ; 471if (layout .offset [i ]!= at || bytes == 0 || layout .bytes [i ]!= bytes || 472bytes > std::numeric_limits < uint64_t > ::max () / (uint64_t )n_expert ) { 473err = "FileExpertSource: the native expert layout is invalid at layer " + std::to_string (layer ); 474return false; 475 } 476const uint64_t layer_bytes = bytes * (uint64_t )n_expert ; 477if (at > want || layer_bytes > want - at ) { 478err = "FileExpertSource: the native expert layout exceeds its declared size at layer " + 479 std::to_string (layer ); 480return false; 481 } 482layer_offsets [i ]= layout .offset [i ]; 483layer_blob_bytes [i ]= bytes ; 484at += layer_bytes ; 485 } 486if (at != want ) { 487err = "FileExpertSource: the native expert layout has an inconsistent size" ; 488return false; 489 } 490 } 491const std::string path = pack_dir + "/experts.bin" ; 492if (layout .native && !gguf_ .empty ()&& !std::filesystem::exists (path )) { 493// CS-T: no experts.bin - the model's GGUF shards, read in place 494blobs_ = (int64_t )blob_count ; 495n_layers_ = n_layers ; 496n_expert_ = n_expert ; 497layer_offsets_ = std::move (layer_offsets ); 498layer_blob_bytes_ = std::move (layer_blob_bytes ); 499if (!open_gguf (err )) {close ();return false; } 500record_inputs (path ,gguf_ ,layout , true); 501return 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. 507const int wide = MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,nullptr ,0 ); 508 std::vector < wchar_t > wpath ((size_t ) (wide > 0 ?wide :1 )); 509if (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. 521HANDLE f = CreateFileW (wpath .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 522FILE_ATTRIBUTE_NORMAL ,nullptr ); 523if (f == INVALID_HANDLE_VALUE ) { 524err = "FileExpertSource: cannot open " + path ; 525return false; 526 } 527LARGE_INTEGER sz {}; 528if (!GetFileSizeEx (f ,& sz )) { 529CloseHandle (f ); 530err = "FileExpertSource: cannot size " + path ; 531return false; 532 } 533if ((uint64_t )sz .QuadPart != want ) { 534char 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" , 538path .c_str (), (unsigned long long )sz .QuadPart , (unsigned long long )want ); 539CloseHandle (f ); 540err = buf ; 541return false; 542 } 543HANDLE m = CreateFileMappingW (f ,nullptr ,PAGE_READONLY ,0 ,0 ,nullptr ); 544if (m == nullptr ) { 545CloseHandle (f ); 546err = "FileExpertSource: CreateFileMapping failed on " + path ; 547return false; 548 } 549void * view = MapViewOfFile (m ,FILE_MAP_READ ,0 ,0 ,0 ); 550if (view == nullptr ) { 551CloseHandle (m ); 552CloseHandle (f ); 553err = "FileExpertSource: MapViewOfFile failed on " + path ; 554return false; 555 } 556file_ = f ; 557mapping_ = m ; 558base_ = (const uint8_t * )view ; 559paths_ .assign (1 ,path ); 560#else 561const int fd = ::open (path .c_str (),O_RDONLY ); 562if (fd < 0 ) {err = "FileExpertSource: cannot open " + path ;return false; } 563struct stat st {}; 564if (fstat (fd ,& st )!= 0 ) { ::close (fd );err = "FileExpertSource: cannot stat " + path ;return false; } 565if (st .st_size < 0 || (uint64_t )st .st_size != want ) { 566char 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" , 570path .c_str (), (unsigned long long ) (st .st_size < 0 ?0 :st .st_size ), 571 (unsigned long long )want ); 572 ::close (fd ); 573err = buf ; 574return false; 575 } 576void * view = mmap (nullptr , (size_t )want ,PROT_READ ,MAP_SHARED ,fd ,0 ); 577if (view == MAP_FAILED ) { ::close (fd );err = "FileExpertSource: mmap failed on " + path ;return false; } 578fd_ = fd ; 579base_ = (const uint8_t * )view ; 580paths_ .assign (1 ,path );// #286: open_direct opens it again with O_DIRECT 581#endif 582blobs_ = (int64_t )blob_count ; 583n_layers_ = n_layers ; 584n_expert_ = n_expert ; 585mapped_bytes_ = want ; 586layer_offsets_ = std::move (layer_offsets ); 587layer_blob_bytes_ = std::move (layer_blob_bytes ); 588record_inputs (path ,gguf_ ,layout , false); 589return true; 590} 591 592void FileExpertSource ::close () { 593inputs_ .clear (); 594if (complement_arena_ != nullptr ) { 595if (complement_pinned_ && !complement_partial_ )(void )DPCT_CHECK_ERROR ( 596 sycl::free (complement_arena_ , dpct::get_in_order_queue ())); 597else { 598/* 599DPCT1027: The call to cudaHostUnregister was replaced with 0 600because SYCL currently does not support registering of existing host 601memory for use by device. Use USM to allocate memory for use by host 602and device. 603*/ 604if (complement_partial_ )(void )0 ; 605if (complement_locked_ > 0 ) 606 strata::platform::unlock_resident ((uint8_t * )complement_arena_ + complement_lock_off_ ,complement_locked_ ); 607 std::free (complement_arena_ ); 608 } 609 } 610if (xstage_ != nullptr ) { 611if (xstage_pinned_ )(void ) 612DPCT_CHECK_ERROR (sycl::free (xstage_ , dpct::get_in_order_queue ())); 613else std::free (xstage_ ); 614 } 615xstage_ = nullptr ; 616xstage_pinned_ = false; 617xstage_cap_ = 0 ; 618xstage_blob_ = 0 ; 619override_ .clear (); 620staged_ .clear (); 621exchange_storage_ .clear (); 622exchanges_ = 0 ; 623file_reads_ .store (0 ); 624complement_arena_ = nullptr ; 625complement_host_ = nullptr ; 626complement_device_ = nullptr ; 627complement_bytes_ = 0 ; 628complement_offsets_ .clear (); 629complement_pinned_ = false; 630complement_partial_ = false; 631complement_pin_limit_ = 0 ; 632complement_lock_off_ = 0 ; 633complement_ready_ = false; 634complement_locked_ = 0 ; 635complement_lent_slots_ = 0 ; 636if (!maps_ .empty ()) { 637for (Map & m :maps_ ) { 638#if defined(_WIN32 ) 639if (m .base != nullptr )UnmapViewOfFile ((LPCVOID )m .base ); 640if (m .mapping != nullptr )CloseHandle ((HANDLE )m .mapping ); 641if (m .file != nullptr )CloseHandle ((HANDLE )m .file ); 642#else 643if (m .base != nullptr )munmap ((void * )m .base , (size_t )m .bytes ); 644if (m .fd >=0 ) ::close (m .fd ); 645#endif 646 } 647maps_ .clear (); 648base_ = nullptr ;// one of the views above 649 } 650role_ptr_ .clear (); 651role_bytes_ .clear (); 652role_file_ .clear (); 653paths_ .clear (); 654for (void * h :direct_ )close_direct (h ); 655direct_ .clear (); 656 { 657 std::lock_guard < std::mutex > lk (stage_mu_ ); 658stage_buf_ .clear (); 659stage_key_ .clear (); 660stage_epoch_ .clear (); 661stage_used_ .clear (); 662stage_busy_ .clear (); 663stage_of_ .clear (); 664stage_blob_ = 0 ; 665stage_seq_ = 0 ; 666epoch_ = 0 ; 667last_layer_ = -1 ; 668stage_grew_ = false; 669 } 670ram_reads_ .store (0 ); 671warm_stamp_ .reset (); 672warm_hits_ .store (0 ); 673warm_count_ .store (0 ); 674file_read_bytes_ .store (0 ); 675file_blob_bytes_ .store (0 ); 676file_us_ .store (0 ); 677#if defined(_WIN32 ) 678if (base_ != nullptr )UnmapViewOfFile ((LPCVOID )base_ ); 679if (mapping_ != nullptr )CloseHandle ((HANDLE )mapping_ ); 680if (file_ != nullptr )CloseHandle ((HANDLE )file_ ); 681mapping_ = nullptr ; 682file_ = nullptr ; 683#else 684if (base_ != nullptr )munmap ((void * )base_ , (size_t )mapped_bytes_ ); 685if (fd_ >=0 ) ::close (fd_ ); 686fd_ = -1 ; 687#endif 688base_ = nullptr ; 689blobs_ = 0 ; 690n_layers_ = 0 ; 691n_expert_ = 0 ; 692mapped_bytes_ = 0 ; 693layer_offsets_ .clear (); 694layer_blob_bytes_ .clear (); 695reads_ = 0 ; 696} 697 698 699bool ExpertSource ::copy_blob (int64_t layer ,int64_t expert ,uint8_t * dst ) { 700const uint8_t * b = blob (layer ,expert ); 701if (b == nullptr || dst == nullptr )return false; 702 std::memcpy (dst ,b , (size_t ) strata::kernels::cpu::expert_layout ().blob_bytes (layer )); 703return 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 ) { 714const auto & lay = strata::kernels::cpu::expert_layout (); 715if (!check_experts_gguf (gguf_ ,lay ,err )) {err = "FileExpertSource: " + err ;return false; } 716const size_t cut = gguf_ .find_last_of ("/\\" ); 717const std::string dir = cut == std::string::npos ? std::string () :gguf_ .substr (0 ,cut + 1 ); 718 std::map < std::string ,size_t > index ; 719role_ptr_ .assign ((size_t ) (3 * n_layers_ ),nullptr ); 720role_bytes_ .assign ((size_t ) (3 * n_layers_ ),0 ); 721role_file_ .assign ((size_t ) (3 * n_layers_ ),0 ); 722for (int64_t l = 0 ;l < n_layers_ ;++ l ) { 723const auto & fm = lay .fmt [(size_t )l ]; 724const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,lay .bytes [(size_t )l ]- fm .down_off }; 725for (int r = 0 ;r < 3 ;++ r ) { 726const size_t i = (size_t ) (3 * l + r ); 727const std::string path = lay .gguf_file .size ()> i && !lay .gguf_file [i ].empty () ?dir + lay .gguf_file [i ] 728 :gguf_ ; 729auto it = index .find (path ); 730if (it == index .end ()) { 731Map m ; 732#if defined(_WIN32 ) 733const int wide = MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,nullptr ,0 ); 734 std::vector < wchar_t > wpath ((size_t ) (wide > 0 ?wide :1 )); 735if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,wpath .data (),wide ); 736HANDLE f = CreateFileW (wpath .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 737FILE_ATTRIBUTE_NORMAL ,nullptr ); 738LARGE_INTEGER sz {}; 739if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx (f ,& sz )) { 740if (f != INVALID_HANDLE_VALUE )CloseHandle (f ); 741err = "FileExpertSource: cannot open " + path ; 742return false; 743 } 744HANDLE mh = CreateFileMappingW (f ,nullptr ,PAGE_READONLY ,0 ,0 ,nullptr ); 745void * view = mh != nullptr ?MapViewOfFile (mh ,FILE_MAP_READ ,0 ,0 ,0 ) :nullptr ; 746if (view == nullptr ) { 747if (mh != nullptr )CloseHandle (mh ); 748CloseHandle (f ); 749err = "FileExpertSource: cannot map " + path ; 750return false; 751 } 752m .file = f ; 753m .mapping = mh ; 754m .bytes = (uint64_t )sz .QuadPart ; 755m .base = (const uint8_t * )view ; 756#else 757const int fd = ::open (path .c_str (),O_RDONLY ); 758struct stat st {}; 759if (fd < 0 || fstat (fd ,& st )!= 0 || st .st_size <=0 ) { 760if (fd >=0 ) ::close (fd ); 761err = "FileExpertSource: cannot open " + path ; 762return false; 763 } 764void * view = mmap (nullptr , (size_t )st .st_size ,PROT_READ ,MAP_SHARED ,fd ,0 ); 765if (view == MAP_FAILED ) { ::close (fd );err = "FileExpertSource: cannot map " + path ;return false; } 766m .fd = fd ; 767m .bytes = (uint64_t )st .st_size ; 768m .base = (const uint8_t * )view ; 769#endif 770maps_ .push_back (m ); 771paths_ .push_back (path ); 772it = index .emplace (path ,maps_ .size ()- 1 ).first ; 773 } 774const Map & m = maps_ [it -> second ]; 775role_file_ [i ]= (int )it -> second ; 776const uint64_t at = lay .gguf_off [i ],bytes = per [r ]* (uint64_t )n_expert_ ; 777if (at > m .bytes || bytes > m .bytes - at ) {// check_experts_gguf proved it; the mapping must agree 778err = "FileExpertSource: an expert span runs past the end of " + path ; 779return false; 780 } 781role_ptr_ [i ]= m .base + (size_t )at ; 782role_bytes_ [i ]= per [r ]; 783 } 784 } 785base_ = maps_ .front ().base ;// "opened"; mapped_blob answers nullptr in this mode 786warm_stamp_ .reset (new std::atomic < uint32_t > [(size_t ) (n_layers_ * n_expert_ )]()); 787for (uint64_t b :layer_blob_bytes_ )stage_blob_ = std::max (stage_blob_ ,b ); 788return true; 789} 790 791bool FileExpertSource ::copy_from_files (int64_t layer ,int64_t expert ,uint8_t * dst )const { 792if (dst == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return false; 793if (!direct_ .empty ()) {// #286: from the drive; a failed read falls back to the mapping below 794const Fill f {0 ,layer ,expert ,dst }; 795if (read_direct (& f ,1 ))return true; 796direct_fallbacks_ .fetch_add (1 , std::memory_order_relaxed ); 797 } 798if (!role_ptr_ .empty ()) { 799uint64_t at = 0 ; 800for (int r = 0 ;r < 3 ;++ r ) { 801const size_t i = (size_t ) (3 * layer + r ); 802const uint64_t per = role_bytes_ [i ]; 803 std::memcpy (dst + at ,role_ptr_ [i ]+ (size_t ) ((uint64_t )expert * per ), (size_t )per ); 804at += per ; 805 } 806return true; 807 } 808const uint8_t * b = mapped_blob (layer ,expert ); 809if (b == nullptr )return false; 810 std::memcpy (dst ,b , (size_t )layer_blob_bytes_ [(size_t )layer ]); 811return 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 ) { 822constexpr uint64_t kStageSeq = 256 ; 823const uint64_t seq = ++ stage_seq_ ; 824auto it = stage_of_ .find (key ); 825fill = false; 826if (it != stage_of_ .end ()) { 827v = it -> second ; 828stage_epoch_ [v ]= epoch_ ; 829stage_used_ [v ]= seq ; 830return true; 831 } 832v = stage_buf_ .size (); 833uint64_t oldest = std::numeric_limits < uint64_t > ::max (); 834for (size_t i = 0 ;i < stage_buf_ .size ();++ i ) 835if (!stage_busy_ [i ]&& (stage_epoch_ [i ]+ kStageAge <=epoch_ || stage_used_ [i ]+ kStageSeq <=seq )&& 836stage_used_ [i ]< oldest ) { 837oldest = stage_used_ [i ]; 838v = i ; 839 } 840if (v == stage_buf_ .size ()) { 841stage_buf_ .emplace_back (new (std::nothrow )uint8_t [(size_t )stage_blob_ ]); 842if (!stage_buf_ .back ()) {stage_buf_ .pop_back ();return false; } 843stage_key_ .push_back (-1 ); 844stage_epoch_ .push_back (0 ); 845stage_used_ .push_back (0 ); 846stage_busy_ .push_back (0 ); 847if (stage_buf_ .size ()== 512 && !stage_grew_ ) { 848stage_grew_ = true; 849 std::fprintf (stderr ,"FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n" , 850stage_buf_ .size (), (double )stage_buf_ .size ()* (double )stage_blob_ /1073741824.0 ); 851 } 852 }else { 853stage_of_ .erase (stage_key_ [v ]); 854 } 855stage_key_ [v ]= key ; 856stage_epoch_ [v ]= epoch_ ; 857stage_used_ [v ]= seq ; 858stage_busy_ [v ]= 1 ; 859stage_of_ [key ]= v ; 860fill = true; 861return 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 ) { 866const auto t0 = std::chrono::steady_clock::now (); 867const bool ok = copy_from_files (layer ,expert ,dst ); 868publish_stage (v ,layer ,ok , std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count ()); 869return ok ; 870} 871 872void FileExpertSource ::publish_stage (size_t v ,int64_t layer ,bool ok ,double us ) { 873file_us_ .fetch_add ((uint64_t )us , std::memory_order_relaxed ); 874if (ok ) { 875file_read_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 876file_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_ ); 880stage_busy_ [v ]= 0 ; 881if (!ok ) { 882stage_of_ .erase (stage_key_ [v ]); 883stage_key_ [v ]= -1 ; 884 } 885 } 886stage_cv_ .notify_all (); 887} 888 889const uint8_t * FileExpertSource ::staged_blob (int64_t layer ,int64_t expert ) { 890const int64_t key = layer * n_expert_ + expert ; 891size_t v = 0 ; 892bool fill = false; 893uint8_t * dst = nullptr ; 894 { 895 std::unique_lock < std::mutex > lk (stage_mu_ ); 896const bool have = claim_stage (key ,v ,fill ); 897if (!have && !fill )return nullptr ; 898dst = stage_buf_ [v ].get (); 899if (have ) { 900// another thread (a prefetch, the adaptive tier) is filling it: wait for that 901stage_cv_ .wait (lk , [& ] {return !stage_busy_ [v ]|| stage_key_ [v ]!= key ; }); 902if (stage_key_ [v ]!= key )return nullptr ;// its fill failed 903return dst ; 904 } 905 } 906return fill_stage (v ,layer ,expert ,dst ) ?dst :nullptr ; 907} 908 909void FileExpertSource ::prefetch (int64_t layer ,const int64_t * experts ,int64_t n ) { 910if (!staged ()|| n <=0 || layer < 0 || layer >=n_layers_ )return ; 911 std::vector < Fill > todo ; 912 { 913 std::lock_guard < std::mutex > lk (stage_mu_ ); 914for (int64_t i = 0 ;i < n ;++ i ) { 915const int64_t e = experts [i ]; 916if (e < 0 || e >=n_expert_ )continue ; 917const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )e ; 918if (complement_ready_ && resident_blob (index )!= nullptr ) 919continue ;// in the RAM copy 920if (!override_ .empty ()&& override_ [index ]!= nullptr )continue ; 921size_t v = 0 ; 922bool fill = false; 923if (!claim_stage (layer * n_expert_ + e ,v ,fill )&& fill ) { 924todo .push_back ({v ,layer ,e ,stage_buf_ [v ].get ()}); 925if (warm_stamp_ ) { 926const uint32_t s = warm_stamp_ [index ].load (std::memory_order_relaxed ); 927if (s != 0 && (uint64_t )s + 3 >=epoch_ + 1 )warm_hits_ .fetch_add (1 , std::memory_order_relaxed ); 928 } 929 } 930 } 931 } 932fill_many (todo ); 933} 934 935void FileExpertSource ::prefetch_pairs (const std::pair < int32_t ,int32_t >* pairs ,int64_t n ) { 936if (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_ ); 940for (int64_t i = 0 ;i < std::min < int64_t > (n ,64 );++ i ) { 941const int64_t l = pairs [i ].first ,e = pairs [i ].second ; 942if (l < 0 || e < 0 || l >=n_layers_ || e >=n_expert_ )continue ; 943size_t v = 0 ; 944bool fill = false; 945if (!claim_stage (l * n_expert_ + e ,v ,fill )&& fill )todo .push_back ({v ,l ,e ,stage_buf_ [v ].get ()}); 946 } 947 } 948fill_many (todo ); 949} 950 951bool FileExpertSource ::advise_pairs (const std::pair < int32_t ,int32_t >* pairs ,int64_t n )const { 952if (base_ == nullptr || !direct_ .empty ()|| !strata::platform::read_ahead_enabled ())return false; 953for (int64_t i = 0 ;pairs != nullptr && i < n ;++ i ) { 954const int64_t l = pairs [i ].first ,e = pairs [i ].second ; 955if (l < 0 || e < 0 || l >=n_layers_ || e >=n_expert_ )continue ; 956if (role_ptr_ .empty ()) {// experts.bin: the blob is one contiguous range 957if (const uint8_t * b = mapped_blob (l ,e )) strata::platform::advise_willneed (b ,layer_blob_bytes_ [(size_t )l ]); 958continue ; 959 } 960for (int r = 0 ;r < 3 ;++ r ) { 961const 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 } 965return true; 966} 967 968void FileExpertSource ::fill_many (const std::vector < Fill >& todo ) { 969if (todo .empty ())return ; 970if (!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 }; 974auto work = [& ] { 975for (size_t at ; (at = next .fetch_add (16 ))< todo .size ();) { 976const size_t k = std::min < size_t > (16 ,todo .size ()- at ); 977const auto t0 = std::chrono::steady_clock::now (); 978const bool ok = read_direct (todo .data ()+ at ,k ); 979const double us = std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (); 980for (size_t i = at ;i < at + k ;++ i ) { 981const Fill & f = todo [i ]; 982// a failed batch: each blob again on its own (copy_from_files falls back to the mapping) 983if (ok )publish_stage (f .v ,f .layer , true,us / (double )k ); 984else (void )fill_stage (f .v ,f .layer ,f .e ,f .dst ); 985 } 986 } 987 }; 988const size_t nt = std::min < size_t > (4 , (todo .size ()+ 15 ) /16 ); 989 std::vector < std::thread > th ; 990for (size_t t = 1 ;t < nt ;++ t )th .emplace_back (work ); 991work (); 992for (auto & t :th )t .join (); 993return ; 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 { 1000using Pvm = BOOL (WINAPI * )(HANDLE ,ULONG_PTR ,PWIN32_MEMORY_RANGE_ENTRY ,ULONG ); 1001static const Pvm pvm = [] { 1002const char * v = std::getenv ("STRATA_FETCH_PVM" ); 1003if (v != nullptr && std::atoi (v )== 0 )return (Pvm )nullptr ; 1004return (Pvm ) (void * )GetProcAddress (GetModuleHandleW (L"kernel32.dll" ),"PrefetchVirtualMemory" ); 1005 }(); 1006if (pvm != nullptr ) { 1007 std::vector < WIN32_MEMORY_RANGE_ENTRY > ranges ; 1008ranges .reserve (todo .size ()* 3 ); 1009for (const Fill & f :todo ) 1010for (int r = 0 ;r < 3 ;++ r ) { 1011const size_t i = (size_t ) (3 * f .layer + r ); 1012ranges .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 }; 1021auto work = [& ] { 1022for (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 }; 1025const size_t nt = std::min < size_t > (todo .size (), (size_t )fetch_threads_ ); 1026 std::vector < std::thread > th ; 1027for (size_t t = 1 ;t < nt ;++ t )th .emplace_back (work ); 1028work (); 1029for (auto & t :th )t .join (); 1030} 1031 1032uint64_t FileExpertSource ::expert_bytes ()const { 1033uint64_t total = 0 ; 1034for (uint64_t b :layer_blob_bytes_ )total += b * (uint64_t )n_expert_ ; 1035return total ; 1036} 1037 1038bool FileExpertSource ::open_direct (std::string & why ) { 1039#if defined(_WIN32 ) 1040for (const std::string & path :paths_ ) { 1041const 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' ); 1043if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,w .data (),wide ); 1044HANDLE h = CreateFileW (w .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 1045FILE_FLAG_NO_BUFFERING |FILE_FLAG_OVERLAPPED ,nullptr ); 1046if (h == INVALID_HANDLE_VALUE ) { 1047why += "; cannot open " + path + " unbuffered (error " + std::to_string ((unsigned long long )GetLastError ())+ 1048"), read through the file cache" ; 1049for (void * d :direct_ )CloseHandle ((HANDLE )d ); 1050direct_ .clear (); 1051return false; 1052 } 1053direct_ .push_back (h ); 1054 } 1055if (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_ ); 1057for (uint64_t b :layer_blob_bytes_ )stage_blob_ = std::max (stage_blob_ ,b ); 1058 } 1059return 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) 1062for (const std::string & path :paths_ ) { 1063const int fd = ::open (path .c_str (),O_RDONLY |O_DIRECT |O_CLOEXEC ); 1064if (fd < 0 ) { 1065why += "; cannot open " + path + " with O_DIRECT (" + std::strerror (errno )+ "), read through the file cache" ; 1066for (void * d :direct_ )close_direct (d ); 1067direct_ .clear (); 1068return false; 1069 } 1070direct_ .push_back ((void * ) (intptr_t )fd ); 1071 } 1072if (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_ ); 1074for (uint64_t b :layer_blob_bytes_ )stage_blob_ = std::max (stage_blob_ ,b ); 1075 } 1076return true; 1077#else 1078 (void )why ; 1079return false; 1080#endif 1081} 1082 1083bool FileExpertSource ::set_unbuffered (uint64_t ram_bytes , std::string & why ) { 1084#if defined(_WIN32 )|| defined(__linux__ ) 1085if (base_ == nullptr || paths_ .empty ()|| !direct_ .empty ()) { 1086why = !direct_ .empty () ?"already unbuffered" :"no expert files open" ; 1087return !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 1091const uint64_t experts = expert_bytes (); 1092const uint64_t arena = std::min (ram_bytes ,experts ); 1093if (!file_tier_unbuffered (paths_ ,arena ,experts - arena ,why ))return false; 1094return open_direct (why ); 1095#else 1096 (void )ram_bytes ; 1097why = "through the file cache (no unbuffered reads on this platform)" ; 1098return false; 1099#endif 1100} 1101 1102bool FileExpertSource ::recheck_unbuffered (std::string & why ) { 1103#if defined(_WIN32 )|| defined(__linux__ ) 1104if (const char * env = std::getenv ("STRATA_UNBUFFERED_LOAD" );env != nullptr && env [0 ]!= '\0' ) { 1105why = std::string ("STRATA_UNBUFFERED_LOAD=" )+ env ; 1106return !direct_ .empty (); 1107 } 1108if (base_ == nullptr || paths_ .empty ()) { 1109why = "no expert files open" ; 1110return 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 1115const uint64_t experts = expert_bytes (); 1116const uint64_t read = experts > complement_bytes_ ?experts - complement_bytes_ :0 ; 1117 std::string w ; 1118const bool ub = file_tier_unbuffered (paths_ ,0 ,read ,w ); 1119char head [96 ]; 1120 std::snprintf (head ,sizeof head ,"re-checked with the RAM copy built (%.2f GiB): " , 1121 (double )complement_bytes_ /1073741824.0 ); 1122why = head + w ; 1123if (ub == !direct_ .empty ())return ub ; 1124if (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) 1126for (void * d :direct_ )close_direct (d ); 1127direct_ .clear (); 1128return false; 1129#else 1130why = "through the file cache (no unbuffered reads on this platform)" ; 1131return 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. 1141constexpr uint64_t kSector = 4096 ,kGap = 1ull <<20 ,kMerge = 32ull <<20 ; 1142struct Window {int file ;uint64_t a0 ,size ,skip ,n ,at ;uint8_t * dst ;size_t req ;uint64_t in_req ; }; 1143struct Req {HANDLE h ;uint64_t a0 ,size ,pos ; }; 1144// this thread's aligned buffer and events, kept for its next batch 1145struct Scratch { 1146uint8_t * buf = nullptr ; 1147size_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 () { 1155if (buf != nullptr )VirtualFree (buf ,0 ,MEM_RELEASE ); 1156for (HANDLE e :ev )CloseHandle (e ); 1157 } 1158 }; 1159 thread_localScratch sc ; 1160sc .win .clear (); 1161for (size_t k = 0 ;k < n ;++ k ) { 1162const Fill & f = fills [k ]; 1163if (f .dst == nullptr || f .layer < 0 || f .e < 0 || f .layer >=n_layers_ || f .e >=n_expert_ )return false; 1164if (role_ptr_ .empty ()) {// experts.bin: the blob is one contiguous range 1165const uint64_t per = layer_blob_bytes_ [(size_t )f .layer ]; 1166const uint64_t off = layer_offsets_ [(size_t )f .layer ]+ (uint64_t )f .e * per ; 1167const uint64_t a0 = off /kSector * kSector ,a1 = (off + per + kSector - 1 ) /kSector * kSector ; 1168sc .win .push_back ({0 ,a0 ,a1 - a0 ,off - a0 ,per ,0 ,f .dst ,0 ,0 }); 1169continue ; 1170 } 1171uint64_t at = 0 ; 1172for (int r = 0 ;r < 3 ;++ r ) { 1173const size_t i = (size_t ) (3 * f .layer + r ); 1174const uint64_t per = role_bytes_ [i ]; 1175const Map & m = maps_ [(size_t )role_file_ [i ]]; 1176const uint64_t off = (uint64_t ) (role_ptr_ [i ]- m .base )+ (uint64_t )f .e * per ; 1177const uint64_t a0 = off /kSector * kSector ,a1 = (off + per + kSector - 1 ) /kSector * kSector ; 1178sc .win .push_back ({role_file_ [i ],a0 ,a1 - a0 ,off - a0 ,per ,at ,f .dst ,0 ,0 }); 1179at += per ; 1180 } 1181 } 1182sc .order .resize (sc .win .size ()); 1183for (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 ) { 1185return 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 }); 1187sc .req .clear (); 1188uint64_t total = 0 ; 1189int last_file = -1 ; 1190for (size_t w :sc .order ) { 1191Window & x = sc .win [w ]; 1192if (!sc .req .empty ()&& x .file == last_file ) { 1193Req & q = sc .req .back (); 1194const uint64_t end = q .a0 + q .size ,xend = x .a0 + x .size ; 1195if (x .a0 <=end + kGap && std::max (end ,xend )- q .a0 <=kMerge ) { 1196if (xend > end ) { 1197total += xend - end ; 1198q .size = xend - q .a0 ; 1199 } 1200x .req = sc .req .size ()- 1 ; 1201x .in_req = x .a0 - q .a0 ; 1202continue ; 1203 } 1204 } 1205sc .req .push_back ({(HANDLE )direct_ [(size_t )x .file ],x .a0 ,x .size ,total }); 1206total += x .size ; 1207last_file = x .file ; 1208x .req = sc .req .size ()- 1 ; 1209x .in_req = 0 ; 1210 } 1211if (total > sc .cap ) { 1212if (sc .buf != nullptr )VirtualFree (sc .buf ,0 ,MEM_RELEASE ); 1213sc .cap = (size_t ) ((total + (1u <<20 )- 1 ) >>20 <<20 ); 1214sc .buf = (uint8_t * )VirtualAlloc (nullptr ,sc .cap ,MEM_COMMIT |MEM_RESERVE ,PAGE_READWRITE ); 1215if (sc .buf == nullptr ) {sc .cap = 0 ;return false; } 1216 } 1217while (sc .ev .size ()< sc .req .size ()) { 1218HANDLE e = CreateEventW (nullptr , TRUE, FALSE,nullptr ); 1219if (e == nullptr )return false; 1220sc .ev .push_back (e ); 1221 } 1222sc .ov .assign (sc .req .size (),OVERLAPPED {}); 1223// every request in flight before the first wait: the drive sees the whole batch as one queue 1224size_t issued = 0 ; 1225bool ok = true; 1226for (size_t q = 0 ;q < sc .req .size ();++ q ) { 1227const Req & r = sc .req [q ]; 1228OVERLAPPED & o = sc .ov [q ]; 1229o .Offset = (DWORD )r .a0 ; 1230o .OffsetHigh = (DWORD ) (r .a0 >>32 ); 1231o .hEvent = sc .ev [q ]; 1232if (!ReadFile (r .h ,sc .buf + r .pos , (DWORD )r .size ,nullptr ,& o )&& GetLastError ()!= ERROR_IO_PENDING ) { 1233ok = false; 1234break ; 1235 } 1236++ issued ; 1237 } 1238 std::vector < DWORD >& got = sc .got ; 1239got .assign (sc .req .size (),0 ); 1240for (size_t q = 0 ;q < issued ;++ q ) 1241if (!GetOverlappedResult (sc .req [q ].h ,& sc .ov [q ],& got [q ], TRUE))ok = false; 1242if (!ok || issued < sc .req .size ())return false; 1243for (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 1245if ((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 } 1248return 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. 1255constexpr uint64_t kSector = 4096 ,kMerge = 32ull <<20 ; 1256constexpr long kDepth = 256 ;// requests in flight per thread; a larger batch is read in waves of this many 1257struct Window {int file ;uint64_t a0 ,size ,skip ,n ,at ;uint8_t * dst ;size_t req ;uint64_t in_req ; }; 1258struct Req {int fd ;uint64_t a0 ,size ,pos ; }; 1259struct Scratch { 1260uint8_t * buf = nullptr ; 1261size_t cap = 0 ; 1262aio_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 ); 1272if (ctx != 0 ) (void )syscall (SYS_io_destroy ,ctx ); 1273 } 1274 }; 1275 thread_localScratch sc ; 1276if (sc .ctx == 0 && syscall (SYS_io_setup ,kDepth ,& sc .ctx )!= 0 ) { 1277sc .ctx = 0 ; 1278return false;// no AIO (a seccomp profile, aio-max-nr): the caller falls back to the mapped copy 1279 } 1280sc .win .clear (); 1281for (size_t k = 0 ;k < n ;++ k ) { 1282const Fill & f = fills [k ]; 1283if (f .dst == nullptr || f .layer < 0 || f .e < 0 || f .layer >=n_layers_ || f .e >=n_expert_ )return false; 1284if (role_ptr_ .empty ()) {// experts.bin: the blob is one contiguous range 1285const uint64_t per = layer_blob_bytes_ [(size_t )f .layer ]; 1286const uint64_t off = layer_offsets_ [(size_t )f .layer ]+ (uint64_t )f .e * per ; 1287const uint64_t a0 = off /kSector * kSector ,a1 = (off + per + kSector - 1 ) /kSector * kSector ; 1288sc .win .push_back ({0 ,a0 ,a1 - a0 ,off - a0 ,per ,0 ,f .dst ,0 ,0 }); 1289continue ; 1290 } 1291uint64_t at = 0 ; 1292for (int r = 0 ;r < 3 ;++ r ) { 1293const size_t i = (size_t ) (3 * f .layer + r ); 1294const uint64_t per = role_bytes_ [i ]; 1295const Map & m = maps_ [(size_t )role_file_ [i ]]; 1296const uint64_t off = (uint64_t ) (role_ptr_ [i ]- m .base )+ (uint64_t )f .e * per ; 1297const uint64_t a0 = off /kSector * kSector ,a1 = (off + per + kSector - 1 ) /kSector * kSector ; 1298sc .win .push_back ({role_file_ [i ],a0 ,a1 - a0 ,off - a0 ,per ,at ,f .dst ,0 ,0 }); 1299at += per ; 1300 } 1301 } 1302sc .order .resize (sc .win .size ()); 1303for (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 ) { 1305return 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 }); 1307sc .req .clear (); 1308uint64_t total = 0 ; 1309int last_file = -1 ; 1310for (size_t w :sc .order ) { 1311Window & x = sc .win [w ]; 1312if (!sc .req .empty ()&& x .file == last_file ) { 1313Req & q = sc .req .back (); 1314const uint64_t end = q .a0 + q .size ,xend = x .a0 + x .size ; 1315if (x .a0 <=end && std::max (end ,xend )- q .a0 <=kMerge ) { 1316if (xend > end ) { 1317total += xend - end ; 1318q .size = xend - q .a0 ; 1319 } 1320x .req = sc .req .size ()- 1 ; 1321x .in_req = x .a0 - q .a0 ; 1322continue ; 1323 } 1324 } 1325sc .req .push_back ({(int ) (intptr_t )direct_ [(size_t )x .file ],x .a0 ,x .size ,total }); 1326total += x .size ; 1327last_file = x .file ; 1328x .req = sc .req .size ()- 1 ; 1329x .in_req = 0 ; 1330 } 1331if (total > sc .cap ) { 1332 std::free (sc .buf ); 1333sc .cap = (size_t ) ((total + (1u <<20 )- 1 ) >>20 <<20 ); 1334void * p = nullptr ; 1335sc .buf = posix_memalign (& p , (size_t )kSector ,sc .cap )== 0 ? (uint8_t * )p :nullptr ; 1336if (sc .buf == nullptr ) {sc .cap = 0 ;return false; } 1337 } 1338sc .got .assign (sc .req .size (),-1 ); 1339sc .cb .resize (std::min < size_t > (sc .req .size (), (size_t )kDepth )); 1340sc .cbp .resize (sc .cb .size ()); 1341sc .ev .resize (sc .cb .size ()); 1342bool ok = true; 1343for (size_t w0 = 0 ;ok && w0 < sc .req .size ();w0 += (size_t )kDepth ) { 1344const size_t wn = std::min < size_t > ((size_t )kDepth ,sc .req .size ()- w0 ); 1345for (size_t j = 0 ;j < wn ;++ j ) { 1346const Req & r = sc .req [w0 + j ]; 1347iocb & c = sc .cb [j ]; 1348 std::memset (& c ,0 ,sizeof c ); 1349c .aio_lio_opcode = IOCB_CMD_PREAD ; 1350c .aio_fildes = (uint32_t )r .fd ; 1351c .aio_buf = (uint64_t ) (uintptr_t ) (sc .buf + r .pos ); 1352c .aio_nbytes = r .size ; 1353c .aio_offset = (int64_t )r .a0 ; 1354c .aio_data = (uint64_t ) (w0 + j ); 1355sc .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) 1359size_t queued = 0 ; 1360while (queued < wn ) { 1361const long r = syscall (SYS_io_submit ,sc .ctx , (long ) (wn - queued ),sc .cbp .data ()+ queued ); 1362if (r > 0 ) {queued += (size_t )r ;continue ; } 1363if (r < 0 && errno == EINTR )continue ; 1364ok = false; 1365break ; 1366 } 1367for (size_t done = 0 ;done < queued ;) { 1368const long r = syscall (SYS_io_getevents ,sc .ctx ,1L , (long ) (queued - done ),sc .ev .data (),nullptr ); 1369if (r < 0 ) { 1370if (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 ); 1373sc .ctx = 0 ; 1374return false; 1375 } 1376for (long j = 0 ;j < r ;++ j ) { 1377const io_event & e = sc .ev [(size_t )j ]; 1378sc .got [(size_t )e .data ]= e .res ; 1379if (e .res < 0 )ok = false; 1380 } 1381done += (size_t )r ; 1382 } 1383 } 1384if (!ok )return false; 1385for (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 1387if (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 } 1390return true; 1391#else 1392 (void )fills ; (void )n ; 1393return false; 1394#endif 1395} 1396 1397void FileExpertSource ::warm (int64_t layer ,const int64_t * experts ,int64_t n ) { 1398if (role_ptr_ .empty ()|| n <=0 || layer < 0 || layer >=n_layers_ )return ; 1399uint32_t stamp ; 1400 { 1401 std::lock_guard < std::mutex > lk (stage_mu_ ); 1402stamp = (uint32_t )epoch_ + 1 ; 1403 } 1404#if defined(_WIN32 ) 1405using Pvm = BOOL (WINAPI * )(HANDLE ,ULONG_PTR ,PWIN32_MEMORY_RANGE_ENTRY ,ULONG ); 1406static const Pvm pvm = (Pvm ) (void * )GetProcAddress (GetModuleHandleW (L"kernel32.dll" ),"PrefetchVirtualMemory" ); 1407 std::vector < WIN32_MEMORY_RANGE_ENTRY > ranges ; 1408#endif 1409for (int64_t j = 0 ;j < n ;++ j ) { 1410const int64_t e = experts [j ]; 1411if (e < 0 || e >=n_expert_ )continue ; 1412const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )e ; 1413if (complement_ready_ && resident_blob (index )!= nullptr ) 1414continue ;// in the RAM copy 1415if (warm_stamp_ )warm_stamp_ [index ].store (stamp , std::memory_order_relaxed ); 1416warm_count_ .fetch_add (1 , std::memory_order_relaxed ); 1417for (int r = 0 ;r < 3 ;++ r ) { 1418const size_t i = (size_t ) (3 * layer + r ); 1419const uint8_t * p = role_ptr_ [i ]+ (size_t ) ((uint64_t )e * role_bytes_ [i ]); 1420#if defined(_WIN32 ) 1421ranges .push_back ({(PVOID )p , (SIZE_T )role_bytes_ [i ]}); 1422#else 1423const 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 ) 1429if (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_ ); 1436quit_ = true; 1437 } 1438cv_ .notify_all (); 1439if (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 , 1443ExpertSource * src , std::string & err ) { 1444if (src == nullptr || !src -> warms ()) {err = "RouterLookahead: the expert source does not warm" ;return false; } 1445if (n_embd %8 != 0 ) {err = "RouterLookahead: n_embd is not a multiple of 8" ;return false; } 1446for (const auto & r :routers ) 1447if (r .size ()!= (size_t ) (n_embd * n_expert )) {err = "RouterLookahead: a router of another shape" ;return false; } 1448routers_ = std::move (routers ); 1449n_embd_ = n_embd ; 1450n_expert_ = n_expert ; 1451k_ = k < 1 ?1 :k > (int )n_expert ? (int )n_expert :k ; 1452src_ = src ; 1453x_ .assign ((size_t ) (8 * n_embd ),0.f ); 1454thread_ = std::thread ([this ] {run (); }); 1455return true; 1456} 1457 1458void RouterLookahead ::submit (int64_t layer ,const float * x ,int64_t n_tok ,const int32_t * host_res ) { 1459if (layer + 1 >= (int64_t )routers_ .size ()|| n_tok <=0 || x == nullptr )return ; 1460 { 1461 std::lock_guard < std::mutex > lk (mu_ ); 1462if (busy_ || pending_ ) {skipped_ .fetch_add (1 , std::memory_order_relaxed );return ; } 1463n_tok_ = std::min < int64_t > (n_tok ,8 ); 1464 std::memcpy (x_ .data (),x , (size_t ) (n_tok_ * n_embd_ )* sizeof (float )); 1465layer_ = layer + 1 ; 1466host_res_ = host_res ; 1467pending_ = true; 1468 } 1469cv_ .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 ; 1476for (;;) { 1477int64_t layer ,nt ; 1478const int32_t * host_res ; 1479 { 1480 std::unique_lock < std::mutex > lk (mu_ ); 1481cv_ .wait (lk , [& ] {return quit_ || pending_ ; }); 1482if (quit_ )return ; 1483pending_ = false; 1484busy_ = true; 1485layer = layer_ ; 1486nt = n_tok_ ; 1487host_res = host_res_ ; 1488 } 1489const auto t0 = std::chrono::steady_clock::now (); 1490want .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. 1495if (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_ , 1497x_ .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) 1504const uint16_t * rw = routers_ [(size_t )layer ].data (); 1505for (int64_t r = 0 ;r < n_expert_ ;++ r ) { 1506const uint16_t * wr = rw + (size_t )r * (size_t )n_embd_ ; 1507for (int64_t t = 0 ;t < nt ;++ t ) { 1508const float * xr = x_ .data ()+ (size_t )t * (size_t )n_embd_ ; 1509float acc = 0.0f ; 1510for (int64_t c = 0 ;c < n_embd_ ;++ c ) { 1511const uint32_t bits = (uint32_t )wr [c ] <<16 ; 1512float wf ; 1513 std::memcpy (& wf ,& bits ,sizeof wf ); 1514acc += wf * xr [c ]; 1515 } 1516logits [(size_t )t * (size_t )n_expert_ + (size_t )r ]= acc ; 1517 } 1518 } 1519 } 1520for (int64_t t = 0 ;t < nt ;++ t ) { 1521const float * lt = logits .data ()+ (size_t ) (t * n_expert_ ); 1522for (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 ]; }); 1525for (int j = 0 ;j < k_ ;++ j ) { 1526const int64_t e = order [(size_t )j ]; 1527if (host_res != nullptr && host_res [(size_t ) (layer * n_expert_ + e )] >=0 )continue ;// on the GPU 1528if (std::find (want .begin (),want .end (),e )== want .end ())want .push_back (e ); 1529 } 1530 } 1531src_ -> warm (layer ,want .data (), (int64_t )want .size ()); 1532predicted_ .fetch_add ((int64_t )want .size (), std::memory_order_relaxed ); 1533busy_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_ ); 1537busy_ = 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 ; 1545if (!staged ())return ; 1546 std::lock_guard < std::mutex > lk (stage_mu_ ); 1547if (layer != last_layer_ ) { 1548++ epoch_ ; 1549last_layer_ = layer ; 1550 } 1551} 1552 1553bool FileExpertSource ::transient (int64_t layer ,int64_t expert )const { 1554if (!staged ()|| layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return false; 1555const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 1556if (complement_ready_ && resident_blob (index )!= nullptr ) 1557return false; 1558return override_ .empty ()|| override_ [index ]== nullptr ; 1559} 1560 1561bool FileExpertSource ::copy_blob (int64_t layer ,int64_t expert ,uint8_t * dst ) { 1562if (base_ == nullptr || dst == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ ) 1563return false; 1564const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 1565const uint64_t bytes = layer_blob_bytes_ [(size_t )layer ]; 1566if (complement_ready_ ) { 1567const uint8_t * held = 1568resident_blob (index ); 1569if (held == nullptr && !override_ .empty ())held = override_ [index ]; 1570if (held != nullptr ) { 1571 std::memcpy (dst ,held , (size_t )bytes ); 1572return true; 1573 } 1574 } 1575const auto t0 = std::chrono::steady_clock::now (); 1576if (!copy_from_files (layer ,expert ,dst ))return false; 1577file_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 1578 std::memory_order_relaxed ); 1579file_read_bytes_ .fetch_add (bytes , std::memory_order_relaxed ); 1580return true; 1581} 1582 1583const uint8_t * FileExpertSource ::mapped_blob (int64_t layer ,int64_t expert )const { 1584if (!role_ptr_ .empty ())return nullptr ;// the GGUF in place: no contiguous blob in any file 1585if (base_ == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return nullptr ; 1586const size_t i = (size_t )layer ; 1587if (i >=layer_offsets_ .size ()|| i >=layer_blob_bytes_ .size ())return nullptr ; 1588const uint64_t blob_bytes = layer_blob_bytes_ [i ]; 1589if (blob_bytes == 0 || (uint64_t )expert > std::numeric_limits < uint64_t > ::max () /blob_bytes )return nullptr ; 1590const uint64_t expert_offset = (uint64_t )expert * blob_bytes ; 1591const uint64_t layer_offset = layer_offsets_ [i ]; 1592if (layer_offset > mapped_bytes_ || expert_offset > mapped_bytes_ - layer_offset )return nullptr ; 1593const uint64_t offset = layer_offset + expert_offset ; 1594if (blob_bytes > mapped_bytes_ - offset )return nullptr ; 1595return base_ + (size_t )offset ; 1596} 1597 1598uint64_t FileExpertSource ::release (int64_t layer ,int64_t expert ) { 1599#if defined(_WIN32 ) 1600static const bool enabled = [] { 1601const char * v = std::getenv ("STRATA_FILE_RELEASE" ); 1602return v != nullptr && std::strcmp (v ,"1" )== 0 ; 1603 }(); 1604if (!enabled || base_ == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ ) 1605return 0 ; 1606static const uint64_t page = [] { 1607SYSTEM_INFO info {}; 1608GetSystemInfo (& info ); 1609return (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. 1613auto trim = [& ](const uint8_t * p ,uint64_t bytes )-> uint64_t { 1614const uint64_t misalignment = (uintptr_t )p %page ; 1615const uint64_t skip = misalignment == 0 ?0 :page - misalignment ; 1616if (bytes <=skip )return 0 ; 1617const uint64_t whole = (bytes - skip ) /page * page ; 1618if (whole == 0 )return 0 ; 1619SetLastError (ERROR_SUCCESS ); 1620if (!VirtualUnlock ((LPVOID ) (p + (size_t )skip ), (SIZE_T )whole )) { 1621const DWORD error = GetLastError (); 1622// VirtualUnlock trims an unlocked range and reports FALSE / ERROR_NOT_LOCKED for that success. 1623if (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 ); 1629return 0 ; 1630 } 1631 } 1632return whole ;// bytes advised, not a measurement of physical RAM reclaimed 1633 }; 1634if (role_ptr_ .empty ()) { 1635const uint8_t * p = mapped_blob (layer ,expert ); 1636return p == nullptr ?0 :trim (p ,layer_blob_bytes_ [(size_t )layer ]); 1637 } 1638uint64_t bytes = 0 ; 1639for (int r = 0 ;r < 3 ;++ r ) { 1640const size_t i = (size_t ) (3 * layer + r ); 1641bytes += trim (role_ptr_ [i ]+ (size_t ) ((uint64_t )expert * role_bytes_ [i ]),role_bytes_ [i ]); 1642 } 1643return bytes ; 1644#else 1645 (void )layer ; (void )expert ; 1646return 0 ; 1647#endif 1648} 1649 1650bool FileExpertSource ::pin_cache_complement ( 1651const ExpertCache & cache , std::string & err ,bool pin , 1652const std::vector < std::pair < int32_t ,int32_t >> & additional_gpu_pairs , 1653int64_t lend_from_slot ,uint64_t headroom_bytes ,uint64_t budget_bytes , 1654const std::vector < std::pair < int32_t ,int32_t >> * rank )try { 1655err .clear (); 1656const auto pin_t0 = std::chrono::steady_clock::now (); 1657if (base_ == nullptr ) {err = "FileExpertSource: open the mapped experts before pinning a complement" ;return false; } 1658if (complement_ready_ ) {err = "FileExpertSource: the cache complement is already pinned" ;return false; } 1659if (!cache .valid ()) {err = "FileExpertSource: the GPU expert cache is not open" ;return false; } 1660if (cache .fills ()!= cache .resident ()) { 1661err = "FileExpertSource: the GPU expert cache is not fully filled" ; 1662return false; 1663 } 1664const dpct::err0 sync = 1665DPCT_CHECK_ERROR (dpct::get_current_device ().queues_wait_and_throw ()); 1666/* 1667DPCT1000: Error handling if-stmt was detected but could not be 1668rewritten. 1669*/ 1670if (sync != 0 ) { 1671/* 1672DPCT1009: SYCL reports errors using exceptions and does not use 1673error codes. Please replace the "get_error_string_dummy(...)" with a 1674real error-handling function. 1675*/ 1676/* 1677DPCT1001: The statement could not be removed. 1678*/ 1679err = std::string ("FileExpertSource: GPU expert cache is not ready: " )+ 1680 dpct::get_error_string_dummy (sync ); 1681/* 1682DPCT1010: SYCL uses exceptions to report errors and does not use 1683the error codes. The cudaGetLastError function call was replaced with 0. 1684You need to rewrite this code. 1685*/ 1686 (void )0 ; 1687return false; 1688 } 1689 1690// The GPU cache's experts, and the bytes each slot's expert takes here (for the lend region below). 1691const 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 ); 1695primary_gpu_pairs .reserve ((size_t )cache .resident ()); 1696pair_slot .reserve ((size_t )cache .resident ()); 1697for (int64_t layer = 0 ;layer < n_layers_ ;++ layer ) { 1698for (int64_t expert = 0 ;expert < n_expert_ ;++ expert ) { 1699const int32_t slot = cache .slot_of (layer ,expert ); 1700if (slot == kNotResident )continue ; 1701primary_gpu_pairs .emplace_back ((int32_t )layer , (int32_t )expert ); 1702pair_slot .push_back (slot ); 1703if (slot >=0 && slot < n_slots )slot_bytes [(size_t )slot ]= layer_blob_bytes_ [(size_t )layer ]; 1704 } 1705 } 1706 std::vector < uint64_t > offsets ; 1707uint64_t bytes = 0 ; 1708if (!detail::make_cache_complement_plan (n_layers_ ,n_expert_ ,layer_blob_bytes_ ,primary_gpu_pairs , 1709additional_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 { 1716uint64_t before = 0 ,after = 0 ; 1717const bool read_before = available_memory_bytes (before ); 1718 (void )SetProcessWorkingSetSize (GetCurrentProcess (), (SIZE_T )- 1 , (SIZE_T )- 1 ); 1719if (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 1725const bool what_fits = budget_bytes == kResidentWhatFits ;// #467: the soft mode's second try 1726uint64_t budget_physical = 0 ;// #403: reuse the memory snapshot a budget was sized from 1727uint64_t budget_commit = std::numeric_limits < uint64_t > ::max (); 1728if (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). 1731uint64_t physical = 0 ; 1732if (!available_memory_bytes (physical ,& budget_commit )) { 1733err = "FileExpertSource: cannot determine available memory for --resident-budget-gib" ; 1734return false; 1735 } 1736budget_physical = physical ; 1737const uint64_t available = std::min (physical ,budget_commit ); 1738const char * limit = budget_commit < physical ?"commit" :"RAM" ; 1739const uint64_t clamped = detail::clamp_resident_budget (budget_bytes ,physical ,budget_commit ,headroom_bytes ); 1740if (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. 1744if (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 ); 1749else 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 ); 1754budget_bytes = clamped ; 1755 } 1756 std::vector < uint64_t > ranked (offsets .size (),kNoComplement ); 1757uint64_t at = 0 ; 1758int64_t held = 0 ; 1759if (rank != nullptr ) 1760for (const auto & pr :* rank ) { 1761if (pr .first < 0 || pr .second < 0 || pr .first >=n_layers_ || pr .second >=n_expert_ )continue ; 1762const size_t i = (size_t )pr .first * (size_t )n_expert_ + (size_t )pr .second ; 1763if (offsets [i ]== kNoComplement || ranked [i ]!= kNoComplement )continue ;// on a GPU, or twice 1764const uint64_t b = layer_blob_bytes_ [(size_t )pr .first ]; 1765if (b > budget_bytes - at )continue ; 1766ranked [i ]= at ; 1767at += b ; 1768++ held ; 1769 } 1770if (what_fits && held == 0 ) {// #467: nothing to keep - the caller's plain mmap fallback, not an empty copy 1771err = "FileExpertSource: available memory cannot hold any expert of the complement" ; 1772return 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 ); 1777offsets .swap (ranked ); 1778bytes = at ; 1779lend_from_slot = -1 ; 1780 } 1781 1782const bool lend = lend_from_slot >=0 && lend_from_slot < n_slots && additional_gpu_pairs .empty (); 1783uint64_t budget = std::numeric_limits < uint64_t > ::max (); 1784if (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.) 1787uint64_t physical = budget_physical ; 1788uint64_t commit = budget_commit ; 1789if (physical == 0 && !available_memory_bytes (physical ,& commit )) { 1790err = "FileExpertSource: cannot determine available memory for the resident-memory safety check" ; 1791return false; 1792 } 1793const uint64_t available = std::min (physical ,commit ); 1794budget = available > headroom_bytes ?available - headroom_bytes :0 ; 1795if (bytes > budget ) { 1796char 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 ); 1802err = message ; 1803return 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. 1809int64_t keep_from = n_slots ; 1810if (lend ) { 1811keep_from = detail::choose_resident_keep_from (slot_bytes ,bytes ,budget ,lend_from_slot ); 1812if (keep_from < 0 )keep_from = n_slots ; 1813if (keep_from < n_slots ) { 1814 std::vector < std::pair < int32_t ,int32_t >> core ; 1815core .reserve (primary_gpu_pairs .size ()); 1816for (size_t i = 0 ;i < primary_gpu_pairs .size ();++ i ) 1817if (pair_slot [i ]< keep_from )core .push_back (primary_gpu_pairs [i ]); 1818if (!detail::make_cache_complement_plan (n_layers_ ,n_expert_ ,layer_blob_bytes_ ,core , 1819additional_gpu_pairs ,offsets ,bytes ,err ))return false; 1820 } 1821 } 1822 1823void * arena = nullptr ; 1824const uint8_t * host = nullptr ; 1825const uint8_t * device = nullptr ; 1826bool pinned_ok = false; 1827uint64_t locked = 0 ; 1828uint64_t partial_pin = 0 ;///< CS-T: a registered prefix of a locked arena 1829uint64_t lock_off = 0 ;///< where the working-set lock starts (after the registered prefix) 1830 std::string note ; 1831auto release = [& ]() { 1832try { 1833if (arena == nullptr )return ; 1834if (pinned_ok )(void ) 1835DPCT_CHECK_ERROR (sycl::free (arena , dpct::get_in_order_queue ())); 1836else { 1837/* 1838DPCT1027: The call to cudaHostUnregister was replaced with 0 1839because SYCL currently does not support registering of existing host 1840memory for use by device. Use USM to allocate memory for use by host 1841and device. 1842*/ 1843if (partial_pin > 0 )(void )0 ; 1844if (locked > 0 ) strata::platform::unlock_resident ((uint8_t * )arena + lock_off ,locked ); 1845 std::free (arena ); 1846 } 1847arena = nullptr ; 1848 } 1849catch (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 }; 1855if (bytes > 0 ) { 1856 std::fprintf (stderr ,"FileExpertSource: allocating %.2f GiB %s cache complement\n" , 1857 (double )bytes /1073741824.0 ,pin ?"page-locked" :"pageable resident" ); 1858log_complement_memory ("before complement allocation" ,bytes ); 1859 std::fflush (stderr ); 1860if (pin ) { 1861const dpct::err0 allocated = DPCT_CHECK_ERROR ( 1862arena = (void * )sycl::malloc_host ((size_t )bytes , 1863 dpct::get_in_order_queue ())); 1864if (allocated == 0 ) { 1865void * alias = nullptr ; 1866const dpct::err0 aliased = 1867DPCT_CHECK_ERROR (alias = (void * )arena ); 1868if (aliased == 0 && alias != nullptr ) { 1869device = (const uint8_t * )alias ; 1870pinned_ok = true; 1871note = "page-locked and mapped" ; 1872 }else { 1873/* 1874DPCT1009: SYCL reports errors using exceptions and does 1875not use error codes. Please replace the 1876"get_error_string_dummy(...)" with a real error-handling 1877function. 1878*/ 1879note = std::string ("no device alias (" )+ 1880 dpct::get_error_string_dummy (aliased )+ ")" ; 1881/* 1882DPCT1010: SYCL uses exceptions to report errors and 1883does not use the error codes. The cudaGetLastError function 1884call 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 ())); 1889arena = 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/* 1895DPCT1009: SYCL reports errors using exceptions and does not 1896use error codes. Please replace the 1897"get_error_string_dummy(...)" with a real error-handling 1898function. 1899*/ 1900note = std::string ("page-locking refused (" )+ 1901 dpct::get_error_string_dummy (allocated )+ ")" ; 1902/* 1903DPCT1010: SYCL uses exceptions to report errors and does 1904not use the error codes. The cudaGetLastError function call was 1905replaced with 0. You need to rewrite this code. 1906*/ 1907 (void )0 ; 1908arena = nullptr ; 1909 } 1910 } 1911if (arena == nullptr ) { 1912if (!note .empty ()) { 1913 std::fprintf (stderr ,"FileExpertSource: %s; trying pageable memory\n" ,note .c_str ()); 1914log_complement_memory ("before pageable allocation" ,bytes ); 1915 std::fflush (stderr ); 1916 } 1917errno = 0 ; 1918arena = std::malloc ((size_t )bytes ); 1919if (arena == nullptr ) { 1920const int allocation_errno = errno ; 1921err = "FileExpertSource: pageable resident complement allocation failed (malloc errno " + 1922 std::to_string (allocation_errno )+ ": " + std::strerror (allocation_errno )+ ")" ; 1923if (!note .empty ())err += "; " + note ; 1924log_complement_memory ("after pageable allocation failure" ,bytes ); 1925return false; 1926 } 1927if (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 1936static const bool partial_on = [] { 1937const char * v = std::getenv ("STRATA_PARTIAL_PIN" ); 1938return 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) 1942static const uint64_t pin_cap = [] { 1943const char * v = std::getenv ("STRATA_PARTIAL_PIN_GIB" ); 1944return (uint64_t ) ((v != nullptr && std::atof (v )> 0 ? std::atof (v ) :24.0 )* 1073741824.0 ); 1945 }(); 1946if (budget_bytes > 0 && partial_on ) { 1947const uint64_t step = 2ull <<30 ; 1948for (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") 1951uint64_t w = want ; 1952for (size_t i = 0 ;i < offsets .size ();++ i ) { 1953if (offsets [i ]== kNoComplement )continue ; 1954const uint64_t b = layer_blob_bytes_ [i / (size_t )n_expert_ ]; 1955if (offsets [i ]< want && offsets [i ]+ b > want ) {w = offsets [i ];break ; } 1956 } 1957if (w == 0 )break ; 1958/* 1959DPCT1027: The call to cudaHostRegister was replaced 1960with 0 because SYCL currently does not support 1961registering of existing host memory for use by device. 1962Use USM to allocate memory for use by host and device. 1963*/ 1964if (0 == 0 ) { 1965void * alias = nullptr ; 1966if (DPCT_CHECK_ERROR (alias = (void * )arena )== 0 && 1967alias != nullptr ) { 1968device = (const uint8_t * )alias ; 1969partial_pin = w ; 1970 }else { 1971/* 1972DPCT1010: SYCL uses exceptions to report 1973errors and does not use the error codes. The 1974cudaGetLastError function call was replaced with 19750. You need to rewrite this code. 1976*/ 1977 (void )0 ; 1978/* 1979DPCT1027: The call to cudaHostUnregister 1980was replaced with 0 because SYCL currently does 1981not support registering of existing host memory 1982for use by device. Use USM to allocate memory 1983for use by host and device. 1984*/ 1985 (void )0 ; 1986 } 1987break ; 1988 } 1989/* 1990DPCT1010: SYCL uses exceptions to report errors and 1991does not use the error codes. The cudaGetLastError 1992function call was replaced with 0. You need to rewrite 1993this code. 1994*/ 1995 (void )0 ; 1996if (want <=step )break ; 1997 } 1998char msg [160 ]; 1999 std::snprintf (msg ,sizeof msg ,"%.2f GiB of it registered for the GPU (the hottest)" , 2000 (double )partial_pin /1073741824.0 ); 2001note += std::string ("; " )+ msg ; 2002 } 2003lock_off = partial_pin ; 2004const strata::platform::LockResult lr = 2005 strata::platform::lock_resident ((uint8_t * )arena + lock_off ,bytes - lock_off ); 2006locked = lr .locked_bytes ; 2007note += (note .empty () ?"" :"; " )+ lr .note ; 2008 } 2009 } 2010host = (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 ) 2015const long page_size = sysconf (_SC_PAGESIZE ); 2016if (page_size <=0 ) { 2017err = "FileExpertSource: cannot determine page size for mapped-page release" ; 2018release (); 2019return 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 ; 2026const auto copy_t0 = std::chrono::steady_clock::now (); 2027 std::string fail_msg ; 2028auto fail = [& ](const std::string & m ) { 2029 std::lock_guard < std::mutex > lock (fail_mu ); 2030if (fail_msg .empty ())fail_msg = m ; 2031failed .store (true); 2032 }; 2033auto worker = [& ]() { 2034for (;;) { 2035const int64_t layer = next_layer .fetch_add (1 ); 2036if (layer >=n_layers_ || failed .load ())return ; 2037const 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 2039auto flush = [& ]() { 2040if (batch .empty ())return true; 2041bool ok = read_direct (batch .data (),batch .size ()); 2042for (size_t i = 0 ; !ok && i < batch .size ();++ i ) 2043if (!copy_from_files (batch [i ].layer ,batch [i ].e ,batch [i ].dst ))return false; 2044copied .fetch_add (blob_bytes * (uint64_t )batch .size ()); 2045batch .clear (); 2046return true; 2047 }; 2048if (direct_ .empty ()) {// mapped reads: ask for the layer's blobs before copying them 2049 std::vector < std::pair < int32_t ,int32_t >> ahead ; 2050for (int64_t expert = 0 ;expert < n_expert_ ;++ expert ) 2051if (offsets [(size_t )layer * (size_t )n_expert_ + (size_t )expert ]!= kNoComplement ) 2052ahead .emplace_back ((int32_t )layer , (int32_t )expert ); 2053 (void )advise_pairs (ahead .data (), (int64_t )ahead .size ()); 2054 } 2055for (int64_t expert = 0 ;expert < n_expert_ ;++ expert ) { 2056const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 2057const uint64_t offset = offsets [index ]; 2058if (offset == kNoComplement )continue ; 2059if (offset > bytes || blob_bytes > bytes - offset ) { 2060fail ("FileExpertSource: invalid blob bounds while building the cache complement" ); 2061return ; 2062 } 2063uint8_t * dst = (uint8_t * )host + (size_t )offset ; 2064if (!direct_ .empty ()) { 2065batch .push_back ({0 ,layer ,expert ,dst }); 2066if (batch .size ()== 32 && !flush ()) { 2067fail ("FileExpertSource: an expert could not be read while building the cache complement" ); 2068return ; 2069 } 2070continue ; 2071 } 2072if (!copy_from_files (layer ,expert ,dst )) { 2073fail ("FileExpertSource: invalid blob bounds while building the cache complement" ); 2074return ; 2075 } 2076copied .fetch_add (blob_bytes ); 2077 } 2078if (!flush ()) { 2079fail ("FileExpertSource: an expert could not be read while building the cache complement" ); 2080return ; 2081 } 2082#if !defined(_WIN32 ) 2083if (role_ptr_ .empty ()) {// experts.bin; the GGUF in place leaves its pages to the OS 2084const uint64_t layer_offset = layer_offsets_ [(size_t )layer ]; 2085const uint64_t layer_bytes = blob_bytes * (uint64_t )n_expert_ ; 2086const uint64_t layer_end = layer_offset + layer_bytes ; 2087const uint64_t page = (uint64_t )page_size ; 2088const uint64_t advice_start = layer_offset - layer_offset %page ; 2089const uint64_t end_remainder = layer_end %page ; 2090const uint64_t extra = end_remainder == 0 ?0 :page - end_remainder ; 2091const uint64_t advice_end = extra > mapped_bytes_ - layer_end ?mapped_bytes_ :layer_end + extra ; 2092if (advice_end > advice_start && 2093madvise ((void * ) (base_ + (size_t )advice_start ), (size_t ) (advice_end - advice_start ),MADV_DONTNEED )!= 0 ) { 2094fail ("FileExpertSource: madvise could not release mapped expert layer " + std::to_string (layer )); 2095return ; 2096 } 2097if (posix_fadvise (fd_ , (off_t )layer_offset , (off_t )layer_bytes ,POSIX_FADV_DONTNEED )!= 0 ) { 2098fail ("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string (layer )); 2099return ; 2100 } 2101 } 2102#endif 2103const int64_t done = layers_done .fetch_add (1 )+ 1 ; 2104if (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 { 2111const int threads = (int ) std::max < int64_t > (1 , std::min < int64_t > (6 ,n_layers_ )); 2112 std::vector < std::thread > pool ; 2113for (int i = 1 ;i < threads ;++ i )pool .emplace_back (worker ); 2114worker (); 2115for (auto & t :pool )t .join (); 2116 } 2117 std::fflush (stderr ); 2118if (failed .load ()) { 2119err = fail_msg ; 2120release (); 2121return 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). 2126if (maps_ .empty ()) (void )VirtualUnlock ((LPVOID )base_ , (SIZE_T )mapped_bytes_ ); 2127for (const Map & m :maps_ ) (void )VirtualUnlock ((LPVOID )m .base , (SIZE_T )m .bytes ); 2128#endif 2129 2130complement_arena_ = arena ; 2131complement_host_ = host ; 2132complement_device_ = device ; 2133complement_bytes_ = bytes ; 2134complement_offsets_ = std::move (offsets ); 2135complement_pinned_ = (pinned_ok || partial_pin > 0 )&& bytes > 0 ; 2136complement_pin_limit_ = pinned_ok ?bytes :partial_pin ; 2137complement_partial_ = !pinned_ok && partial_pin > 0 ; 2138complement_locked_ = locked ; 2139complement_lock_off_ = lock_off ; 2140complement_lent_slots_ = lend ?n_slots - keep_from :0 ; 2141complement_ready_ = true; 2142 std::fprintf (stderr ,"FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB in %.0f s%s%s\n" , 2143complement_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 (), 2146note .empty () ?"" :"; " ,note .c_str ()); 2147if (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 ), 2150complement_lent_slots_ < n_slots - lend_from_slot 2151 ?" (the others are read from the file when lent: not enough RAM for them)" :"" ); 2152if (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. 2156const long long lendable = (long long ) (n_slots - lend_from_slot ); 2157const 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 } 2163if (!additional_gpu_pairs .empty ()) { 2164 std::fprintf (stderr ,"FileExpertSource: %zu verified additional-GPU experts remain on the mmap fallback\n" , 2165additional_gpu_pairs .size ()); 2166 } 2167 std::fflush (stderr ); 2168return 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 { 2177if (exchange_storage_ .active ())return exchange_storage_ .resident (index ).host ; 2178return 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 { 2182if (!complement_ready_ || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return false; 2183const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 2184return resident_blob (index )!= nullptr ; 2185} 2186 2187bool FileExpertSource ::reserve_exchanges (int64_t n , std::string & err ) { 2188err .clear (); 2189if (n <=xstage_cap_ )return true; 2190if (!staged_ .empty ()) {err = "FileExpertSource: exchange buffers are in use" ;return false; } 2191if (exchange_storage_ .active ()) { 2192err = "FileExpertSource: reserve maximum exchange capacity before enabling rotation" ; 2193return false;// the original exchange allocation can now contain live resident experts 2194 } 2195uint64_t blob = 0 ; 2196for (const uint64_t b :layer_blob_bytes_ )blob = std::max (blob ,b ); 2197if (blob == 0 || n <=0 ) {err = "FileExpertSource: no expert geometry for the exchange buffers" ;return false; } 2198if (xstage_ != nullptr ) { 2199if (xstage_pinned_ )(void ) 2200DPCT_CHECK_ERROR (sycl::free (xstage_ , dpct::get_in_order_queue ())); 2201else std::free (xstage_ ); 2202xstage_ = nullptr ; 2203xstage_cap_ = 0 ; 2204 } 2205if ((uint64_t )n > std::numeric_limits < size_t > ::max () /blob ) { 2206err = "FileExpertSource: exchange allocation size overflow" ;return false; 2207 } 2208const char * rotate_env = std::getenv ("STRATA_EXCHANGE_ROTATE" ); 2209const bool requested = rotate_env && std::strcmp (rotate_env ,"1" )== 0 ; 2210const bool uniform = std::all_of (layer_blob_bytes_ .begin (),layer_blob_bytes_ .end (), 2211 [blob ](uint64_t b ) {return b == blob ; }); 2212const bool eligible = requested && uniform && complement_pinned_ && !complement_partial_ && 2213complement_host_ && complement_device_ && complement_bytes_ > 0 ; 2214const size_t total = (size_t )n * (size_t )blob ; 2215void * p = nullptr ; 2216/* 2217DPCT1048: The original value cudaHostAllocMapped is not meaningful in the 2218migrated code and was removed or replaced with 0. You may need to check the 2219migrated code. 2220*/ 2221/* 2222DPCT1048: The original value cudaHostAllocDefault is not meaningful in the 2223migrated code and was removed or replaced with 0. You may need to check the 2224migrated code. 2225*/ 2226if (DPCT_CHECK_ERROR (p = (void * )sycl::malloc_host ( 2227total , dpct::get_in_order_queue ()))== 0 && 2228p != nullptr ) { 2229xstage_pinned_ = true; 2230 }else { 2231/* 2232DPCT1010: SYCL uses exceptions to report errors and does not use 2233the error codes. The cudaGetLastError function call was replaced with 0. 2234You need to rewrite this code. 2235*/ 2236 (void )0 ; 2237p = std::malloc (total ); 2238xstage_pinned_ = false; 2239if (p == nullptr ) {err = "FileExpertSource: cannot allocate the exchange buffers" ;return false; } 2240 } 2241xstage_ = (uint8_t * )p ; 2242xstage_cap_ = n ; 2243xstage_blob_ = blob ; 2244if (requested ) { 2245 std::string reason = "requires equal-size expert blocks and a fully mapped/pinned RAM complement" ; 2246void * device = nullptr ; 2247if (eligible && xstage_pinned_ && 2248DPCT_CHECK_ERROR (device = (void * )p )== 0 && device ) { 2249try { 2250if (exchange_storage_ .initialize (complement_offsets_ , (uint8_t * )complement_host_ ,complement_device_ , 2251complement_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/* 2258DPCT1010: SYCL uses exceptions to report errors and does not use 2259the error codes. The cudaGetLastError function call was replaced 2260with 0. You need to rewrite this code. 2261*/ 2262 (void )0 ; 2263reason = "exchange buffers could not be pinned and mapped" ; 2264 } 2265if (!exchange_storage_ .active ()) 2266 std::fprintf (stderr ,"FileExpertSource: exchange rotation unavailable; retaining copy path: %s\n" ,reason .c_str ()); 2267 } 2268return true; 2269} 2270 2271uint8_t * FileExpertSource ::exchange_buffer (int64_t q )const { 2272if (xstage_ == nullptr || q < 0 || q >=xstage_cap_ )return nullptr ; 2273if (exchange_storage_ .active ())return exchange_storage_ .spare ((size_t )q ).host ; 2274return 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 ) { 2278if (out < 0 || out >=n_expert_ || !has_resident (layer ,in )|| has_resident (layer ,out )|| 2279exchange_buffer (q )== nullptr )return false; 2280const size_t i_in = (size_t )layer * (size_t )n_expert_ + (size_t )in ; 2281const size_t i_out = (size_t )layer * (size_t )n_expert_ + (size_t )out ; 2282if (override_ .empty ())override_ .assign ((size_t )blobs_ ,nullptr ); 2283if (override_ [i_out ]!= nullptr )return false; 2284for (const Exchange & x :staged_ ) 2285if (x .in == i_in || x .q == q )return false; 2286override_ [i_out ]= exchange_buffer (q ); 2287staged_ .push_back ({i_in ,i_out ,q ,layer_blob_bytes_ [(size_t )layer ]}); 2288return true; 2289} 2290 2291int64_t FileExpertSource ::commit_exchanges () { 2292int64_t n = 0 ; 2293for (const Exchange & x :staged_ ) { 2294const uint8_t * src = override_ [x .out ]; 2295if (exchange_storage_ .active ()) { 2296if (!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 ; 2302override_ [x .out ]= nullptr ; 2303continue ; 2304 } 2305const uint64_t at = complement_offsets_ [x .in ]; 2306if (src != nullptr && at != kNoComplement && at <=complement_bytes_ && x .bytes <=complement_bytes_ - at && 2307complement_host_ != nullptr ) { 2308 std::memcpy ((uint8_t * )complement_host_ + (size_t )at ,src , (size_t )x .bytes ); 2309if (detail::exchange_cache_complement (complement_offsets_ ,x .in ,x .out ))++ n ; 2310 } 2311override_ [x .out ]= nullptr ; 2312 } 2313staged_ .clear (); 2314exchanges_ += n ; 2315return n ; 2316} 2317 2318void FileExpertSource ::commit_copies () { 2319if (exchange_storage_ .active ())return ;// STRATA_EXCHANGE_ROTATE: ownership moves in commit_flip, nothing to copy 2320for (const Exchange & x :staged_ ) { 2321const uint8_t * src = override_ .empty () ?nullptr :override_ [x .out ]; 2322const uint64_t at = complement_offsets_ [x .in ]; 2323if (src != nullptr && at != kNoComplement && at <=complement_bytes_ && x .bytes <=complement_bytes_ - at && 2324complement_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 () { 2330int64_t n = 0 ; 2331for (const Exchange & x :staged_ ) { 2332const uint8_t * src = override_ [x .out ]; 2333if (exchange_storage_ .active ()) {// STRATA_EXCHANGE_ROTATE: the same ownership transfer as commit_exchanges 2334if (!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 ; 2339override_ [x .out ]= nullptr ; 2340continue ; 2341 } 2342const 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 2344if (src != nullptr && at != kNoComplement && at <=complement_bytes_ && x .bytes <=complement_bytes_ - at && 2345complement_host_ != nullptr && detail::exchange_cache_complement (complement_offsets_ ,x .in ,x .out )) 2346++ n ; 2347override_ [x .out ]= nullptr ; 2348 } 2349staged_ .clear (); 2350exchanges_ += n ; 2351return n ; 2352} 2353 2354const uint8_t * FileExpertSource ::resident_blob (int64_t layer ,int64_t expert )const { 2355if (!complement_ready_ || complement_host_ == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || 2356expert >=n_expert_ )return nullptr ; 2357const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 2358if (index >=complement_offsets_ .size ())return nullptr ; 2359return 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 ) { 2363if (base_ == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return nullptr ; 2364const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 2365const uint8_t * result = nullptr ; 2366bool from_files = true; 2367if (complement_ready_ ) { 2368result = resident_blob (index ); 2369if (result != nullptr ) { 2370ram_reads_ .fetch_add (1 , std::memory_order_relaxed ); 2371from_files = false; 2372 }else if (!override_ .empty ()&& override_ [index ]!= nullptr ) { 2373result = override_ [index ]; 2374from_files = false; 2375 } 2376 } 2377if (from_files ) { 2378if (staged ()) { 2379result = staged_blob (layer ,expert );// counts its bytes 2380 }else { 2381result = mapped_blob (layer ,expert ); 2382if (result != nullptr ) 2383file_read_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 2384 } 2385if (complement_ready_ && result != nullptr )file_reads_ .fetch_add (1 , std::memory_order_relaxed ); 2386 } 2387if (result != nullptr )++ reads_ ; 2388return result ; 2389} 2390 2391bool FileExpertSource ::pinned (int64_t layer ,int64_t expert )const { 2392if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 || 2393layer >=n_layers_ || expert >=n_expert_ )return false; 2394const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 2395if (exchange_storage_ .active ())return exchange_storage_ .resident (index ).host != nullptr ; 2396if (index >=complement_offsets_ .size ()|| complement_offsets_ [index ]== kNoComplement )return false; 2397// a partial pin (CS-T): only the registered prefix 2398return !complement_partial_ || 2399complement_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 { 2403if (!pinned (layer ,expert )|| complement_device_ == nullptr )return nullptr ; 2404const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 2405if (exchange_storage_ .active ())return exchange_storage_ .resident (index ).device ; 2406return complement_device_ + (size_t )complement_offsets_ [index ]; 2407} 2408 2409bool FileExpertSource ::pcie_layer (int64_t layer )const { 2410if (complement_ready_ && complement_pinned_ && complement_device_ != nullptr ) 2411return layer >=0 && layer < n_layers_ ; 2412return 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 , 2418int64_t k ,float * out ) { 2419 (void )weights ;// clause 2: `moe_combine` applies it on the device. Not an oversight. 2420ExpertDispatch & d = * (ExpertDispatch * )user ; 2421if (d .failed )return ;// a previous layer already failed; do not make it worse 2422 2423using 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. 2427if (n_embd != H ) { 2428d .failed = true; 2429d .fail = "the expert kernel is compiled for a 2560-wide activation" ; 2430d .fail_layer = d .layers ; 2431return ; 2432 } 2433if (expert_layout ().native ) { 2434// plan v0.3 P6: a native pack runs its experts in verify windows only (the driver guarantees it) 2435d .failed = true; 2436d .fail = "the single-token expert path does not take a native (IQ) pack" ; 2437d .fail_layer = d .layers ; 2438return ; 2439 } 2440if (k > (int64_t )d .jobs .size ())d .jobs .resize ((size_t )k ); 2441 2442d .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. 2446act_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. 2456const bool graph_hits = d .host_res != nullptr ; 2457const bool use_hits = graph_hits || (d .hits_ready ()&& d .decided ); 2458int64_t njobs = 0 ; 2459 2460if (d .remote_count > 0 ) { 2461int32_t kind [32 ]; 2462if (k > 32 ) { 2463d .failed = true;d .fail = "remote experts: routing width exceeds 32" ;return ; 2464 } 2465for (int64_t i = 0 ;i < k ;++ i ) 2466kind [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 ; 2469static thread_local std::string remote_error ; 2470for (int r = 0 ;r < d .remote_count ;++ r ) 2471if (!d .remote [r ]-> begin (d .layers ,x_f ,ids ,1 ,k ,kind ,d .host_res ,remote_error )) { 2472d .failed = true;d .fail = remote_error .c_str ();d .fail_layer = d .layers ;return ; 2473 } 2474 } 2475 2476for (int64_t i = 0 ;i < k ;++ i ) { 2477const int64_t e = ids [i ]; 2478if (e < 0 || e >=d .n_expert ) { 2479d .failed = true; 2480d .fail = "a routed expert id is out of range" ; 2481d .fail_layer = d .layers ; 2482d .fail_expert = e ; 2483return ; 2484 } 2485const uint8_t * b = d .src -> blob (d .layers ,e ); 2486if (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. 2490d .failed = true; 2491d .fail = "the expert source could not produce a blob" ; 2492d .fail_layer = d .layers ; 2493d .fail_expert = e ; 2494++ d .missing ; 2495return ; 2496 } 2497// A hit's row was zeroed by `Launch` and belongs to the GPU; the pool must not touch it. 2498if (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 )) { 2500if (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 )); 2504continue ; 2505 } 2506if (graph_hits )++ d .cache_refused ;// token graph: a miss (nothing is admitted during a token) 2507 2508bool remote_owns = false; 2509for (int r = 0 ;r < d .remote_count ;++ r )remote_owns |=d .remote [r ]-> owns (i ); 2510if (remote_owns ) { 2511 std::memset (out + (size_t )i * (size_t )n_embd ,0 , (size_t )n_embd * sizeof (float )); 2512continue ; 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. 2517ExpertJob & j = d .jobs [(size_t )njobs ++ ]; 2518j .blob = b ; 2519j .act = & d .act ;// SHARED across the batch: one conversion serves all ten experts 2520j .out = out + (size_t )i * (size_t )n_embd ; 2521j .weight = 1.0f ;// clause 2: a diagnostic field, NOT the router weight 2522j .slot = (int )i ; 2523 } 2524 2525// Plan v0.3 P4: rows of every expert across all threads (bitwise the same as `run`). 2526if (d .split_rows )d .pool -> run_split (d .jobs .data (), (int )njobs ); 2527else d .pool -> run (d .jobs .data (), (int )njobs ); 2528if (d .remote_count > 0 ) { 2529static thread_local std::string remote_error ; 2530for (int r = 0 ;r < d .remote_count ;++ r ) 2531if (!d .remote [r ]-> finish (out ,remote_error )) { 2532d .failed = true;d .fail = remote_error .c_str ();d .fail_layer = d .layers ;return ; 2533 } 2534 } 2535++ d .layers ; 2536d .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 , 2548float * out ) { 2549using namespace strata::kernels::cpu ; 2550if (d .failed )return ; 2551if (n_tok < 1 || n_tok > MAXT ) { 2552d .failed = true; 2553d .fail = "a verify window has more tokens than the multi-token expert kernel takes" ; 2554d .fail_layer = d .layers ; 2555return ; 2556 } 2557if (d .lookahead != nullptr )d .lookahead -> submit (d .layers ,x_f ,n_tok ,d .host_res );// CS-T: warm layer + 1 2558if (k < 1 || n_tok * k > kMaxWindowEntries ) { 2559d .failed = true; 2560d .fail = "a verify window routes more entries than the expert pool's window tables hold" ; 2561d .fail_layer = d .layers ; 2562return ; 2563 } 2564if ((int64_t )d .act_multi .size ()< n_tok )d .act_multi .resize ((size_t )MAXT ); 2565const ExpertLayout & lay = expert_layout (); 2566const bool native = lay .native ; 2567if (native && d .nact_multi .size ()< (size_t )MAXT * kNativeActBytes )d .nact_multi .resize ((size_t )MAXT * kNativeActBytes ); 2568if (d .job_of .size ()!= (size_t )d .n_expert )d .job_of .assign ((size_t )d .n_expert , (int16_t )-1 ); 2569if (d .jobs_multi .size ()< (size_t ) (n_tok * k ))d .jobs_multi .resize ((size_t ) (MAXT * k )); 2570static const bool ptrace = std::getenv ("STRATA_POOL_TRACE" )!= nullptr ; 2571auto pt = [& ](const char * what ,long long a = -1 ) { 2572if (ptrace ) { std::fprintf (stderr ,"pool trace: layer %lld %s %lld\n" , (long long )d .layers ,what ,a ); std::fflush (stderr ); } 2573 }; 2574const auto c0 = std::chrono::steady_clock::now (); 2575pt ("begin" ); 2576d .src -> begin_layer (d .layers ,ids ,n_tok * k ); 2577pt ("begun" ); 2578if (!d .usage .empty ()) 2579for (int64_t i = 0 ;i < n_tok * k ;++ i ) 2580if (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. 2583const int64_t n = n_tok * k ; 2584int32_t kind [kMaxWindowEntries ];// per entry: -1 CPU, 0 VRAM, 1 PCIe 2585if (d .plan != nullptr && n <=kMaxWindowEntries && n <=d .plan -> cap ) { 2586int64_t distinct [kMaxWindowEntries ],first_of [kMaxWindowEntries ]; 2587int 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) 2592auto helper_holds = [& ](int32_t e ) { 2593for (int r = 0 ;r < d .remote_count ;++ r ) 2594if (d .remote [r ]-> holds (d .layers ,e ))return true; 2595return false; 2596 }; 2597for (int64_t i = 0 ;i < n ;++ i ) { 2598first_of [i ]= i ; 2599for (int64_t j = 0 ;j < i ;++ j ) 2600if (ids [j ]== ids [i ]) {first_of [i ]= first_of [j ];break ; } 2601if (first_of [i ]== i ) { 2602distinct [nd ++ ]= i ; 2603const int32_t e = ids [i ]; 2604if (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 } 2608const bool pcie_ok = d .pcie_num > 0 && d .src -> pcie_layer (d .layers ); 2609const int m = pcie_ok ? (nmiss * d .pcie_num ) >>8 :0 ; 2610int miss_rank = 0 ,groups = 0 ,entries = 0 ,fetches = 0 ; 2611GpuPlanSink & P = * d .plan ; 2612const uint8_t * dma_src [64 ]; 2613int64_t pcie_i0 [64 ]; 2614for (int q = 0 ;q < nd ;++ q ) { 2615const int64_t i0 = distinct [q ]; 2616const int32_t e = ids [i0 ]; 2617int kd = -1 ; 2618unsigned long long ptr = 0 ; 2619if (e >=0 && e < d .n_expert ) { 2620const int32_t slot = d .host_res [(size_t )d .layers * (size_t )d .n_expert + (size_t )e ]; 2621if (slot >=0 ) { 2622kd = 0 ; 2623ptr = (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 )) { 2626kd = 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 { 2630if (miss_rank >=nmiss - m && fetches < P .staging_cap && fetches < 64 ) { 2631const uint8_t * src = d .src -> pinned (d .layers ,e ) ?d .src -> blob (d .layers ,e ) :nullptr ; 2632if (src != nullptr ) { 2633kd = 1 ; 2634dma_src [fetches ]= src ; 2635pcie_i0 [fetches ]= i0 ; 2636++ fetches ; 2637 } 2638 } 2639++ miss_rank ; 2640 } 2641 } 2642for (int64_t i = i0 ;i < n ;++ i ) 2643if (first_of [i ]== i0 )kind [i ]= kd ; 2644if (kd != 0 )continue ;// the VRAM groups first; the PCIe groups below 2645P .ptr [groups ]= ptr ; 2646P .start [groups ]= entries ; 2647for (int64_t i = i0 ;i < n ;++ i ) 2648if (first_of [i ]== i0 ) { 2649P .dst [entries ]= (int32_t )i ; 2650P .tok [entries ]= (int32_t ) (i /k ); 2651++ entries ; 2652 } 2653++ groups ; 2654 } 2655P .start [groups ]= entries ; 2656const uint64_t bb = lay .blob_bytes (d .layers ); 2657for (int q = 0 ;q < fetches ;++ q ) {// the PCIe groups: staging slot q, entries after the VRAM ones 2658const int64_t i0 = pcie_i0 [q ]; 2659P .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 ; 2661P .start2 [q ]= entries ; 2662for (int64_t i = i0 ;i < n ;++ i ) 2663if (first_of [i ]== i0 ) { 2664P .dst [entries ]= (int32_t )i ; 2665P .tok [entries ]= (int32_t ) (i /k ); 2666++ entries ; 2667 } 2668++ d .pcie_experts ; 2669 } 2670P .start2 [fetches ]= entries ; 2671P .counts [0 ]= groups ; 2672P .counts [1 ]= entries ; 2673P .counts [2 ]= fetches ; 2674 std::atomic_thread_fence (std::memory_order_seq_cst ); 2675pt ("publish" ,fetches ); 2676if (P .publish )P .publish (P .ctx ); 2677pt ("fetch" ,fetches ); 2678if (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 { 2680for (int64_t i = 0 ;i < n ;++ i ) { 2681const int32_t e = ids [i ]; 2682kind [i ]= (e >=0 && e < d .n_expert && d .host_res != nullptr && 2683d .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 } 2687if (d .peer != nullptr ) {// multi-GPU: start the second GPU's share before the CPU's own work 2688 std::string perr ; 2689if (!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 ); 2691d .failed = true; 2692d .fail = "the peer GPU's experts could not be launched" ; 2693d .fail_layer = d .layers ; 2694return ; 2695 } 2696 } 2697if (d .remote_count > 0 ) { 2698static thread_local std::string remote_error ; 2699for (int r = 0 ;r < d .remote_count ;++ r ) { 2700if (!d .remote [r ]-> begin (d .layers ,x_f ,ids ,n_tok ,k ,kind ,d .host_res ,remote_error )) { 2701d .failed = true;d .fail = remote_error .c_str ();d .fail_layer = d .layers ;return ; 2702 } 2703for (int64_t i = 0 ;i < n ;++ i )if (d .remote [r ]-> owns (i ))kind [i ]= 2 ; 2704 } 2705 } 2706static 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 2709static const bool device_plan = [] {const char * v = std::getenv ("STRATA_VERIFY_DEVICE_PLAN" );return v != nullptr && std::atoi (v )!= 0 ; }(); 2710const bool gpu_zeroes_hits = (d .plan != nullptr && n <=kMaxWindowEntries && n <=d .plan -> cap && dec_batch && !device_plan ); 2711bool any_cpu = false; 2712for (int64_t i = 0 ;i < n ;++ i ) 2713if (kind [i ]< 0 ) {any_cpu = true;break ; } 2714const auto c1 = std::chrono::steady_clock::now (); 2715if (any_cpu ) { 2716// #578 --remote-expert-opt: a token whose experts all run on a GPU (CUDA0 or a helper) needs no CPU activation 2717const bool ep = d .remote_count > 0 && d .remote [0 ]-> optimized_decode (); 2718for (int64_t t = 0 ;t < n_tok ;++ t ) { 2719if (ep && std::all_of (kind + t * k ,kind + (t + 1 )* k , [](int32_t v ) {return v >=0 ; }))continue ; 2720if (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 2721act_quant_any (x_f + (size_t )t * H ,H ,d .act_multi [(size_t )t ]); 2722else if (native ) 2723native_quant_act (lay .fmt [(size_t )d .layers ],x_f + (size_t )t * H ,d .nact_multi .data ()+ (size_t )t * kNativeActBytes ); 2724else 2725act_quant_q8_1 (x_f + (size_t )t * H ,H ,d .act_multi [(size_t )t ]); 2726 } 2727 } 2728const auto c2 = std::chrono::steady_clock::now (); 2729if (any_cpu ) {// CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads) 2730static thread_local std::vector < int64_t > miss ; 2731miss .clear (); 2732for (int64_t i = 0 ;i < n_tok * k ;++ i ) 2733if (kind [i ]< 0 && ids [i ] >=0 && ids [i ]< d .n_expert && 2734 std::find (miss .begin (),miss .end (), (int64_t )ids [i ])== miss .end ()) 2735miss .push_back (ids [i ]); 2736d .src -> prefetch (d .layers ,miss .data (), (int64_t )miss .size ()); 2737 } 2738int njobs = 0 ; 2739for (int64_t t = 0 ;t < n_tok ;++ t ) 2740for (int64_t j = 0 ;j < k ;++ j ) { 2741const int64_t i = t * k + j ; 2742const int64_t e = ids [i ]; 2743float * row = out + (size_t )i * H ; 2744if (e < 0 || e >=d .n_expert ) { 2745d .failed = true; 2746d .fail = "a routed expert id is out of range" ; 2747d .fail_layer = d .layers ; 2748d .fail_expert = e ; 2749return ; 2750 } 2751if (kind [i ] >=0 ) {// CUDA0, PCIe, or a remote/peer result staged into this row below 2752if (kind [i ]== 0 )++ d .cache_hits ; 2753else ++ d .offload_entries ;// #588: PCIe or another GPU 2754if (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 2757if (!((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 )); 2760continue ; 2761 } 2762++ d .cache_refused ; 2763int16_t & jo = d .job_of [(size_t )e ]; 2764if (jo < 0 ) { 2765const uint8_t * b = d .src -> blob (d .layers ,e ); 2766if (b == nullptr ) { 2767d .failed = true; 2768d .fail = "the expert source could not produce a blob" ; 2769d .fail_layer = d .layers ; 2770d .fail_expert = e ; 2771++ d .missing ; 2772return ; 2773 } 2774jo = (int16_t )njobs ++ ; 2775ExpertJobMulti & nj = d .jobs_multi [(size_t )jo ]; 2776nj .blob = b ; 2777nj .nt = 0 ; 2778 } 2779ExpertJobMulti & jb = d .jobs_multi [(size_t )jo ]; 2780jb .act [jb .nt ]= & d .act_multi [(size_t )t ]; 2781jb .nact [jb .nt ]= native ?d .nact_multi .data ()+ (size_t )t * kNativeActBytes :nullptr ; 2782jb .out [jb .nt ]= row ; 2783++ jb .nt ; 2784++ d .multi_entries ; 2785 } 2786const auto c3 = std::chrono::steady_clock::now (); 2787pt ("run" ,njobs ); 2788if (njobs > 0 ) { 2789if (native )d .pool -> run_split_multi_native (lay .fmt [(size_t )d .layers ],d .jobs_multi .data (),njobs ); 2790else d .pool -> run_split_multi (d .jobs_multi .data (),njobs ); 2791 } 2792if (d .remote_count > 0 ) { 2793static thread_local std::string remote_error ; 2794for (int r = 0 ;r < d .remote_count ;++ r ) 2795if (!d .remote [r ]-> finish (out ,remote_error )) { 2796d .failed = true;d .fail = remote_error .c_str ();d .fail_layer = d .layers ;return ; 2797 } 2798 } 2799if (d .peer != nullptr ) {// multi-GPU: the second GPU's rows, into the same mapped rows 2800 std::string perr ; 2801if (!d .peer -> finish (out ,perr )) { 2802 std::fprintf (stderr ,"strata: %s (layer %lld)\n" ,perr .c_str (), (long long )d .layers ); 2803d .failed = true; 2804d .fail = "the peer GPU's experts failed" ; 2805d .fail_layer = d .layers ; 2806return ; 2807 } 2808 } 2809const auto c4 = std::chrono::steady_clock::now (); 2810pt ("ran" ); 2811auto ms = [](auto a ,auto b ) {return std::chrono::duration < double , std::milli > (b - a ).count (); }; 2812d .ms_plan += ms (c0 ,c1 ); 2813d .ms_actq += ms (c1 ,c2 ); 2814d .ms_jobs += ms (c2 ,c3 ); 2815d .ms_run += ms (c3 ,c4 ); 2816for (int64_t i = 0 ;i < n_tok * k ;++ i ) { 2817const int64_t e = ids [i ]; 2818if (e >=0 && e < d .n_expert )d .job_of [(size_t )e ]= -1 ; 2819 } 2820d .multi_misses += njobs ; 2821++ d .layers ; 2822d .experts += n_tok * k ; 2823} 2824 2825void expert_hit_run (void * user ,void * stream ,HitPhase phase , 2826const int32_t * ids ,int64_t k )try { 2827ExpertDispatch & d = * (ExpertDispatch * )user ; 2828if (d .failed )return ; 2829 dpct::queue_ptr cs = strata::q_of (stream ); 2830 2831if (phase == HitPhase ::Launch ) { 2832d .decided = false; 2833d .hit_pending = false; 2834if (!d .hits_ready ()|| ids == nullptr || k <=0 )return ; 2835if ((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. 2842d .n_hits = 0 ; 2843for (int64_t i = 0 ;i < k ;++ i ) { 2844const int64_t e = ids [i ]; 2845d .is_hit [(size_t )i ]= 0 ; 2846if (e < 0 || e >=d .n_expert )continue ;// out of range: the pool refuses it, with a message 2847int32_t slot = d .cache -> slot_of (d .layers ,e ); 2848if (slot == kNotResident ) { 2849const int32_t cand = d .cache -> admit (d .layers ,e ); 2850if (cand == kNotResident ) { 2851++ d .cache_refused ; 2852continue ; 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. 2856const uint8_t * b = d .src -> blob (d .layers ,e ); 2857 std::string ferr ; 2858if (b == nullptr || !d .cache -> fill_slot (cand ,b ,cs ,ferr , (int64_t ) strata::kernels::cpu::expert_layout ().blob_bytes (d .layers ))) { 2859d .failed = true; 2860d .fail = "the expert cache could not fill a slot" ; 2861d .fail_layer = d .layers ; 2862d .fail_expert = e ; 2863return ; 2864 } 2865++ d .cache_admitted ; 2866slot = cand ; 2867 }else { 2868++ d .cache_hits ; 2869 } 2870d .is_hit [(size_t )i ]= 1 ; 2871d .h_slot [(size_t )d .n_hits ]= slot ; 2872d .h_dst [(size_t )d .n_hits ]= (int32_t )i ; 2873++ d .n_hits ; 2874 } 2875d .decided = true; 2876if (d .n_hits <=0 )return ;// nothing resident yet: no GPU work, and nothing for `Combine` to add 2877 2878const 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. 2882if (DPCT_CHECK_ERROR (cs -> memset ( 2883d .hit_out ,0 , (size_t )d .parts_elems * sizeof (float )))!= 0 || 2884/* 2885DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 2886API. While the origin API might be synchronous, it depends on the 2887type of operand memory, so you may need to call wait() on event 2888return by memcpy API to ensure synchronization behavior. 2889*/ 2890DPCT_CHECK_ERROR ( 2891cs -> memcpy (d .d_slot ,d .h_slot .data (),list_bytes ))!= 0 || 2892/* 2893DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 2894API. While the origin API might be synchronous, it depends on the 2895type of operand memory, so you may need to call wait() on event 2896return by memcpy API to ensure synchronization behavior. 2897*/ 2898DPCT_CHECK_ERROR (cs -> memcpy (d .d_dst ,d .h_dst .data (),list_bytes ))!= 28990 ) { 2900d .hit_fail = "the hit list could not be staged" ; 2901d .failed = true; 2902d .fail = d .hit_fail ; 2903return ; 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. 2914if (d .x_q8_0_hit_scale == nullptr ) { 2915d .failed = true; 2916d .fail = "the hit path has no fp32 activation scales (R4.2h)" ; 2917return ; 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 , 2920cs ); 2921if (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 , 2923d .cache_blob ,d .x_q8_0_hit ,d .hit_scratch ,d .hit_out ,cs ,d .x_q8_0_hit_scale ); 2924else 2925 strata::kernels::moe_hit_grouped_s2 (d .cache_base ,d .d_slot ,d .d_dst ,d .n_hits ,d .cache_blob , 2926d .x_q8_0_hit ,d .hit_scratch ,d .hit_out ,cs ,d .x_q8_0_hit_scale ); 2927d .hit_pending = true; 2928if (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. 2932if (d .hit_poke && d .hit_done != nullptr )(void ) 2933 dpct::sycl_event_query ((dpct::event_ptr )d .hit_done ); 2934return ; 2935 } 2936 2937// Combine: `parts += hit_out`, stream-ordered after the misses were copied into `parts`. 2938if (!d .hit_pending )return ; 2939d .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. 2943if (d .hit_done != nullptr ) { 2944if (((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 ; 2947else ++ 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 ) { 2962h = fnv1a64 ((const uint8_t * )& v ,sizeof v ,h ); 2963} 2964 2965void hash_text (uint64_t & h ,const std::string & s ) { 2966h = 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 ) { 2970hash_text (h ,path .filename ().string ()); 2971 std::ifstream f (path , std::ios::binary ); 2972if (!f ) { 2973hash_u64 (h ,0 ); 2974return true; 2975 } 2976hash_u64 (h ,1 ); 2977 std::vector < uint8_t > buf (64u <<10 ); 2978for (;;) { 2979f .read ((char * )buf .data (), (std::streamsize )buf .size ()); 2980const std::streamsize n = f .gcount (); 2981if (n > 0 )h = fnv1a64 (buf .data (), (uint64_t )n ,h ); 2982if (f .eof ())break ; 2983if (!f ) { 2984err = "ArenaExpertSource: cannot hash pack metadata " + path .string (); 2985return false; 2986 } 2987 } 2988return 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 ); 2993if (!f ) { 2994err = "ArenaExpertSource: cannot sample pack source " + path .string (); 2995return false; 2996 } 2997const std::streamoff end = f .tellg (); 2998if (end < 0 ) { 2999err = "ArenaExpertSource: cannot size pack source " + path .string (); 3000return false; 3001 } 3002const uint64_t bytes = (uint64_t )end ; 3003hash_text (h ,path .filename ().string ()); 3004hash_u64 (h ,bytes ); 3005constexpr uint64_t sample = 64u <<10 ; 3006const 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 )); 3008for (uint64_t off :starts ) { 3009if (buf .empty ())break ; 3010const uint64_t at = std::min < uint64_t > (off ,bytes - (uint64_t )buf .size ()); 3011f .clear (); 3012f .seekg ((std::streamoff )at ); 3013f .read ((char * )buf .data (), (std::streamsize )buf .size ()); 3014if ((size_t )f .gcount ()!= buf .size ()) { 3015err = "ArenaExpertSource: short read while hashing pack source " + path .string (); 3016return false; 3017 } 3018hash_u64 (h ,at ); 3019h = fnv1a64 (buf .data (), (uint64_t )buf .size (),h ); 3020 } 3021return true; 3022} 3023 3024bool shared_arena_pack_hash (const std::string & pack_dir ,const std::string & experts_path , 3025const std::string & gguf ,const strata::kernels::cpu::ExpertLayout & lay , 3026uint64_t & out , std::string & err ) { 3027uint64_t h = 1469598103934665603ull ; 3028hash_text (h ,"strata-shared-expert-arena-pack-v1" ); 3029hash_u64 (h , (uint64_t )lay .n_layers ); 3030hash_u64 (h , (uint64_t )lay .n_expert ); 3031hash_u64 (h ,lay .total ); 3032hash_u64 (h ,lay .max_blob ); 3033hash_u64 (h ,lay .native ?1 :0 ); 3034 3035const std::filesystem::path pack (pack_dir ); 3036for (const char * name : {"manifest.json" ,"index.txt" ,"native_experts.txt" }) { 3037if (!hash_small_file (pack /name ,h ,err ))return false; 3038 } 3039 3040if (std::filesystem::exists (experts_path )) { 3041if (!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. 3046const std::filesystem::path first (gguf ); 3047 std::vector < std::filesystem::path > sources {first }; 3048for (const std::string & name :lay .gguf_file ) { 3049if (name .empty ())continue ; 3050const std::filesystem::path p = first .parent_path () /name ; 3051if (std::find (sources .begin (),sources .end (),p )== sources .end ())sources .push_back (p ); 3052 } 3053for (const auto & p :sources ) { 3054if (!hash_sampled_file (p ,h ,err ))return false; 3055 } 3056 } 3057 3058out = h == 0 ?1 :h ; 3059return 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 ) { 3068const size_t i = (size_t ) (3 * l + r ); 3069if (lay .gguf_file .size () <=i || lay .gguf_file [i ].empty ())return gguf ; 3070const size_t cut = gguf .find_last_of ("/\\" ); 3071return (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 , 3076const strata::kernels::cpu::ExpertLayout & lay ,bool from_gguf ) { 3077static const char * roles [3 ]= {"gate" ,"up" ,"down" }; 3078inputs_ .clear (); 3079if (!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 3081for (int64_t l = 0 ;l < lay .n_layers ;++ l ) 3082for (int r = 0 ;r < 3 ;++ r ) 3083inputs_ .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 ) { 3087static const char * roles [3 ]= {"gate" ,"up" ,"down" }; 3088if (lay .gguf_off .size ()!= (size_t ) (3 * lay .n_layers )) { 3089err = "native_experts.txt has no GGUF offsets (a pack older than v2): repack it with tools/iq_pack.py" ; 3090return false; 3091 } 3092try { 3093 std::map < std::string , std::unique_ptr < strata::GgufFile >> files ; 3094for (int64_t l = 0 ;l < lay .n_layers ;++ l ) { 3095const auto & fm = lay .fmt [(size_t )l ]; 3096const uint64_t blob = lay .bytes [(size_t )l ]; 3097const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,blob - fm .down_off }; 3098for (int r = 0 ;r < 3 ;++ r ) { 3099const std::string path = expert_gguf_file (gguf ,lay ,l ,r ); 3100auto & f = files [path ]; 3101if (!f )f = std::make_unique < strata::GgufFile > (path ); 3102const std::string name = "blk." + std::to_string (l )+ ".ffn_" + roles [r ]+ "_exps.weight" ; 3103const strata::TensorInfo * t = f -> find (name ); 3104const 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 3106const uint64_t cols = (uint64_t ) (r < 2 ?fm .n_embd :fm .n_ff ); 3107const uint64_t rows = (uint64_t ) (r < 2 ?fm .n_ff :fm .n_embd ); 3108const uint64_t bytes = per [r ]* (uint64_t )lay .n_expert ; 3109const uint64_t payload = f -> file_size ()- f -> data_start (); 3110 std::string why ; 3111if (t == nullptr )why = "is not in it" ; 3112else if (t -> type != want_type ) 3113why = std::string ("is " )+ t -> type_name ()+ ", the pack says type " + std::to_string (want_type ); 3114else if (t -> shape .size ()!= 3 || t -> shape [0 ]!= cols || t -> shape [1 ]!= rows || 3115t -> shape [2 ]!= (uint64_t )lay .n_expert ) 3116why = "is not [" + std::to_string (cols )+ ", " + std::to_string (rows )+ ", " + 3117 std::to_string (lay .n_expert )+ "]" ; 3118else if (strata::tensor_payload_bytes (* t )!= bytes ) 3119why = "is not " + std::to_string (per [r ])+ " B per expert" ; 3120else if (f -> data_start ()+ t -> offset != lay .gguf_off [(size_t ) (3 * l + r )]) 3121why = "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 )]); 3123else if (t -> offset > payload || bytes > payload - t -> offset ) 3124why = "runs past the end of the file (a truncated shard?)" ; 3125if (!why .empty ()) { 3126err = "the pack's native_experts.txt does not match the model: " + name + " in " + path + " " + 3127why + " - repack with tools/iq_pack.py from this model's shards" ; 3128return false; 3129 } 3130 } 3131 } 3132return true; 3133 }catch (const std::exception & e ) { 3134err = std::string ("native experts from the GGUF: " )+ e .what (); 3135return 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 , 3147int 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) 3150auto wait_ready = [ready ](int64_t l ) { 3151if (ready != nullptr ) 3152while (ready -> load (std::memory_order_acquire ) <=l + 1 ) std::this_thread::yield (); 3153 }; 3154LoadStats st ; 3155st .layers = (uint64_t )lay .n_layers ; 3156const auto t0 = std::chrono::steady_clock::now (); 3157 std::atomic < int64_t > next {0 }; 3158 std::atomic < bool > bad {false}; 3159#if defined(_WIN32 ) 3160if (unbuffered ) { 3161uint64_t max_chunk = 0 ; 3162for (int64_t l = 0 ;l < lay .n_layers ;++ l ) { 3163const auto & fm = lay .fmt [(size_t )l ]; 3164max_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 ; 3168auto worker = [& ]() { 3169constexpr uint64_t kSector = 4096 ; 3170const uint64_t cap = (max_chunk + 2 * kSector + kSector - 1 ) /kSector * kSector ; 3171uint8_t * buf = (uint8_t * )VirtualAlloc (nullptr , (size_t )cap ,MEM_COMMIT |MEM_RESERVE ,PAGE_READWRITE ); 3172HANDLE h = INVALID_HANDLE_VALUE ; 3173 std::string open_name ; 3174auto fail = [& ](const std::string & what ) { 3175 std::lock_guard < std::mutex > g (err_mu ); 3176if (err .empty ())err = what ; 3177bad = true; 3178 }; 3179if (buf == nullptr )fail ("cannot allocate a read buffer" ); 3180for (;;) { 3181const int64_t l = next .fetch_add (1 ); 3182if (l >=lay .n_layers || bad )break ; 3183wait_ready (l ); 3184const auto & fm = lay .fmt [(size_t )l ]; 3185const uint64_t blob = lay .bytes [(size_t )l ]; 3186const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,blob - fm .down_off }; 3187const uint64_t at [3 ]= {0 ,fm .up_off ,fm .down_off }; 3188for (int r = 0 ;r < 3 && !bad ;++ r ) { 3189// the handle is kept while consecutive roles share a file (every layer of a v3 pack) 3190const std::string name = expert_gguf_file (gguf ,lay ,l ,r ); 3191if (name != open_name ) { 3192if (h != INVALID_HANDLE_VALUE )CloseHandle (h ); 3193const 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' ); 3195if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,name .c_str (),-1 ,w .data (),wide ); 3196h = CreateFileW (w .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 3197FILE_FLAG_NO_BUFFERING |FILE_FLAG_SEQUENTIAL_SCAN ,nullptr ); 3198if (h == INVALID_HANDLE_VALUE ) { 3199fail ("cannot open " + name + " (error " + std::to_string ((unsigned long long )GetLastError ())+ ")" ); 3200break ; 3201 } 3202open_name = name ; 3203 } 3204const uint64_t src = lay .gguf_off [(size_t ) (3 * l + r )]; 3205const uint64_t total = per [r ]* (uint64_t )lay .n_expert ; 3206const uint64_t chunk = per [r ]* 16 ;// 16 experts per read 3207for (uint64_t done = 0 ;done < total ;done += chunk ) { 3208const uint64_t n = std::min < uint64_t > (chunk ,total - done ); 3209const uint64_t a0 = (src + done ) /kSector * kSector ; 3210const uint64_t a1 = (src + done + n + kSector - 1 ) /kSector * kSector ; 3211OVERLAPPED ov {}; 3212ov .Offset = (DWORD )a0 ; 3213ov .OffsetHigh = (DWORD ) (a0 >>32 ); 3214DWORD got = 0 ; 3215// the window may run past the end of the file: only the tensor's own bytes have to arrive 3216if (!ReadFile (h ,buf , (DWORD ) (a1 - a0 ),& got ,& ov )|| (uint64_t )got < src + done - a0 + n ) { 3217fail ("short unbuffered read of layer " + std::to_string (l )+ " in " + name + " (error " + 3218 std::to_string ((unsigned long long )GetLastError ())+ ")" ); 3219break ; 3220 } 3221const uint8_t * q = buf + (src + done - a0 ); 3222for (uint64_t k = 0 ;k < n /per [r ];++ k ) { 3223const 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 } 3229if (h != INVALID_HANDLE_VALUE )CloseHandle (h ); 3230if (buf != nullptr )VirtualFree (buf ,0 ,MEM_RELEASE ); 3231 }; 3232 std::vector < std::thread > pool ; 3233for (int i = 1 ;i < threads ;++ i )pool .emplace_back (worker ); 3234worker (); 3235for (auto & t :pool )t .join (); 3236if (bad ) { 3237st .seconds = -1.0 ; 3238st .ok = false; 3239st .error = err .empty () ?"unreadable shard while reading the experts from the GGUF" :err ; 3240return st ; 3241 } 3242st .bytes = lay .total ; 3243st .seconds = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 3244return st ; 3245 } 3246#else 3247 (void )unbuffered ; 3248#endif 3249auto 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. 3253struct Closer { 3254FILE * f = nullptr ; 3255 ~Closer () {if (f != nullptr ) std::fclose (f ); } 3256 }file ; 3257 std::string open_name ; 3258 std::vector < uint8_t > buf ; 3259for (;;) { 3260const int64_t l = next .fetch_add (1 ); 3261if (l >=lay .n_layers || bad )break ; 3262wait_ready (l ); 3263const auto & fm = lay .fmt [(size_t )l ]; 3264const uint64_t blob = lay .bytes [(size_t )l ]; 3265const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,blob - fm .down_off }; 3266const uint64_t at [3 ]= {0 ,fm .up_off ,fm .down_off }; 3267for (int r = 0 ;r < 3 ;++ r ) { 3268// the handle is kept while consecutive roles share a file (every layer of a v3 pack) 3269const std::string name = expert_gguf_file (gguf ,lay ,l ,r ); 3270if (name != open_name ) { 3271if (file .f != nullptr ) std::fclose (file .f ); 3272file .f = std::fopen (name .c_str (),"rb" ); 3273if (file .f == nullptr ) {bad = true;return ; } 3274open_name = name ; 3275 } 3276FILE * const f = file .f ; 3277const uint64_t src = lay .gguf_off [(size_t ) (3 * l + r )]; 3278const uint64_t total = per [r ]* (uint64_t )lay .n_expert ; 3279const uint64_t chunk = per [r ]* 16 ;// 16 experts per read 3280buf .resize ((size_t )chunk ); 3281for (uint64_t done = 0 ;done < total ;done += chunk ) { 3282const uint64_t n = std::min < uint64_t > (chunk ,total - done ); 3283// 64-bit seek: a shard is tens of GB 3284if (STRATA_FSEEK64 (f ,src + done )!= 0 ) {bad = true;return ; } 3285if (std::fread (buf .data (),1 , (size_t )n ,f )!= (size_t )n ) {bad = true;return ; } 3286for (uint64_t k = 0 ;k < n /per [r ];++ k ) { 3287const 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 ; 3295for (int i = 1 ;i < threads ;++ i )pool .emplace_back (worker ); 3296worker (); 3297for (auto & t :pool )t .join (); 3298if (bad ) { 3299st .seconds = -1.0 ; 3300st .ok = false; 3301st .error = "short read or unreadable shard while reading the experts from the GGUF" ; 3302return st ; 3303 } 3304st .bytes = lay .total ; 3305st .seconds = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 3306return 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 , 3313const std::string & shared_arena_file ) { 3314close (); 3315const 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 3317const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 3318if (lay .n_layers != n_layers || lay .n_expert != n_expert ) { 3319err = "ArenaExpertSource: the expert layout was loaded for a different geometry" ; 3320return false; 3321 } 3322const int64_t blob = (int64_t )lay .max_blob ; 3323const 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 3326const 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. 3329if (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 3333if (!check_experts_gguf (gguf_ ,lay ,err )) {err = "ArenaExpertSource: " + err ;return false; } 3334 }else { 3335 std::ifstream f (path , std::ios::binary | std::ios::ate ); 3336if (!f ) {err = "ArenaExpertSource: cannot open " + path ;return false; } 3337const uint64_t got = (uint64_t )f .tellg (); 3338if (got != want && got != want + (uint64_t )blob ) {// + one blob: STRATA_ARENA_MMAP's padded file 3339char 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" , 3343path .c_str (), (unsigned long long )got , (long long )n_layers , (long long )n_expert , 3344 (long long )blob , (unsigned long long )want ); 3345err = buf ; 3346return 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 ) 3357static const bool arena_mmap = false;// POSIX mmap/madvise: Linux only for now 3358#else 3359static const bool arena_mmap = [] {const char * v = std::getenv ("STRATA_ARENA_MMAP" );return v && v [0 ]== '1' ; }(); 3360if (arena_mmap ) { 3361const uint64_t file_bytes = want + (uint64_t )blob ; 3362uint64_t have = 0 ; 3363 { 3364 std::ifstream f (path , std::ios::binary | std::ios::ate ); 3365if (f )have = (uint64_t )f .tellg (); 3366 } 3367if (have == file_bytes ) { 3368const int fd = ::open (path .c_str (),O_RDONLY ); 3369void * v = fd >=0 ?mmap (nullptr , (size_t )file_bytes ,PROT_READ ,MAP_SHARED ,fd ,0 ) :MAP_FAILED ; 3370if (fd >=0 ) ::close (fd ); 3371if (v == MAP_FAILED ) {err = "ArenaExpertSource: mmap of " + path + " failed" ;return false; } 3372map_ = v ; 3373map_bytes_ = file_bytes ; 3374base_ = (const uint8_t * )v ; 3375pinned_bytes_ = 0 ; 3376dev_slice_ .clear (); 3377slice_bytes_ = 0 ; 3378blobs_ = n_layers * n_expert ; 3379n_expert_ = n_expert ; 3380reads_ = 0 ; 3381note_ = "mapped read-only from " + path + " (STRATA_ARENA_MMAP: not locked, not pinned)" ; 3382gib_per_s_ = 0.0 ; 3383load_seconds_ = load_read_s_ = load_copy_s_ = 0.0 ; 3384record_inputs (path ,gguf_ ,lay ,from_gguf );// session files: the mapped experts.bin is a model input 3385return 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. 3395ram_warning_ .clear (); 3396// (a shared arena, --shared-expert-arena, may already be in RAM for another engine: not checked) 3397if (detail::HostMemory hm ;shared_arena_file .empty ()&& detail::host_available_memory (hm )) { 3398const uint64_t need = want + (uint64_t )blob ; 3399const double gib = 1073741824.0 ; 3400char buf [512 ]; 3401if (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 ); 3408err = buf ; 3409return false; 3410 } 3411if (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 ); 3417ram_warning_ = buf ; 3418 } 3419 } 3420 3421uint64_t pack_hash = 0 ; 3422if (!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 ; 3428for (int64_t l = 0 ;l < n_layers ;++ l ) { 3429bounds .push_back (lay .layer_offset (l )); 3430loff .push_back (lay .layer_offset (l )); 3431lbytes .push_back (lay .blob_bytes (l )* (uint64_t )n_expert ); 3432 } 3433bounds .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 3441const char * defer_env = std::getenv ("STRATA_DEFERRED_REGISTER" ); 3442const 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 3445const bool deferred = false; 3446#endif 3447PinnedArena * a = deferred ?new PinnedArena (want + (uint64_t )blob ,bounds ,PinnedArena ::Deferred {}) 3448 :new PinnedArena (want + (uint64_t )blob ,bounds ,max_pinned_bytes , 3449shared_arena_file ,pack_hash ); 3450if (!a -> valid ()) { 3451const std::string why = a -> note ; 3452delete a ; 3453err = "ArenaExpertSource: the arena could not be reserved (" + 3454 std::to_string (want + (uint64_t )blob )+ " B)" + 3455 (why .empty () ? std::string {} :": " + why ); 3456return 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 ; 3461if (from_gguf ) { 3462for (int64_t l = 0 ;l < n_layers ;++ l ) 3463for (int r = 0 ;r < 3 ;++ r ) { 3464const std::string f = expert_gguf_file (gguf_ ,lay ,l ,r ); 3465if (std::find (files .begin (),files .end (),f )== files .end ())files .push_back (f ); 3466 } 3467 }else { 3468files .push_back (path ); 3469 } 3470 std::string why ; 3471const bool unbuffered = experts_unbuffered (files ,want + (uint64_t )blob ,why ); 3472const int readers = unbuffered ? std::max (threads ,16 ) :threads ;// 16 keep a PCIe 5 drive's queue full 3473LoadStats st ; 3474 std::atomic < int > ready {0 }; 3475 std::thread reg ; 3476if (deferred ) { 3477int dev = 0 ; 3478dev = dpct::get_current_device_id (); 3479reg = std::thread ([a ,& ready ,dev ] { 3480/* 3481DPCT1093: The "dev" device may be not the one intended for use. 3482Adjust the selected device if needed. 3483*/ 3484 dpct::select_device (dev ); 3485a -> register_slices (ready ); 3486 }); 3487 } 3488const std::atomic < int >* rp = deferred ?& ready :nullptr ; 3489if (from_gguf ) { 3490st = load_experts_gguf (gguf_ ,a -> data (),lay ,readers ,unbuffered ,rp ); 3491 }else { 3492if (unbuffered )st = load_experts_direct (path ,a -> data (),loff ,lbytes ,readers ,/*chunk=*/ 8u <<20 ,rp ); 3493if (!unbuffered || (!st .ok && st .error .empty ()))// unaligned ranges: the buffered reader 3494st = load_experts_ranges (path ,a -> data (),loff ,lbytes ,threads ,/*chunk=*/ 8u <<20 ,rp ); 3495 } 3496if (reg .joinable ())reg .join (); 3497 std::fprintf (stderr ,"strata generate: expert arena read %s (%s)\n" ,unbuffered ?"unbuffered" :"through the file cache" , 3498why .c_str ()); 3499if (!st .ok ) { 3500delete a ; 3501err = "ArenaExpertSource: the expert load was refused: " + (st .error .empty () ? std::string ("unknown" ) :st .error ); 3502return false; 3503 } 3504if (st .bytes != want ) { 3505delete a ; 3506err = "ArenaExpertSource: the load read " + std::to_string (st .bytes )+ " B of " + std::to_string (want ); 3507return false; 3508 } 3509if (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 ; 3516const uint64_t free_disk = arena_mmap && from_gguf ? (uint64_t ) std::filesystem::space ( 3517 std::filesystem::path (path ).parent_path (),space_ec ).available :0 ; 3518const bool room = !space_ec && free_disk >=want + (uint64_t )blob + (2ull <<30 ); 3519if (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 ); 3523if (arena_mmap && from_gguf && room ) { 3524const std::string tmp = path + ".tmp" ; 3525 std::FILE * f = std::fopen (tmp .c_str (),"wb" ); 3526bool ok = f != nullptr && std::fwrite (a -> data (),1 , (size_t )want ,f )== (size_t )want ; 3527if (ok ) { 3528 std::vector < uint8_t > pad ((size_t )blob ,0 ); 3529ok = std::fwrite (pad .data (),1 ,pad .size (),f )== pad .size (); 3530 } 3531if (f )ok = std::fclose (f )== 0 && ok ; 3532if (ok )ok = std::rename (tmp .c_str (),path .c_str ())== 0 ; 3533if (!ok ) std::remove (tmp .c_str ()); 3534 std::fprintf (stderr ,"strata generate: STRATA_ARENA_MMAP: %s %s (the next start maps it)\n" , 3535ok ?"wrote" :"could NOT write" ,path .c_str ()); 3536 } 3537arena_ = a ; 3538base_ = a -> data (); 3539pinned_bytes_ = a -> registered_bytes ; 3540// plan v0.3 P6: device aliases of the mapped registration, for the PCIe share of the misses 3541dev_slice_ .clear (); 3542slice_bytes_ = a -> slice_bytes ; 3543if (a -> registered_bytes > 0 ) { 3544 std::vector < uint64_t > starts = a -> slice_bytes > 0 ?a -> slice_starts : std::vector < uint64_t > {0 }; 3545for (uint64_t off :starts ) { 3546void * d = nullptr ; 3547if (DPCT_CHECK_ERROR (d = (void * )(void * )(base_ + off ))!= 0 ) { 3548/* 3549DPCT1010: SYCL uses exceptions to report errors and does 3550not use the error codes. The cudaGetLastError function call was 3551replaced with 0. You need to rewrite this code. 3552*/ 3553 (void )0 ; 3554dev_slice_ .clear (); 3555break ; 3556 } 3557dev_slice_ .push_back ((const uint8_t * )d ); 3558 } 3559 } 3560blobs_ = n_layers * n_expert ; 3561n_expert_ = n_expert ; 3562reads_ = 0 ; 3563note_ = a -> note ; 3564gib_per_s_ = st .gib_per_second (); 3565load_seconds_ = st .seconds ; 3566load_read_s_ = st .read_seconds ; 3567load_copy_s_ = st .copy_seconds ; 3568record_inputs (path ,gguf_ ,lay ,from_gguf ); 3569return true; 3570} 3571 3572void ArenaExpertSource ::close () { 3573#if !defined(_WIN32 ) 3574if (map_ != nullptr )munmap (map_ , (size_t )map_bytes_ ); 3575#endif 3576map_ = nullptr ; 3577map_bytes_ = 0 ; 3578inputs_ .clear (); 3579if (arena_ != nullptr ) { 3580delete (PinnedArena * )arena_ ; 3581arena_ = nullptr ; 3582 } 3583base_ = nullptr ; 3584blobs_ = 0 ; 3585n_expert_ = 0 ; 3586} 3587 3588void ArenaExpertSource ::prefetch (int64_t layer ,int64_t expert ) { 3589#if defined(_WIN32 ) 3590 (void )layer ; (void )expert ; 3591#else 3592if (map_ == nullptr || layer < 0 || expert < 0 || expert >=n_expert_ )return ; 3593const auto & lay = strata::kernels::cpu::expert_layout (); 3594const uint64_t off = lay .blob_offset (layer ,expert )& ~(uint64_t )4095 ; 3595const uint64_t end = lay .blob_offset (layer ,expert )+ lay .blob_bytes (layer ); 3596madvise ((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 ; 3609return 0 ; 3610#else 3611if (map_ == nullptr || layer < 0 || expert < 0 || expert >=n_expert_ )return 0 ; 3612const auto & lay = strata::kernels::cpu::expert_layout (); 3613const uint64_t off = (lay .blob_offset (layer ,expert )+ 4095 )& ~(uint64_t )4095 ; 3614const uint64_t end = (lay .blob_offset (layer ,expert )+ lay .blob_bytes (layer ))& ~(uint64_t )4095 ; 3615if (end <=off )return 0 ; 3616if (madvise ((uint8_t * )map_ + off , (size_t ) (end - off ),MADV_DONTNEED )!= 0 )return 0 ; 3617return end - off ; 3618#endif 3619} 3620 3621bool ArenaExpertSource ::pinned (int64_t layer ,int64_t expert )const { 3622if (base_ == nullptr || layer < 0 || expert < 0 || expert >=n_expert_ )return false; 3623const auto & lay = strata::kernels::cpu::expert_layout (); 3624return 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 { 3628if (dev_slice_ .empty ()|| !pinned (layer ,expert ))return nullptr ; 3629const auto & lay = strata::kernels::cpu::expert_layout (); 3630if (slice_bytes_ == 0 )return dev_slice_ [0 ]+ lay .blob_offset (layer ,expert ); 3631// one registration slice per layer 3632if ((size_t )layer >=dev_slice_ .size ())return nullptr ; 3633return 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 ) { 3637if (base_ == nullptr )return nullptr ; 3638if (layer < 0 || expert < 0 || expert >=n_expert_ )return nullptr ; 3639const int64_t idx = layer * n_expert_ + expert ; 3640if (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`. 3644return base_ + strata::kernels::cpu::expert_layout ().blob_offset (layer ,expert ); 3645} 3646 3647}// namespace strata::core