okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
d510921bc
main
1// src/core/expert_source.cpp - the adapter. See the header for the three clauses of the contract. 2#include "strata/core/expert_source.hpp" 3#include "strata/kernels/cpu/kq_avx2.hpp" 4#include "ggml.h" 5#include "ggml-cpu.h" 6#include "strata/core/latent_share.hpp" 7#include "strata/core/expert_nibble.hpp" 8#include "strata/core/conversation_memory.hpp" 9#include "strata/core/foresight_swap.hpp" 10#include "strata/core/on_device.hpp" 11#include "strata/core/page_cache_drop.hpp" 12#include "strata/core/ple_residency.hpp" 13#include "strata/core/resident_ram_copy.hpp" 14#include "strata/platform/aux_cpus.hpp" 15#include "strata/core/remote_experts.hpp" 16#include "strata/core/peer_experts.hpp" 17#include "strata/kernels/cpu/expert_layout.hpp" 18#include "strata/kernels/window_limits.hpp" 19#include "strata/artifact/gguf_reader.hpp" 20 21#include "strata/core/pinned.hpp" 22#include "strata/platform/memory.hpp" 23#include "strata/kernels/elementwise.hpp" 24#include "strata/kernels/quantize_act.hpp" 25#include "strata/kernels/s2_expert_grouped.hpp" 26#include "strata/kernels/cpu/kq_avx1.hpp" 27#include "strata/kernels/cpu/kq_avx2.hpp" 28#include "strata/kernels/cpu/pool.hpp" 29#include "strata/kernels/f16_bits.hpp" 30 31#include <cuda_runtime.h> 32#ifndef _WIN32 33#include <signal.h> 34#include <unistd.h> 35#endif 36 37#include <algorithm> 38#include <atomic> 39#include <cassert> 40#include <cerrno> 41#include <chrono> 42#include <cstdio> 43#include <cstdlib> 44#include <cstring> 45#include <deque> 46#include <fstream> 47#include <filesystem> 48#include <iterator> 49#include <sstream> 50#include <limits> 51#include <map> 52#include <memory> 53#include <mutex> 54#include <thread> 55#include <utility> 56#include <vector> 57 58#if defined(_WIN32 ) 59#define WIN32_LEAN_AND_MEAN 60#ifndef NOMINMAX 61#define NOMINMAX // std::numeric_limits<T>::max() below 62#endif 63#include <windows.h> 64#else 65#include <fcntl.h> 66#if defined(__APPLE__ ) 67#include <mach/mach.h> // host_statistics64: the available memory 68#endif 69#include <sys/mman.h> 70#include <sys/stat.h> 71#include <unistd.h> 72#endif 73#if defined(__linux__ ) 74#include <cerrno> 75#include <linux/aio_abi.h> // the kernel's own asynchronous reads (io_submit): no library, allowed by Docker's seccomp 76#include <sched.h> 77#include <sys/syscall.h> 78#endif 79 80// a 64-bit seek (as in pinned.cu): the 32-bit `fseek` wraps past 4 GiB, and the spelling differs per platform 81#ifndef STRATA_FSEEK64 82#ifdef _WIN32 83#define STRATA_FSEEK64 (f ,o ) _fseeki64((f), (long long) (o), SEEK_SET) 84#else 85#define STRATA_FSEEK64 (f ,o ) fseeko((f), (off_t) (o), SEEK_SET) 86#endif 87#endif 88 89// The pid of this process and whether a pid still exists (the shared arena's reader election, both OSes) 90static uint64_t arena_this_pid () { 91#ifdef _WIN32 92return (uint64_t )GetCurrentProcessId (); 93#else 94return (uint64_t )getpid (); 95#endif 96} 97static bool arena_pid_alive (uint64_t pid ) { 98#ifdef _WIN32 99HANDLE h = OpenProcess (PROCESS_QUERY_LIMITED_INFORMATION , FALSE, (DWORD )pid ); 100if (h == nullptr )return GetLastError ()== ERROR_ACCESS_DENIED ;// (denied: it exists; invalid parameter: it does not) 101DWORD code = 0 ; 102const bool alive = GetExitCodeProcess (h ,& code )&& code == STILL_ACTIVE ; 103CloseHandle (h ); 104return alive ; 105#else 106return !(kill ((pid_t )pid ,0 )!= 0 && errno == ESRCH ); 107#endif 108} 109 110namespace strata::core { 111 112namespace detail { 113 114bool cgroup_available_bytes (uint64_t limit ,const CgroupMemoryStat & stat ,uint64_t & bytes ) { 115bytes = 0 ; 116if (!stat .valid )return false; 117 118// memory.stat's counters can race memory.current, so bound them to charged usage first. The whole clean page 119// cache is reclaimable (149: MemAvailable counts active file pages too); the kernel keeps a low-watermark share. 120uint64_t reclaimable = std::min (std::max (stat .file ,stat .inactive_file ),stat .current ); 121reclaimable = stat .file_dirty >=reclaimable ?0 :reclaimable - stat .file_dirty ; 122reclaimable = stat .file_writeback >=reclaimable ?0 :reclaimable - stat .file_writeback ; 123reclaimable -= std::min (reclaimable /2 ,limit /64 ); 124 125// Reclaiming clean file pages reduces usage; saturating subtraction also handles a transient over-limit read. 126const uint64_t usage_after_reclaim = stat .current - reclaimable ; 127bytes = usage_after_reclaim < limit ?limit - usage_after_reclaim :0 ; 128return true; 129} 130 131uint64_t clamp_resident_budget (uint64_t requested ,uint64_t physical ,uint64_t commit ,uint64_t headroom ) { 132const uint64_t available = std::min (physical ,commit ); 133const uint64_t room = available > headroom ?available - headroom :0 ; 134if (requested <=room )return requested ; 135const uint64_t margin = 256ull <<20 ; 136return room > margin ?room - margin :0 ; 137} 138 139bool pin_depends_on_reclaim (uint64_t free_now ,uint64_t bytes ,uint64_t reserve ) { 140return bytes > 0 && free_now < bytes + reserve ; 141} 142 143bool wait_for_ram (uint64_t need ,double max_wait_s ,double step_s ,double note_s , 144const std::function < bool (uint64_t & )>& sample ,const std::function < void (double )>& sleep , 145const std::function < void (double ,uint64_t )>& progress ,double & waited ,uint64_t & available ) { 146waited = 0.0 ; 147if (!sample (available ))return false; 148double next_note = 0.0 ; 149while (available < need && waited < max_wait_s ) { 150if (progress && waited >=next_note ) { 151progress (waited ,available ); 152next_note = waited + note_s ; 153 } 154sleep (step_s ); 155waited += step_s ; 156if (!sample (available ))return false; 157 } 158return available >=need ; 159} 160 161bool pin_step_fits (uint64_t available ,uint64_t step ,uint64_t reserve ) { 162return available >=step + reserve ; 163} 164 165uint64_t meminfo_bytes (const std::string & meminfo_text ,const std::string & key ) { 166 std::istringstream in (meminfo_text ); 167 std::string line ; 168const std::string want = key + ":" ; 169while (std::getline (in ,line )) { 170 std::istringstream fields (line ); 171 std::string k ,unit ; 172uint64_t value = 0 ; 173if (fields >>k >>value && k == want ) { 174fields >>unit ; 175return unit == "kB" ?value * 1024 :value ; 176 } 177 } 178return 0 ; 179} 180 181uint64_t numa_pin_free (uint64_t global_free ,const std::vector < uint64_t >& node_free ) { 182if (node_free .size ()< 2 )return global_free ; 183const uint64_t smallest = * std::min_element (node_free .begin (),node_free .end ()); 184return std::min < uint64_t > (global_free ,smallest * (uint64_t )node_free .size ()); 185} 186 187std::array < std::pair < uint64_t ,uint64_t > ,3 > numa_slice_ranges (uint64_t slot_off ,const uint64_t role_bytes [3 ], 188int slice ,uint64_t page ) { 189assert (slice == 0 || slice == 1 ); 190 std::array < std::pair < uint64_t ,uint64_t > ,3 > out {}; 191uint64_t start = slot_off ; 192for (int r = 0 ;r < 3 ;++ r ) { 193const uint64_t mid = start + role_bytes [r ] /2 ,end = start + role_bytes [r ]; 194if (slice == 0 ) { 195out [r ]= {start /page * page , (mid + page - 1 ) /page * page }; 196 }else { 197const uint64_t lo = (mid + page - 1 ) /page * page ,hi = end /page * page ; 198out [r ]= hi > lo ? std::make_pair (lo ,hi ) : std::make_pair (lo ,lo ); 199 } 200start = end ; 201 } 202return out ; 203} 204 205std::string page_cache_hint (const std::string & meminfo_text ) { 206const uint64_t cache = meminfo_bytes (meminfo_text ,"Cached" )+ meminfo_bytes (meminfo_text ,"Buffers" ); 207if (cache < (1ull <<30 ))return "" ; 208char msg [420 ]; 209 std::snprintf (msg ,sizeof msg , 210"; %.1f GiB of the RAM is file cache (earlier runs' model files, which Linux gives back on demand - " 211"'free' showing little is normal). If the start still fails, free it with: " 212"sync; echo 1 | sudo tee /proc/sys/vm/drop_caches (or start strata serve with " 213"STRATA_DROP_CACHE_ON_EXIT=1 so it releases its model files when it stops)" , 214 (double )cache /1073741824.0 ); 215return msg ; 216} 217 218bool make_cache_complement_plan ( 219int64_t n_layers ,int64_t n_expert ,const std::vector < uint64_t >& layer_blob_bytes , 220const std::vector < std::pair < int32_t ,int32_t >>& primary_gpu_pairs , 221const std::vector < std::pair < int32_t ,int32_t >>& additional_gpu_pairs , 222 std::vector < uint64_t >& offsets ,uint64_t & bytes , std::string & err ) { 223offsets .clear (); 224bytes = 0 ; 225err .clear (); 226if (n_layers <=0 || n_expert <=0 || layer_blob_bytes .size ()!= (size_t )n_layers ) { 227err = "FileExpertSource: invalid geometry for the cache complement plan" ; 228return false; 229 } 230if ((uint64_t )n_layers > (uint64_t ) std::numeric_limits < size_t > ::max () / (uint64_t )n_expert ) { 231err = "FileExpertSource: cache complement index table is too large" ; 232return false; 233 } 234const size_t count = (size_t )n_layers * (size_t )n_expert ; 235 std::vector < uint8_t > omitted (count ,0 ); 236auto mark_pairs = [& ](const std::vector < std::pair < int32_t ,int32_t >>& pairs ,uint8_t bit , 237const char * label )-> bool { 238for (const auto & pair :pairs ) { 239if (pair .first < 0 || pair .second < 0 || pair .first >=n_layers || pair .second >=n_expert ) { 240err = std::string ("FileExpertSource: " )+ label + " pair is outside the expert geometry" ; 241return false; 242 } 243const size_t index = (size_t )pair .first * (size_t )n_expert + (size_t )pair .second ; 244if ((omitted [index ]& bit )!= 0 ) { 245err = std::string ("FileExpertSource: duplicate " )+ label + " pair in the cache complement plan" ; 246return false; 247 } 248if (bit == 2 && (omitted [index ]& 1 )!= 0 ) { 249err = "FileExpertSource: the primary and additional GPU expert tiers overlap" ; 250return false; 251 } 252omitted [index ] |=bit ; 253 } 254return true; 255 }; 256if (!mark_pairs (primary_gpu_pairs ,1 ,"primary GPU" )|| 257 !mark_pairs (additional_gpu_pairs ,2 ,"additional GPU" ))return false; 258for (uint64_t blob_bytes :layer_blob_bytes ) { 259if (blob_bytes == 0 ) { 260err = "FileExpertSource: cache complement layer has zero-sized expert blobs" ; 261return false; 262 } 263 } 264 265offsets .assign (count ,kNoCacheComplement ); 266for (int64_t layer = 0 ;layer < n_layers ;++ layer ) { 267const uint64_t blob_bytes = layer_blob_bytes [(size_t )layer ]; 268for (int64_t expert = 0 ;expert < n_expert ;++ expert ) { 269const size_t index = (size_t )layer * (size_t )n_expert + (size_t )expert ; 270if (omitted [index ]!= 0 )continue ; 271if (bytes > std::numeric_limits < uint64_t > ::max ()- blob_bytes ) { 272offsets .clear (); 273bytes = 0 ; 274err = "FileExpertSource: cache complement size overflows" ; 275return false; 276 } 277offsets [index ]= bytes ; 278bytes += blob_bytes ; 279 } 280 } 281if (bytes > (uint64_t ) std::numeric_limits < size_t > ::max ()) { 282offsets .clear (); 283bytes = 0 ; 284err = "FileExpertSource: cache complement exceeds the host address space" ; 285return false; 286 } 287return true; 288} 289 290const uint8_t * cache_complement_blob_or_fallback ( 291size_t index ,const std::vector < uint64_t >& offsets ,const uint8_t * complement_host , 292const uint8_t * mapped_fallback ) { 293if (complement_host != nullptr && index < offsets .size ()&& offsets [index ]!= kNoCacheComplement ) 294return complement_host + (size_t )offsets [index ]; 295return mapped_fallback ; 296} 297 298int64_t choose_resident_keep_from (const std::vector < uint64_t >& slot_bytes ,uint64_t base_bytes ,uint64_t budget , 299int64_t lend_from ) { 300if (base_bytes > budget )return -1 ; 301const int64_t slots = (int64_t )slot_bytes .size (); 302if (lend_from < 0 || lend_from > slots )lend_from = slots ;// no lend region: only the experts no slot holds 303int64_t keep = slots ; 304uint64_t bytes = base_bytes ; 305while (keep > lend_from ) { 306const uint64_t b = slot_bytes [(size_t )keep - 1 ]; 307if (b > budget - bytes )break ; 308bytes += b ; 309-- keep ; 310 } 311return keep ; 312} 313 314int64_t append_stage_lend_regions (int64_t n_layers ,int64_t n_expert ,const std::vector < uint64_t >& layer_blob_bytes , 315 std::vector < uint64_t >& offsets ,uint64_t & bytes ,uint64_t cap_bytes , 316const std::vector < std::vector < std::pair < int32_t ,int32_t >>>& regions , 317 std::string & err ) { 318const size_t blobs = (size_t ) (n_layers * n_expert ); 319if (n_layers <=0 || n_expert <=0 || layer_blob_bytes .size ()!= (size_t )n_layers || offsets .size ()!= blobs ) { 320err = "append_stage_lend_regions: the plan does not match the geometry" ; 321return -1 ; 322 } 323 std::vector < std::pair < int32_t ,int32_t >> sorted ; 324for (const auto & region :regions ) {// validate the whole request before touching the plan 325for (const auto & pair :region ) 326if (pair .first < 0 || pair .first >=n_layers || pair .second < 0 || pair .second >=n_expert ) { 327err = "append_stage_lend_regions: a lend-region expert is outside the model" ; 328return -1 ; 329 } 330sorted = region ; 331 std::sort (sorted .begin (),sorted .end ()); 332for (size_t i = 1 ;i < sorted .size ();++ i ) 333if (sorted [i ]== sorted [i - 1 ]) { 334err = "append_stage_lend_regions: a stage's lend region repeats an expert" ; 335return -1 ; 336 } 337 } 338int64_t kept = 0 ; 339for (const auto & region :regions ) { 340for (const auto & pair :region ) { 341const size_t index = (size_t )pair .first * (size_t )n_expert + (size_t )pair .second ; 342if (offsets [index ]!= kNoCacheComplement )continue ;// already in the copy: the complement, or a 343// CUDA0 lend slot the region is asked to skip 344const uint64_t b = layer_blob_bytes [(size_t )pair .first ]; 345if (b > cap_bytes - bytes )break ;// this stage's rest keeps the file fallback 346offsets [index ]= bytes ; 347bytes += b ; 348++ kept ; 349 } 350 } 351return kept ; 352} 353 354bool exchange_cache_complement (std::vector < uint64_t >& offsets ,size_t in ,size_t out ) { 355if (in == out || in >=offsets .size ()|| out >=offsets .size ()|| offsets [in ]== kNoCacheComplement || 356offsets [out ]!= kNoCacheComplement )return false; 357offsets [out ]= offsets [in ]; 358offsets [in ]= kNoCacheComplement ; 359return true; 360} 361 362}// namespace detail 363 364namespace { 365 366#if defined(__linux__ ) 367bool read_cgroup_memory_stat (const std::filesystem::path & path ,uint64_t current , 368 detail::CgroupMemoryStat & stat ) { 369 std::ifstream input (path /"memory.stat" ); 370if (!input )return false; 371 372bool inactive_file = false,file_dirty = false,file_writeback = false,file = false; 373 std::string line ; 374while (std::getline (input ,line )) { 375 std::istringstream fields (line ); 376 std::string key ; 377uint64_t value = 0 ; 378if (!(fields >>key >>value ))return false; 379fields >> std::ws ; 380if (!fields .eof ())return false; 381 382if (key == "inactive_file" ) { 383if (inactive_file )return false; 384inactive_file = true; 385stat .inactive_file = value ; 386 }else if (key == "file_dirty" ) { 387if (file_dirty )return false; 388file_dirty = true; 389stat .file_dirty = value ; 390 }else if (key == "file_writeback" ) { 391if (file_writeback )return false; 392file_writeback = true; 393stat .file_writeback = value ; 394 }else if (key == "file" ) {// 149: optional (every v2 kernel has it); 0 = inactive_file alone 395if (file )return false; 396file = true; 397stat .file = value ; 398 } 399 } 400if (!input .eof ()|| !inactive_file || !file_dirty || !file_writeback )return false; 401stat .current = current ; 402stat .valid = true; 403return true; 404} 405#endif 406 407}// namespace 408 409namespace detail { 410 411bool host_available_memory (HostMemory & m ,const std::string & meminfo ,const std::string & self_cgroup , 412const std::string & cgroup_root ) { 413m = HostMemory {}; 414#if defined(_WIN32 ) 415 (void )meminfo ; (void )self_cgroup ; (void )cgroup_root ; 416MEMORYSTATUSEX status {}; 417status .dwLength = sizeof (status ); 418if (!GlobalMemoryStatusEx (& status ))return false; 419m .available = (uint64_t )status .ullAvailPhys ; 420m .commit = (uint64_t )status .ullAvailPageFile ; 421return m .available > 0 ; 422#elif defined(__linux__ ) 423// MemAvailable includes reclaimable page cache, unlike _SC_AVPHYS_PAGES. 424 std::ifstream info (meminfo ); 425 std::string line ; 426uint64_t bytes = 0 ; 427 std::optional < uint64_t > mem_total ;// a limit below it is a container's (its /proc/meminfo is the host's) 428while (std::getline (info ,line )) { 429 std::istringstream fields (line ); 430 std::string key ,unit ; 431uint64_t value = 0 ; 432if (fields >>key >>value >>unit && key == "MemAvailable:" && unit == "kB" && 433value <= std::numeric_limits < uint64_t > ::max () /1024 )bytes = value * 1024 ; 434else if (key == "MemTotal:" && unit == "kB" && value <= std::numeric_limits < uint64_t > ::max () /1024 )mem_total = value * 1024 ; 435 } 436if (bytes == 0 )return false; 437const bool inactive_only = strata::core::mem_credit_inactive_only (std::getenv ("STRATA_MEM_CREDIT_INACTIVE" )); 438// Account for the tightest cgroup ancestor limit when its normal mount is visible. 439// This is a point-in-time guard, not a reservation against concurrent allocations. 440 std::ifstream groups (self_cgroup ); 441if (!groups )return false; 442const std::filesystem::path root (cgroup_root ); 443bool v2 = false; 444 std::string v1_path ;// the memory controller's group (cgroup v1), when there is no v2 line 445while (std::getline (groups ,line )) { 446if (line .rfind ("0::/" ,0 )!= 0 ) { 447// v1: "N:controller[,controller]:/path" 448const size_t c1 = line .find (':' ),c2 = c1 == std::string::npos ?c1 :line .find (':' ,c1 + 1 ); 449if (c2 == std::string::npos )continue ; 450 std::istringstream ctl (line .substr (c1 + 1 ,c2 - c1 - 1 )); 451for (std::string c ; std::getline (ctl ,c ,',' );) 452if (c == "memory" )v1_path = line .substr (c2 + 1 ); 453continue ; 454 } 455auto path = (root /line .substr (4 )).lexically_normal (); 456if (path .string ().rfind (root .string (),0 )!= 0 || !std::filesystem::is_directory (path ))return false; 457v2 = true; 458while (path .string ().rfind (root .string (),0 )== 0 ) { 459 std::ifstream limit_file (path /"memory.max" ),current_file (path /"memory.current" ); 460 std::string limit ; 461uint64_t current = 0 ; 462const bool readable = bool (limit_file >>limit )&& bool (current_file >>current ); 463// The host's root cgroup has no memory.max; ordinary child groups must expose their limits. 464if (!readable && !(path == root && !std::filesystem::exists (path /"memory.max" )&& 465 std::filesystem::exists (path /"cgroup.controllers" )))return false; 466if (readable && limit != "max" ) { 467try { 468size_t consumed = 0 ; 469const uint64_t cap = std::stoull (limit ,& consumed ); 470if (consumed != limit .size ())return false; 471CgroupMemoryStat stat ; 472if (!read_cgroup_memory_stat (path ,current ,stat ))return false; 473uint64_t cgroup_available = 0 ; 474if (!cgroup_available_bytes (cap ,stat ,cgroup_available ))return false; 475// a container's limit: the memory guard's file-list credit (no shmem, no locked pages), this margin kept 476 std::ifstream stat_file (path /"memory.stat" ); 477 std::ostringstream stat_text ; 478if (stat_file )stat_text <<stat_file .rdbuf (); 479const strata::core::ArenaCgroupRoom room = 480 strata::core::arena_cgroup_room (cap ,current ,stat_text .str (),mem_total ,inactive_only ); 481if (room .applies )cgroup_available = room .room ; 482bytes = std::min (bytes ,cgroup_available ); 483m .cgroup_limit = std::min (m .cgroup_limit ,cap ); 484 }catch (...) {return false; } 485 } 486if (path == root )break ; 487path = path .parent_path (); 488 } 489 } 490if (!v2 && !v1_path .empty ()) { 491// #633: cgroup v1 (older Docker hosts, RHEL 7/8): the memory controller's group and its ancestors. An 492// unlimited group says a number near 2^63 (rounded to its page size); a group whose files are not 493// visible (no mount in this namespace) is skipped - MemAvailable alone, as with no cgroup at all. 494const std::filesystem::path mroot = root /"memory" ; 495auto path = (mroot /v1_path .substr (v1_path .rfind ('/' ,0 )== 0 ?1 :0 )).lexically_normal (); 496while (path .string ().rfind (mroot .string (),0 )== 0 ) { 497 std::ifstream limit_file (path /"memory.limit_in_bytes" ),usage_file (path /"memory.usage_in_bytes" ); 498uint64_t cap = 0 ,usage = 0 ; 499if (limit_file >>cap && usage_file >>usage && cap < (1ull <<62 )) { 500bytes = std::min (bytes ,usage < cap ?cap - usage :0 ); 501m .cgroup_limit = std::min (m .cgroup_limit ,cap ); 502 } 503if (path == mroot )break ; 504path = path .parent_path (); 505 } 506 } 507m .available = bytes ; 508return true; 509#elif defined(__APPLE__ ) 510// macOS: free + inactive + purgeable pages (what the OS can hand out without swapping), as vm_stat reports them 511 (void )meminfo ; (void )self_cgroup ; (void )cgroup_root ; 512vm_statistics64_data_t vs {}; 513mach_msg_type_number_t count = HOST_VM_INFO64_COUNT ; 514vm_size_t page_bytes = 0 ; 515if (host_page_size (mach_host_self (),& page_bytes )!= KERN_SUCCESS || 516host_statistics64 (mach_host_self (),HOST_VM_INFO64 , (host_info64_t )& vs ,& count )!= KERN_SUCCESS )return false; 517m .available = ((uint64_t )vs .free_count + vs .inactive_count + vs .purgeable_count )* (uint64_t )page_bytes ; 518return m .available > 0 ; 519#else 520 (void )meminfo ; (void )self_cgroup ; (void )cgroup_root ; 521const long pages = sysconf (_SC_AVPHYS_PAGES ); 522const long page_bytes = sysconf (_SC_PAGESIZE ); 523if (pages <=0 || page_bytes <=0 || 524 (uint64_t )pages > std::numeric_limits < uint64_t > ::max () / (uint64_t )page_bytes )return false; 525m .available = (uint64_t )pages * (uint64_t )page_bytes ; 526return m .available > 0 ; 527#endif 528} 529 530}// namespace detail 531 532namespace { 533 534bool available_memory_bytes (uint64_t & bytes ,uint64_t * commit = nullptr ) { 535 detail::HostMemory m ; 536if (!detail::host_available_memory (m ))return false; 537bytes = m .available ; 538if (commit != nullptr )* commit = m .commit ; 539return bytes > 0 ; 540} 541 542/// #1250: the pages that are really free (MemFree), not the reclaimable cache MemAvailable counts; false when unknown. 543bool free_memory_bytes (uint64_t & bytes ) { 544#if defined(__linux__ ) 545 std::ifstream info ("/proc/meminfo" ); 546if (!info )return false; 547 std::stringstream text ; 548text <<info .rdbuf (); 549bytes = detail::meminfo_bytes (text .str (),"MemFree" ); 550if (bytes == 0 )return false; 551// 0.1.42: a multi-socket host's nodes each have their own free pages; judge by the emptiest one too 552 std::vector < uint64_t > nodes ; 553for (int n = 0 ;n < 64 ;++ n ) { 554 std::ifstream node ("/sys/devices/system/node/node" + std::to_string (n )+ "/meminfo" ); 555if (!node )break ; 556 std::string line ; 557while (std::getline (node ,line )) { 558 std::istringstream f (line ); 559 std::string a ,id ,key ; 560uint64_t kb = 0 ; 561if (f >>a >>id >>key >>kb && key == "MemFree:" ) {nodes .push_back (kb * 1024 );break ; } 562 } 563 } 564bytes = detail::numa_pin_free (bytes ,nodes ); 565return bytes > 0 ; 566#else 567bytes = 0 ; 568return false; 569#endif 570} 571 572void log_complement_memory (const char * stage ,uint64_t requested ) { 573#if defined(_WIN32 ) 574MEMORYSTATUSEX status {}; 575status .dwLength = sizeof (status ); 576if (!GlobalMemoryStatusEx (& status )) { 577 std::fprintf (stderr ,"FileExpertSource: %s: GlobalMemoryStatusEx failed (error %lu)\n" ,stage ,GetLastError ()); 578return ; 579 } 580 std::fprintf (stderr ,"FileExpertSource: %s: requested %.2f GiB, available RAM %.2f GiB, available commit %.2f GiB " 581"(limit %.2f GiB), available virtual address space %.2f GiB\n" , 582stage , (double )requested /1073741824.0 , (double )status .ullAvailPhys /1073741824.0 , 583 (double )status .ullAvailPageFile /1073741824.0 , (double )status .ullTotalPageFile /1073741824.0 , 584 (double )status .ullAvailVirtual /1073741824.0 ); 585#else 586 (void )stage ; 587 (void )requested ; 588#endif 589} 590 591#if defined(__linux__ ) 592/// STRATA_NUMA_SPLIT step B: each NUMA slice of every complement slot (numa_slice_ranges) is first-touched by a helper 593/// thread pinned to one core of that slice's node, so the default local policy puts its pages there (no mbind: ~113k 594/// ranges would split the arena into more VMAs than vm.max_map_count allows). Inactive (`place` false) unless the 595/// live pool split on real nodes; then the paced fault loop hands it each step to touch. 596struct NumaComplementPlacement { 597bool place = false; 598int nodes [2 ]= {-1 ,-1 }; 599int core [2 ]= {-1 ,-1 }; 600 std::vector < std::pair < uint64_t ,uint64_t >> ranges [2 ];///< page-aligned, sorted, coalesced, arena offsets 601uint64_t slice_bytes [2 ]= {0 ,0 }; 602 std::vector < uint64_t > free_before ;///< MemFree per node before the allocation 603 std::vector < uint64_t > free_after ;///< the same after the model files' pages are released 604 std::atomic < bool > pin_failed {false}; 605 std::chrono::steady_clock::time_point t0 ; 606 607static std::vector < uint64_t > node_free () { 608// CBA: stops at the first missing node directory (as free_memory_bytes does), sparse node ids give a false 609// "at risk 0.00" line only; list the node directory if a sparse-id host ever shows it 610 std::vector < uint64_t > out ; 611for (int n = 0 ;n < 64 ;++ n ) { 612 std::ifstream node ("/sys/devices/system/node/node" + std::to_string (n )+ "/meminfo" ); 613if (!node )break ; 614 std::string line ; 615uint64_t kb = 0 ; 616while (std::getline (node ,line )) { 617 std::istringstream f (line ); 618 std::string a ,id ,key ; 619if (f >>a >>id >>key >>kb && key == "MemFree:" )break ; 620kb = 0 ; 621 } 622out .push_back (kb * 1024 ); 623 } 624return out ; 625 } 626static std::string free_text (const std::vector < uint64_t >& free ) { 627 std::string s ; 628char buf [64 ]; 629for (size_t n = 0 ;n < free .size ();++ n ) { 630 std::snprintf (buf ,sizeof buf ,"%snode %zu %.2f GiB" ,n ?", " :"" ,n , (double )free [n ] /1073741824.0 ); 631s += buf ; 632 } 633return s ; 634 } 635 636/// Decides from the live pool's plan; false with a logged reason when the split is on but placement cannot run. 637void init (const std::vector < uint64_t >& offsets ,int64_t n_expert ,const std::vector < uint64_t >& blob_bytes , 638const std::vector < uint64_t >& role_bytes ) { 639// relies on the pool being built first (generate.cpp: the ExpertPool at ~5632, the complement at ~7690) 640const auto & plan = strata::kernels::cpu::active_numa_split (); 641if (!plan .on || plan .test )return ; 642free_before = node_free (); 643const char * why = nullptr ; 644if (role_bytes .size ()!= 3 * blob_bytes .size ())why = "this pack has no per-role byte sizes (not a GGUF-mapped native pack)" ; 645for (size_t l = 0 ;why == nullptr && l < blob_bytes .size ();++ l ) 646if (role_bytes [3 * l ]+ role_bytes [3 * l + 1 ]+ role_bytes [3 * l + 2 ]!= blob_bytes [l ]) 647why = "the role sizes do not add up to the expert blob" ; 648for (int k = 0 ;why == nullptr && k < 2 ;++ k ) 649if (plan .cores [k ].empty ())why = "a slice has no core" ; 650else if (plan .nodes [k ]< 0 || plan .nodes [k ] >=64 )why = "a node id is out of range" ; 651if (why != nullptr ) { 652 std::fprintf (stderr ,"FileExpertSource: WARNING: NUMA placement FAILED: %s; the complement is placed by " 653"first touch as usual (the split runs with remote reads)\n" ,why ); 654return ; 655 } 656for (int k = 0 ;k < 2 ;++ k ) { 657nodes [k ]= plan .nodes [k ]; 658core [k ]= plan .cores [k ].front ();// workers come before the host core in the plan 659 std::vector < std::pair < uint64_t ,uint64_t >> all ; 660for (size_t i = 0 ;i < offsets .size ();++ i ) { 661if (offsets [i ]== detail::kNoCacheComplement )continue ; 662const size_t l = i / (size_t )n_expert ; 663for (const auto & r : detail::numa_slice_ranges (offsets [i ],& role_bytes [3 * l ],k )) 664if (r .second > r .first )all .push_back (r ); 665 } 666 std::sort (all .begin (),all .end ()); 667for (const auto & r :all ) {// coalesce: ends become monotonic, so a step finds its first range by bisection 668if (!ranges [k ].empty ()&& r .first <=ranges [k ].back ().second ) 669ranges [k ].back ().second = std::max (ranges [k ].back ().second ,r .second ); 670else ranges [k ].push_back (r ); 671 } 672for (const auto & r :ranges [k ])slice_bytes [k ]+= r .second - r .first ; 673 } 674place = true; 675t0 = std::chrono::steady_clock::now (); 676 std::fprintf (stderr ,"FileExpertSource: NUMA placement of the complement: slice 0 -> node %d (%.2f GiB, toucher " 677"CPU %d), slice 1 -> node %d (%.2f GiB, toucher CPU %d), 4 KiB pages; free before: %s\n" , 678nodes [0 ], (double )slice_bytes [0 ] /1073741824.0 ,core [0 ],nodes [1 ], 679 (double )slice_bytes [1 ] /1073741824.0 ,core [1 ],free_text (free_before ).c_str ()); 680 } 681 682/// Touches one byte per page of each slice's ranges clipped to [lo, hi), one pinned thread per slice; then the 683/// calling thread touches the step's other pages (outside every slice: slot tails, the arena end). The caller 684/// must not re-touch slice pages: with automatic NUMA balancing on, its access faults would migrate them to its node. 685void touch_step (uint8_t * arena ,uint64_t lo ,uint64_t hi ) { 686// CBA: two threads spawned per 1 GiB step (~50 spawns per start); long-lived touchers if the spawn ever shows 687auto touch = [& ](int k ) { 688cpu_set_t set ; 689CPU_ZERO (& set ); 690CPU_SET (core [k ],& set ); 691if (sched_setaffinity (0 ,sizeof set ,& set )!= 0 )pin_failed = true; 692const auto & rs = ranges [k ]; 693auto it = std::partition_point (rs .begin (),rs .end (), [& ](const auto & r ) {return r .second <=lo ; }); 694for (;it != rs .end ()&& it -> first < hi ;++ it ) 695for (uint64_t at = std::max (it -> first ,lo );at < std::min (it -> second ,hi );at += 4096 ) 696 ((volatile uint8_t * )arena )[at ]= 0 ; 697 }; 698// CBA: a failed spawn terminates; fall back to an unpinned touch if it ever happens 699 std::thread a (touch ,0 ),b (touch ,1 ); 700a .join (); 701b .join (); 702size_t c [2 ]= {0 ,0 };// the pages no slice holds, as the default loop touches them 703for (uint64_t at = lo ;at < hi ;at += 4096 ) { 704bool covered = false; 705for (int k = 0 ;k < 2 ;++ k ) { 706while (c [k ]< ranges [k ].size ()&& ranges [k ][c [k ]].second <=at )++ c [k ]; 707covered = covered || (c [k ]< ranges [k ].size ()&& ranges [k ][c [k ]].first <=at ); 708 } 709if (!covered ) ((volatile uint8_t * )arena )[at ]= 0 ; 710 } 711 } 712 713/// After the drop: a node whose free memory cannot take its slice plus `reserve_share` will spill to the other node 714/// (no local reclaim); named up front, the 95 % check stays the verdict. 715void check_room (uint64_t reserve_share )const { 716for (int k = 0 ;k < 2 ;++ k ) { 717const uint64_t room = (size_t )nodes [k ]< free_after .size () ?free_after [(size_t )nodes [k ]] :0 ; 718if (room < slice_bytes [k ]+ reserve_share ) 719 std::fprintf (stderr ,"FileExpertSource: WARNING: NUMA placement at risk: node %d has %.2f GiB free for its " 720"%.2f GiB slice plus %.2f GiB of reserve\n" , 721nodes [k ], (double )room /1073741824.0 , (double )slice_bytes [k ] /1073741824.0 , 722 (double )reserve_share /1073741824.0 ); 723 } 724 } 725 726/// Samples one page in 64 of each slice with move_pages (null node list: returns each page's node) and logs the 727/// share on the intended node, once the arena is registered (its final state); `got < bytes` means the paced loop 728/// stopped early, `registered < bytes` that the driver did not page-lock all of it: the placement then fails. 729void report (const uint8_t * arena ,uint64_t got ,uint64_t registered ,uint64_t bytes ,const char * stop )const { 730const double secs = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 731uint64_t on_node [2 ]= {0 ,0 },sampled [2 ]= {0 ,0 },per_node [2 ][64 ]= {},absent [2 ]= {0 ,0 }; 732constexpr int kNotSampled = -100000 ;// outside any per-page status (a node id, or -errno) 733int sys_errno [2 ]= {0 ,0 };// first errno of a failed move_pages batch, per slice 734size_t batches [2 ]= {0 ,0 },failed [2 ]= {0 ,0 }; 735 std::vector < void *> pages ; 736 std::vector < int > status ; 737for (int k = 0 ;k < 2 ;++ k ) { 738uint64_t n = 0 ; 739pages .clear (); 740for (const auto & r :ranges [k ]) 741for (uint64_t at = r .first ;at < r .second ;at += 4096 ,++ n ) 742if (n %64 == 0 )pages .push_back ((void * ) (arena + at )); 743status .assign (pages .size (),-1 ); 744for (size_t b = 0 ;b < pages .size ();b += 4096 ) { 745const size_t cnt = std::min < size_t > (4096 ,pages .size ()- b ); 746++ batches [k ]; 747if (syscall (SYS_move_pages ,0 , (unsigned long )cnt ,pages .data ()+ b ,nullptr ,status .data ()+ b ,0 )!= 0 ) { 748if (sys_errno [k ]== 0 )sys_errno [k ]= errno ; 749++ failed [k ]; 750for (size_t i = b ;i < b + cnt ;++ i )status [i ]= kNotSampled ;// the syscall failed: no sample, unlike a page's own -errno 751 } 752 } 753for (int s :status ) { 754if (s == kNotSampled )continue ; 755++ sampled [k ]; 756if (s >=0 && s < 64 )++ per_node [k ][s ]; 757else ++ absent [k ]; 758 } 759on_node [k ]= nodes [k ] >=0 && nodes [k ]< 64 ?per_node [k ][nodes [k ]] :0 ; 760 } 761double share [2 ]; 762for (int k = 0 ;k < 2 ;++ k )share [k ]= sampled [k ]> 0 ?100.0 * (double )on_node [k ] / (double )sampled [k ] :0.0 ; 763char what [2 ][96 ];// a slice whose move_pages batches all failed has no share to print 764for (int k = 0 ;k < 2 ;++ k ) { 765if (batches [k ]> 0 && failed [k ]== batches [k ]) std::snprintf (what [k ],sizeof what [k ],"not verified" ); 766else std::snprintf (what [k ],sizeof what [k ],"%.2f GiB (%.1f %% of its slices)" , 767share [k ] /100.0 * (double )slice_bytes [k ] /1073741824.0 ,share [k ]); 768 } 769 std::fprintf (stderr ,"FileExpertSource: NUMA placement: node %d %s, node %d %s; free before: %s; after the drop: %s; " 770"pages taken and page-locked in %.1f s since the placement started\n" , 771nodes [0 ],what [0 ],nodes [1 ],what [1 ],free_text (free_before ).c_str (),free_text (free_after ).c_str (),secs ); 772if (got < bytes ) 773 std::fprintf (stderr ,"FileExpertSource: WARNING: NUMA placement FAILED: the paced loop stopped at %.2f of %.2f " 774"GiB (%s); the rest is first-touched by unpinned copy threads (memory not placed on its node: the split runs with remote reads)\n" , 775 (double )got /1073741824.0 , (double )bytes /1073741824.0 ,stop != nullptr ?stop :"?" ); 776else if (registered < bytes ) 777 std::fprintf (stderr ,"FileExpertSource: WARNING: NUMA placement FAILED: only %.2f of %.2f GiB page-locked (%s); " 778"the unregistered pages can be migrated by NUMA balancing (memory not placed on its node: the split runs with remote reads)\n" , 779 (double )registered /1073741824.0 , (double )bytes /1073741824.0 ,stop != nullptr ?stop :"?" ); 780if (pin_failed ) 781 std::fprintf (stderr ,"FileExpertSource: WARNING: NUMA placement: a toucher could not be pinned to its core\n" ); 782for (int k = 0 ;k < 2 ;++ k ) { 783if (batches [k ]> 0 && failed [k ]== batches [k ]) { 784 std::fprintf (stderr ,"FileExpertSource: WARNING: NUMA placement could not be verified: move_pages failed " 785"(errno %d: %s) for slice %d (node %d)\n" ,sys_errno [k ], std::strerror (sys_errno [k ]),k ,nodes [k ]); 786continue ; 787 } 788if (failed [k ]> 0 ) 789 std::fprintf (stderr ,"FileExpertSource: WARNING: NUMA placement: move_pages failed (errno %d: %s) for %zu of %zu " 790"batches of slice %d; judged on the other samples\n" ,sys_errno [k ], 791 std::strerror (sys_errno [k ]),failed [k ],batches [k ],k ); 792if (share [k ]< 95.0 ) 793 std::fprintf (stderr ,"FileExpertSource: WARNING: NUMA placement FAILED: slice %d has %.1f %% of its pages " 794"on node %d (< 95 %%; of %llu sampled: node %d %llu, node %d %llu, not present %llu)\n" , 795k ,share [k ],nodes [k ], (unsigned long long )sampled [k ],nodes [0 ], 796 (unsigned long long )per_node [k ][nodes [0 ]],nodes [1 ], (unsigned long long )per_node [k ][nodes [1 ]], 797 (unsigned long long )absent [k ]); 798 } 799 } 800}; 801#endif 802 803/// #286: an unbuffered file handle - a HANDLE on Windows, an O_DIRECT descriptor (as a pointer-sized integer) on Linux. 804void close_direct (void * h ) { 805#if defined(_WIN32 ) 806CloseHandle ((HANDLE )h ); 807#else 808 ::close ((int ) (intptr_t )h ); 809#endif 810} 811 812#if defined(__linux__ ) 813/// #3237: how fast this drive serves the experts' reads the two ways the file tier can take them - O_DIRECT preads of 814/// 1 MiB at random places on 8 threads (the unbuffered tier's I/O threads) against first touches of the pages of random 815/// 1 MiB pieces of a mapping on 3 threads (the cached tier: the pool's threads faulting the page cache in). Regions the 816/// page cache already holds are skipped, and the probed ranges are dropped from the cache again. The best of two 817/// rounds each; a few hundred MiB read, under two seconds per pass. Done once per process. false: not measurable. 818struct TierProbeResult {bool done = false,ok = false;double direct_bps = 0 ,cached_bps = 0 ; }; 819 820bool file_tier_probe (const std::vector < std::string >& paths ,double & direct_bps ,double & cached_bps ) { 821static std::mutex mu ; 822static TierProbeResult memo ; 823 std::lock_guard < std::mutex > lk (mu ); 824if (memo .done ) {direct_bps = memo .direct_bps ;cached_bps = memo .cached_bps ;return memo .ok ; } 825memo .done = true; 826const std::string * best = nullptr ; 827uint64_t size = 0 ; 828for (const std::string & p :paths ) { 829struct stat st {}; 830if (::stat (p .c_str (),& st )== 0 && (uint64_t )st .st_size > size ) {size = (uint64_t )st .st_size ;best = & p ; } 831 } 832constexpr uint64_t kRegion = 1ull <<20 ; 833constexpr int kPerPass = 96 ,kRounds = 2 ; 834constexpr int kDirectThreads = 8 ,kCachedThreads = 3 ; 835if (best == nullptr || size < 8ull * kPerPass * kRegion * 2 )return false; 836const int fd_d = ::open (best -> c_str (),O_RDONLY |O_DIRECT |O_CLOEXEC ); 837const int fd_b = ::open (best -> c_str (),O_RDONLY |O_CLOEXEC ); 838void * map = fd_b >=0 ?mmap (nullptr , (size_t )size ,PROT_READ ,MAP_SHARED ,fd_b ,0 ) :MAP_FAILED ; 839auto cleanup = [& ] { 840if (map != MAP_FAILED )munmap (map , (size_t )size ); 841if (fd_d >=0 ) ::close (fd_d ); 842if (fd_b >=0 ) ::close (fd_b ); 843 }; 844if (fd_d < 0 || map == MAP_FAILED ) {cleanup ();return false; } 845const uint8_t * base = static_cast < const uint8_t *> (map ); 846uint64_t seed = (uint64_t ) std::chrono::steady_clock::now ().time_since_epoch ().count ()* 6364136223846793005ull + 1442695040888963407ull ; 847 std::vector < uint64_t > used ; 848auto pick = [& ](std::vector < uint64_t >& out ) {// kPerPass distinct 1 MiB pieces the page cache does not hold 849out .clear (); 850 std::vector < unsigned char > vec (kRegion /4096 ); 851for (int tries = 0 ; (int )out .size ()< kPerPass && tries < kPerPass * 40 ;++ tries ) { 852seed = seed * 6364136223846793005ull + 1442695040888963407ull ; 853const uint64_t off = ((seed >>20 ) % (size /kRegion ))* kRegion ; 854if (std::find (used .begin (),used .end (),off )!= used .end ())continue ; 855if (mincore ((void * ) (base + off ), (size_t )kRegion ,vec .data ())!= 0 )continue ; 856int res = 0 ; 857for (unsigned char c :vec )res += c & 1 ; 858if (res * 4 > (int )vec .size ())continue ; 859used .push_back (off ); 860out .push_back (off ); 861 } 862return (int )out .size () >=kPerPass /2 ; 863 }; 864auto preadn = [& ](uint8_t * dst ,uint64_t off ) { 865uint64_t done = 0 ; 866while (done < kRegion ) { 867const ssize_t r = ::pread (fd_d ,dst + done , (size_t ) (kRegion - done ), (off_t ) (off + done )); 868if (r < 0 ) {if (errno == EINTR )continue ;return false; } 869if (r == 0 )return false; 870done += (uint64_t )r ; 871 } 872return true; 873 }; 874double best_d = 0 ,best_c = 0 ; 875bool ok = true; 876for (int round = 0 ;round < kRounds && ok ;++ round ) { 877for (int mode = 0 ;mode < 2 && ok ;++ mode ) {// 0: direct, 1: cached 878 std::vector < uint64_t > offs ; 879if (!pick (offs )) {ok = false;break ; } 880 std::atomic < size_t > next {0 }; 881 std::atomic < uint64_t > bytes {0 }; 882 std::atomic < int > failed {0 }; 883const auto t0 = std::chrono::steady_clock::now (); 884const auto deadline = t0 + std::chrono::milliseconds (1500 ); 885 std::vector < std::thread > th ; 886const int nthreads = mode == 0 ?kDirectThreads :kCachedThreads ; 887for (int t = 0 ;t < nthreads ;++ t ) { 888th .emplace_back ([& ] { 889void * buf = nullptr ; 890if (mode == 0 && posix_memalign (& buf ,4096 ,kRegion )!= 0 ) {failed = 1 ;return ; } 891volatile uint8_t sink = 0 ; 892for (;;) { 893const size_t i = next .fetch_add (1 ); 894if (i >=offs .size ()|| std::chrono::steady_clock::now ()> deadline )break ; 895if (mode == 0 ) { 896if (!preadn ((uint8_t * )buf ,offs [i ])) {failed = 1 ;break ; } 897 }else { 898for (uint64_t pg = 0 ;pg < kRegion ;pg += 4096 )sink = (uint8_t ) (sink + base [offs [i ]+ pg ]); 899 } 900bytes .fetch_add (kRegion ); 901 } 902 std::free (buf ); 903 }); 904 } 905for (std::thread & x :th )x .join (); 906const double secs = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 907if (failed .load ()!= 0 || bytes .load ()== 0 || secs <=0 ) {ok = false;break ; } 908const double bps = (double )bytes .load () /secs ; 909 (mode == 0 ?best_d :best_c )= std::max (mode == 0 ?best_d :best_c ,bps ); 910for (uint64_t off :offs ) {// leave the page cache as it was 911 (void )madvise ((void * ) (base + off ), (size_t )kRegion ,MADV_DONTNEED ); 912 (void )posix_fadvise (fd_b , (off_t )off , (off_t )kRegion ,POSIX_FADV_DONTNEED ); 913 } 914 } 915 } 916cleanup (); 917memo .ok = ok && best_d > 0 && best_c > 0 ; 918memo .direct_bps = best_d ; 919memo .cached_bps = best_c ; 920direct_bps = best_d ; 921cached_bps = best_c ; 922return memo .ok ; 923} 924#endif 925 926/// #286/#577: whether the file tier reads its `read_bytes` unbuffered, beside `arena_bytes` of RAM copy still to be 927/// taken. Windows times probe reads too (experts_unbuffered); on Linux the same rule as its `cache_counts = false` 928/// arm decides: whether the file cache could keep those bytes at all, from MemAvailable and the tightest cgroup 929/// limit (host_available_memory). STRATA_UNBUFFERED_LOAD=1 / 0 forces it either way, as on Windows. 930bool file_tier_unbuffered (const std::vector < std::string >& paths ,uint64_t arena_bytes ,uint64_t read_bytes , 931 std::string & why ) { 932#if defined(_WIN32 ) 933return experts_unbuffered (paths ,arena_bytes ,why ,/*cache_counts=*/ false,read_bytes ); 934#elif defined(__linux__ ) 935 (void )paths ; 936if (const char * env = std::getenv ("STRATA_UNBUFFERED_LOAD" );env != nullptr && env [0 ]!= '\0' ) { 937why = std::string ("STRATA_UNBUFFERED_LOAD=" )+ env ; 938return env [0 ]!= '0' ; 939 } 940uint64_t avail = 0 ; 941if (!available_memory_bytes (avail )) { 942why = "the available RAM is unknown" ; 943return false; 944 } 945// The room the file cache can really have (on by default; STRATA_FILE_TIER_HONEST=0 turns it off; an I/O-path change only). available_memory_bytes credits the group's whole `file` 946// counter as reclaimable (cgroup_available_bytes), and on a RAM-budget config that credit includes pages the engine itself holds 947// (P2003, v31, 22 GiB RAM copy: the room read 18.7 GiB while the group had limit 36 GiB, current 24.8 GiB, i.e. 11 GiB left). The re-check 948// after the copy then saw held >= 0.5, skipped the drive probe and switched the file tier to the cache: 2-3x slower prompts. The 949// conversation cache's sampler (only the clean inactive file cache is credited) is the honest figure; the smaller of the two decides. 950// The operator cap (--memory-limit-mib) is NOT applied: it bounds the engine's own allocations, not the page cache (counting it sent IQ3_S 951// unbuffered and cut its decode 2-3x). 952if (const char * ho = std::getenv ("STRATA_FILE_TIER_HONEST" );ho == nullptr || ho [0 ]!= '0' ) { 953if (const auto honest = strata::core::sample_host_memory (strata::core::MemoryProbePaths {},0 );honest && honest -> available < avail )avail = honest -> available ; 954 } 955// #1194: the experts read from the files are a skewed set: a cache holding a twentieth of them (at least 1.5 GiB) 956// serves most of the repeats, and beat the unbuffered reads at every room measured (it reads 2 to 7 times less from 957// the drive). `avail` already has what this process and the cgroup hold taken off, so 1 GiB is left for the rest. 958// #1752 (KevinX8): ROCm queues are suspended while the kernel reclaims around the process's HMM-tracked arena 959// (#1691) on an MI50 (gfx906): the cached reads churn the page cache and reclaim unmaps the arena, so the gfx906 960// backend keeps the old room >= read_bytes rule. Other HIP cards (gfx1201 measured: not affected) keep the new 961// rule; STRATA_FILE_CACHE_OLD_RULE=1 / 0 forces the old rule on / off on any Linux build. 962bool old_rule = false; 963#if defined(STRATA_HIP_GFX906 ) 964old_rule = true; 965#endif 966if (const char * r = std::getenv ("STRATA_FILE_CACHE_OLD_RULE" );r != nullptr && r [0 ]!= '\0' )old_rule = r [0 ]!= '0' ; 967const bool keepable = old_rule 968 ? strata::platform::file_cache_keeps (avail ,arena_bytes ,read_bytes ) 969 : strata::platform::file_cache_keeps (avail ,arena_bytes ,read_bytes ,1ull <<30 ,0.05 ,3ull <<29 ); 970char msg [256 ]; 971 std::snprintf (msg ,sizeof msg ,"%.1f GiB available, %.1f GiB of it still to be taken by the RAM copy, %.1f GiB " 972"of experts read from the files: the file cache %s keep the ones that come back" , 973 (double )avail / (1ull <<30 ), (double )arena_bytes / (1ull <<30 ), (double )read_bytes / (1ull <<30 ), 974keepable ?"can" :"cannot" ); 975why = msg ; 976// #3237: the room rule says the cache can keep the experts that come back, but when it holds under half of the read 977// set, whether it pays depends on the drive: on a PCIe 5 NVMe (8 GB/s direct) the cached path read prompts at half 978// the speed and decoded 3-4x slower than unbuffered reads, on a 1.7-2.5 GB/s NVMe the cache decodes faster. So time 979// both paths once at start and read unbuffered only when the drive is fast and serves direct reads clearly faster 980// (platform::file_tier_prefers_direct). STRATA_FILE_TIER_PROBE=0 keeps the room rule alone. 981if (keepable && !old_rule && read_bytes > 0 ) { 982const char * pe = std::getenv ("STRATA_FILE_TIER_PROBE" ); 983const uint64_t margin = 1ull <<30 ; 984const double room = avail > arena_bytes + margin ? (double ) (avail - arena_bytes - margin ) :0.0 ; 985const double held = room / (double )read_bytes ; 986if (!(pe != nullptr && pe [0 ]== '0' )&& held < 0.5 ) { 987double d = 0 ,c = 0 ; 988char pm [256 ]; 989if (file_tier_probe (paths ,d ,c )) { 990const bool direct = strata::platform::file_tier_prefers_direct (held ,d ,c ); 991 std::snprintf (pm ,sizeof pm ,"; the cache holds %.0f%% of the read set, direct reads %.2f GB/s, cached-path reads " 992"%.2f GB/s (%.2fx): %s" ,held * 100.0 ,d /1e9 ,c /1e9 ,d /c , 993direct ?"the file tier reads unbuffered" :"the file cache stays" ); 994why += pm ; 995return direct ; 996 } 997why += "; the drive probe could not run, the file cache stays" ; 998 } 999 } 1000return !keepable ; 1001#else 1002 (void )paths ; (void )arena_bytes ; (void )read_bytes ; 1003why = "through the file cache (no unbuffered reads on this platform)" ; 1004return false; 1005#endif 1006} 1007 1008}// namespace 1009 1010// ================================ THE FILE-BACKED SOURCE ================================ 1011 1012FileExpertSource ::~FileExpertSource () {close (); } 1013 1014#if defined(__linux__ ) 1015namespace { 1016/// Bytes of [p, p + n) whose pages are in the page cache (mincore, page-granular); 0 when the call fails. 1017uint64_t resident_in (const uint8_t * p ,uint64_t n ) { 1018if (n == 0 )return 0 ; 1019static thread_local std::vector < unsigned char > vec ; 1020const uintptr_t a = (uintptr_t )p & ~(uintptr_t )4095 ,e = ((uintptr_t )p + (uintptr_t )n + 4095 )& ~(uintptr_t )4095 ; 1021vec .resize ((size_t ) ((e - a ) /4096 )); 1022if (mincore ((void * )a , (size_t ) (e - a ),vec .data ())!= 0 )return 0 ; 1023uint64_t pages = 0 ; 1024for (unsigned char c :vec )pages += c & 1 ; 1025return std::min < uint64_t > (n ,pages * 4096 ); 1026} 1027/// A cheap residency probe: the first, last and two inner pages; the bytes of the range when all four are cached, else 0. 1028uint64_t resident_sampled (const uint8_t * p ,uint64_t n ) { 1029if (n == 0 )return 0 ; 1030const uintptr_t a = (uintptr_t )p & ~(uintptr_t )4095 ,e = ((uintptr_t )p + (uintptr_t )n - 1 )& ~(uintptr_t )4095 ; 1031const uintptr_t pages = (e - a ) /4096 ; 1032const uintptr_t at [4 ]= {a ,a + (pages /3 )* 4096 ,a + (pages * 2 /3 )* 4096 ,e }; 1033for (uintptr_t x :at ) { 1034unsigned char v = 0 ; 1035if (mincore ((void * )x ,4096 ,& v )!= 0 || (v & 1 )== 0 )return 0 ; 1036 } 1037return n ; 1038} 1039bool resident_sampled_n (const uint8_t * p ,uint64_t n ) {return resident_sampled (p ,n ) >=n ; } 1040/// The whole range with pread (a short read continues); false on an error or an end of file. 1041bool pread_full (int fd ,uint8_t * dst ,uint64_t n ,uint64_t off ) { 1042uint64_t done = 0 ; 1043while (done < n ) { 1044const ssize_t r = ::pread (fd ,dst + done , (size_t ) (n - done ), (off_t ) (off + done )); 1045if (r < 0 ) {if (errno == EINTR )continue ;return false; } 1046if (r == 0 )return false; 1047done += (uint64_t )r ; 1048 } 1049return true; 1050} 1051}// namespace 1052#endif 1053 1054int FileExpertSource ::spans (int64_t layer ,int64_t expert ,Span * out )const { 1055if (layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return 0 ; 1056if (!role_ptr_ .empty ()) { 1057if (unmapped_ )return 0 ;// the GGUF views are closed (drop_mapping) 1058uint64_t at = 0 ; 1059for (int r = 0 ;r < 3 ;++ r ) { 1060const size_t i = (size_t ) (3 * layer + r ); 1061const uint64_t per = role_bytes_ [i ]; 1062const uint8_t * p = role_ptr_ [i ]+ (size_t ) ((uint64_t )expert * per ); 1063const size_t f = (size_t )role_file_ [i ]; 1064out [r ]= {p ,per ,f < io_fds_ .size () ?io_fds_ [f ] :-1 , (uint64_t ) (p - maps_ [f ].base ),at }; 1065at += per ; 1066 } 1067return 3 ; 1068 } 1069const uint8_t * b = mapped_blob (layer ,expert ); 1070if (b == nullptr )return 0 ; 1071out [0 ]= {b ,layer_blob_bytes_ [(size_t )layer ],io_fds_ .empty () ?-1 :io_fds_ [0 ], (uint64_t ) (b - base_ ),0 }; 1072return 1 ; 1073} 1074 1075uint64_t FileExpertSource ::cached_bytes (int64_t layer ,int64_t expert ,uint64_t & total ,bool exact )const { 1076total = 0 ; 1077#if defined(__linux__ ) 1078Span sp [3 ]; 1079const int ns = spans (layer ,expert ,sp ); 1080uint64_t res = 0 ; 1081for (int i = 0 ;i < ns ;++ i ) { 1082total += sp [i ].n ; 1083res += exact ?resident_in (sp [i ].p ,sp [i ].n ) :resident_sampled (sp [i ].p ,sp [i ].n ); 1084 } 1085return res ; 1086#else 1087 (void )layer ; (void )expert ; 1088return 0 ; 1089#endif 1090} 1091 1092FileExpertSource ::IoCounters FileExpertSource ::io_counters ()const { 1093IoCounters c ; 1094c .cached_bytes = io_cached_ .load (std::memory_order_relaxed ); 1095c .uncached_bytes = io_uncached_ .load (std::memory_order_relaxed ); 1096c .pread_bytes = io_pread_bytes_ .load (std::memory_order_relaxed ); 1097c .pread_us = io_pread_us_ .load (std::memory_order_relaxed ); 1098c .pread_n = io_pread_n_ .load (std::memory_order_relaxed ); 1099c .pf_jobs = io_pf_jobs_ .load (std::memory_order_relaxed ); 1100c .pf_demand = io_pf_demand_ .load (std::memory_order_relaxed ); 1101c .pf_read_blobs = io_pf_blobs_ .load (std::memory_order_relaxed ); 1102c .pf_resident_skips = io_pf_skips_ .load (std::memory_order_relaxed ); 1103c .pf_dropped = io_pf_dropped_ .load (std::memory_order_relaxed ); 1104c .pf_used = io_pf_used_ .load (std::memory_order_relaxed ); 1105c .pf_unused = io_pf_unused_ .load (std::memory_order_relaxed ); 1106c .crit_us = io_crit_us_ .load (std::memory_order_relaxed ); 1107c .crit_n = io_crit_n_ .load (std::memory_order_relaxed ); 1108c .pf_bytes = io_pf_bytes_ .load (std::memory_order_relaxed ); 1109c .pf_used_bytes = io_pf_used_bytes_ .load (std::memory_order_relaxed ); 1110c .pf_late = io_pf_late_ .load (std::memory_order_relaxed ); 1111c .pf_rej_conf = io_pf_rej_conf_ .load (std::memory_order_relaxed ); 1112c .pf_rej_budget = io_pf_rej_budget_ .load (std::memory_order_relaxed ); 1113if (io_sched_ ) { 1114 std::lock_guard < std::mutex > lk (const_cast < std::mutex &> (io_mu_ )); 1115c .pf_budget_bytes = io_budget_now (); 1116 } 1117return c ; 1118} 1119 1120// 149-prefetch: the speculative bytes a decode window may read ahead. Fixed (STRATA_IO_PF_BUDGET_MB), or what the workers 1121// measured they can read in one window (one worker's rate x the workers x the window's time) times STRATA_IO_PF_BUDGET_FRAC; 1122// 256 MB until both rates are known. 1123uint64_t FileExpertSource ::io_budget_now ()const { 1124if (io_budget_fixed_ > 0 )return io_budget_fixed_ ; 1125if (io_bw_ <=0.0 || io_win_us_ <=0.0 )return 256ull <<20 ; 1126const double b = io_bw_ * (double ) std::max (1 ,io_threads_ )* io_win_us_ * io_budget_frac_ * io_scale_ ; 1127return (uint64_t ) std::max (16.0 * 1048576.0 ,b ); 1128} 1129 1130void FileExpertSource ::io_window_tick () { 1131const auto now = std::chrono::steady_clock::now (); 1132 std::lock_guard < std::mutex > lk (io_mu_ ); 1133if (io_win_t0_ .time_since_epoch ().count ()!= 0 ) { 1134const double us = std::chrono::duration < double , std::micro > (now - io_win_t0_ ).count (); 1135io_win_us_ = io_win_us_ <=0.0 ?us :0.8 * io_win_us_ + 0.2 * us ; 1136 } 1137io_win_t0_ = now ; 1138io_win_bytes_ = 0 ; 1139// feedback: the share of the read-ahead bytes that a layer then used (the used count lags the reads by a window or 1140// so; an EWMA over windows evens that out). Below STRATA_IO_PF_TARGET the budget shrinks (x0.7 a window, to 1/20), 1141// above it it grows back (x1.1, to 1): a box whose page cache cannot hold what is read ahead stops paying for it. 1142const uint64_t pf = io_pf_bytes_ .load (std::memory_order_relaxed ),used = io_pf_used_bytes_ .load (std::memory_order_relaxed ); 1143const uint64_t dpf = pf - io_prev_pf_ ,du = used - io_prev_used_ ; 1144io_prev_pf_ = pf ; 1145io_prev_used_ = used ; 1146if (io_target_ > 0.0 && dpf > 0 ) { 1147const double u = std::min (1.0 , (double )du / (double )dpf ); 1148io_useful_ = io_useful_ < 0.0 ?u :0.8 * io_useful_ + 0.2 * u ; 1149io_scale_ = io_useful_ < io_target_ ? std::max (0.05 ,io_scale_ * 0.7 ) : std::min (1.0 ,io_scale_ * 1.1 ); 1150 } 1151} 1152 1153// 149-prefetch: admit the predicted experts that are not resident. An expert's bar is the base confidence, raised with 1154// the queue's fill against the window budget (a busy drive takes only the surer guesses); the window's speculative bytes 1155// stay within the budget; each job carries the layer clock by which it must have started (else the worker drops it). 1156void FileExpertSource ::warm_scored (int64_t layer ,const int64_t * experts ,const float * conf ,int64_t n ,int ahead ) { 1157if (!io_sched_ || !io_pf_ || !direct_ .empty ()|| !io_ahead_ || !gate_open ()) {warm (layer ,experts ,n );return ; } 1158if (n <=0 || layer < 0 || layer >=n_layers_ )return ; 1159const uint64_t bytes = layer_blob_bytes_ [(size_t )layer ]; 1160const uint64_t deadline = io_epoch_ .load (std::memory_order_relaxed )+ (uint64_t ) std::max (1 ,ahead ); 1161bool any = false; 1162 { 1163 std::lock_guard < std::mutex > lk (io_mu_ ); 1164const uint64_t budget = io_budget_now (); 1165for (int64_t j = 0 ;j < n ;++ j ) { 1166const int64_t e = experts [j ]; 1167if (e < 0 || e >=n_expert_ )continue ; 1168const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )e ; 1169if (complement_ready_ && resident_blob (index )!= nullptr )continue ;// in the RAM copy 1170warm_count_ .fetch_add (1 , std::memory_order_relaxed ); 1171const double pressure = std::min (1.0 , (double )io_q_bytes_ / (double ) std::max < uint64_t > (1 ,budget )); 1172const double bar = (double )io_minconf_ + (1.0 - (double )io_minconf_ )* pressure ; 1173const float c = conf != nullptr ?conf [j ] :1.0f ; 1174if ((double )c < bar ) {io_pf_rej_conf_ .fetch_add (1 , std::memory_order_relaxed );continue ; } 1175if (io_win_bytes_ + bytes > budget ) {io_pf_rej_budget_ .fetch_add (1 , std::memory_order_relaxed );continue ; } 1176bool dup = false; 1177for (const IoJob & q :io_jobs_ ) 1178if (q .layer == (int32_t )layer && q .expert == (int32_t )e ) {dup = true;break ; } 1179if (dup )continue ; 1180io_jobs_ .push_back ({(int32_t )layer , (int32_t )e ,c ,deadline ,bytes }); 1181io_q_bytes_ += bytes ; 1182io_win_bytes_ += bytes ; 1183any = true; 1184 } 1185 } 1186if (any )io_cv_ .notify_all (); 1187} 1188 1189void FileExpertSource ::set_io_prefetch (bool on ,int threads ) { 1190io_stop (); 1191gate_on_ = false;// the decode gate comes and goes with io prefetch 1192#if defined(__linux__ ) 1193if (!on )return ; 1194if (base_ == nullptr || paths_ .empty ()|| !direct_ .empty ())return ;// unbuffered readers batch their own reads 1195 std::vector < int > fds ; 1196for (const std::string & path :paths_ ) { 1197const int fd = ::open (path .c_str (),O_RDONLY |O_CLOEXEC ); 1198if (fd < 0 ) { 1199for (int f :fds ) ::close (f ); 1200return ; 1201 } 1202 (void )posix_fadvise (fd ,0 ,0 ,POSIX_FADV_RANDOM );// read exactly the range asked for, no read-ahead beyond it 1203fds .push_back (fd ); 1204 } 1205io_fds_ = std::move (fds ); 1206 { 1207 std::lock_guard < std::mutex > lk (stage_mu_ ); 1208for (uint64_t b :layer_blob_bytes_ )stage_blob_ = std::max (stage_blob_ ,b ); 1209 } 1210if (!warm_stamp_ )warm_stamp_ .reset (new std::atomic < uint32_t > [(size_t ) (n_layers_ * n_expert_ )]()); 1211io_threads_ = threads > 0 ?threads :8 ; 1212if (const char * v = std::getenv ("STRATA_IO_PF_AHEAD" ))io_ahead_ = std::atoi (v )!= 0 ; 1213 {// experts.bin: fill the page cache from the workers and let the kernels read the mapping (STRATA_IO_PF_STAGE=1: stage) 1214const char * v = std::getenv ("STRATA_IO_PF_STAGE" ); 1215io_fill_ = role_ptr_ .empty ()&& !(v != nullptr && std::atoi (v )!= 0 ); 1216 } 1217io_pf_ = true; 1218io_stats_ = true; 1219io_quit_ = false; 1220 {// 149-prefetch: STRATA_IO_PF_SCHED=1 - deadlines, confidence admission and a per-window byte budget (off: as before) 1221const char * v = std::getenv ("STRATA_IO_PF_SCHED" ); 1222io_sched_ = v != nullptr && std::atoi (v )!= 0 ; 1223if (const char * m = std::getenv ("STRATA_IO_PF_MINCONF" ))io_minconf_ = (float ) std::clamp (std::atof (m ),0.0 ,1.0 ); 1224if (const char * m = std::getenv ("STRATA_IO_PF_BUDGET_MB" ))io_budget_fixed_ = (uint64_t ) std::max (0.0 , std::atof (m )* 1048576.0 ); 1225if (const char * m = std::getenv ("STRATA_IO_PF_BUDGET_FRAC" ))io_budget_frac_ = std::clamp (std::atof (m ),0.01 ,4.0 ); 1226if (const char * m = std::getenv ("STRATA_IO_PF_TARGET" ))io_target_ = std::clamp (std::atof (m ),0.0 ,1.0 ); 1227gate_on_ = true;// 0.2.0: the decode gate comes with io prefetch; STRATA_IO_PF_GATE=0 turns it off 1228if (const char * m = std::getenv ("STRATA_IO_PF_GATE" );m != nullptr && m [0 ]!= '\0' )gate_on_ = std::atoi (m )!= 0 ; 1229if (const char * m = std::getenv ("STRATA_IO_PF_GATE_LO" ))gate_lo_ = std::clamp (std::atof (m ),0.0 ,1.0 ); 1230if (const char * m = std::getenv ("STRATA_IO_PF_GATE_HI" ))gate_hi_ = std::clamp (std::atof (m ),gate_lo_ ,1.0 ); 1231if (const char * m = std::getenv ("STRATA_IO_PF_GATE_USEFUL" ))gate_min_useful_ = std::clamp (std::atof (m ),0.0 ,1.0 ); 1232 } 1233if (!pf_mark_ ) { 1234pf_mark_ .reset (new std::atomic < uint8_t > [(size_t ) (n_layers_ * n_expert_ )]); 1235for (int64_t i = 0 ;i < n_layers_ * n_expert_ ;++ i )pf_mark_ [(size_t )i ].store (0 , std::memory_order_relaxed ); 1236 } 1237for (int i = 0 ;i < io_threads_ ;++ i )io_workers_ .emplace_back ([this ] {io_worker (); }); 1238#else 1239 (void )on ; (void )threads ; 1240#endif 1241} 1242 1243void FileExpertSource ::io_stop () { 1244 { 1245 std::lock_guard < std::mutex > lk (io_mu_ ); 1246io_quit_ = true; 1247io_q_ .clear (); 1248io_jobs_ .clear (); 1249io_q_bytes_ = 0 ; 1250 } 1251io_cv_ .notify_all (); 1252for (std::thread & t :io_workers_ ) 1253if (t .joinable ())t .join (); 1254io_workers_ .clear (); 1255#if defined(__linux__ ) 1256for (int f :io_fds_ ) ::close (f ); 1257#endif 1258io_fds_ .clear (); 1259io_pf_ = false; 1260io_quit_ = false; 1261} 1262 1263void FileExpertSource ::io_enqueue (int64_t layer ,int64_t expert ,bool ahead ) { 1264 { 1265 std::lock_guard < std::mutex > lk (io_mu_ ); 1266if (io_q_ .size () >=512 ) {// the predictions run ahead of the reads: the oldest are the stalest 1267io_q_ .pop_front (); 1268io_pf_dropped_ .fetch_add (1 , std::memory_order_relaxed ); 1269 } 1270io_q_ .emplace_back ((int32_t )layer , (int32_t )expert | (ahead ?kIoAhead :0 )); 1271 } 1272io_cv_ .notify_one (); 1273} 1274 1275// A read-ahead worker: takes a predicted (layer, expert), skips it when its pages are cached or it is already 1276// staged, and otherwise reads the whole blob into a staging buffer (copy_from_files preads what is not cached). 1277void FileExpertSource ::io_worker () { 1278 strata::platform::name_this_thread ("strata-io" ); 1279for (;;) { 1280int32_t layer ,expert ; 1281bool ahead = true;// a prediction (marked for the used / unused count), not a layer's own demand read 1282 { 1283 std::unique_lock < std::mutex > lk (io_mu_ ); 1284io_cv_ .wait (lk , [& ] {return io_quit_ || !io_q_ .empty ()|| !io_jobs_ .empty (); }); 1285if (io_quit_ )return ; 1286if (io_sched_ && io_q_ .empty ()&& !io_jobs_ .empty ()) {// (the layers' own reads in io_q_ go first) 1287// 149-prefetch: drop the jobs whose layer the decode has reached (its demand read covers them); then the 1288// earliest deadline, the surest guess first among equals 1289const uint64_t now = io_epoch_ .load (std::memory_order_relaxed ); 1290size_t best = io_jobs_ .size (); 1291for (size_t i = 0 ;i < io_jobs_ .size ();) { 1292if (io_jobs_ [i ].deadline <=now ) { 1293io_q_bytes_ -= std::min (io_q_bytes_ ,io_jobs_ [i ].bytes ); 1294io_jobs_ [i ]= io_jobs_ .back (); 1295io_jobs_ .pop_back (); 1296io_pf_late_ .fetch_add (1 , std::memory_order_relaxed ); 1297continue ; 1298 } 1299++ i ; 1300 } 1301best = io_jobs_ .size (); 1302for (size_t i = 0 ;i < io_jobs_ .size ();++ i ) 1303if (best == io_jobs_ .size ()|| io_jobs_ [i ].deadline < io_jobs_ [best ].deadline || 1304 (io_jobs_ [i ].deadline == io_jobs_ [best ].deadline && io_jobs_ [i ].conf > io_jobs_ [best ].conf )) 1305best = i ; 1306if (best == io_jobs_ .size ())continue ;// all were late 1307layer = io_jobs_ [best ].layer ; 1308expert = io_jobs_ [best ].expert ; 1309io_q_bytes_ -= std::min (io_q_bytes_ ,io_jobs_ [best ].bytes ); 1310io_jobs_ [best ]= io_jobs_ .back (); 1311io_jobs_ .pop_back (); 1312 }else { 1313if (io_q_ .empty ())continue ; 1314layer = io_q_ .back ().first ;// the newest prediction first: it is the layer that comes next 1315expert = io_q_ .back ().second & ~kIoAhead ; 1316ahead = (io_q_ .back ().second & kIoAhead )!= 0 ; 1317io_q_ .pop_back (); 1318 } 1319 } 1320io_pf_jobs_ .fetch_add (1 , std::memory_order_relaxed ); 1321const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 1322if (complement_ready_ && resident_blob (index )!= nullptr )continue ; 1323if (!override_ .empty ()&& override_ [index ]!= nullptr )continue ; 1324const auto tjob = std::chrono::steady_clock::now (); 1325// 149-prefetch: one worker's read rate (bytes per microsecond), for the scheduler's window budget 1326auto note_rate = [& ](uint64_t b ) { 1327if (b == 0 )return ; 1328const double us = std::max (1.0 , std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- tjob ).count ()); 1329io_pf_bytes_ .fetch_add (b , std::memory_order_relaxed ); 1330 std::lock_guard < std::mutex > lk (io_mu_ ); 1331const double r = (double )b /us ; 1332io_bw_ = io_bw_ <=0.0 ?r :0.9 * io_bw_ + 0.1 * r ; 1333 }; 1334if (io_fill_ ) {// read what is not cached into a scratch buffer: the pages stay in the page cache for the kernels 1335#if defined(__linux__ ) 1336static thread_local std::vector < uint8_t > scratch ; 1337Span sp [3 ]; 1338const int ns = spans (layer ,expert ,sp ); 1339bool any = false; 1340uint64_t got = 0 ; 1341for (int i = 0 ;i < ns ;++ i ) { 1342if (sp [i ].fd < 0 || resident_sampled_n (sp [i ].p ,sp [i ].n ))continue ; 1343if (scratch .size ()< sp [i ].n )scratch .resize ((size_t )sp [i ].n ); 1344const auto t0 = std::chrono::steady_clock::now (); 1345if (pread_full (sp [i ].fd ,scratch .data (),sp [i ].n ,sp [i ].off )) { 1346io_pread_bytes_ .fetch_add (sp [i ].n , std::memory_order_relaxed ); 1347io_pread_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 1348 std::memory_order_relaxed ); 1349io_pread_n_ .fetch_add (1 , std::memory_order_relaxed ); 1350any = true; 1351got += sp [i ].n ; 1352 } 1353 } 1354if (any ) { 1355io_pf_blobs_ .fetch_add (1 , std::memory_order_relaxed ); 1356if (pf_mark_ && ahead )pf_mark_ [index ].store (1 , std::memory_order_relaxed );// read ahead: scored at the demand 1357note_rate (got ); 1358 } 1359else io_pf_skips_ .fetch_add (1 , std::memory_order_relaxed ); 1360#endif 1361continue ; 1362 } 1363uint64_t total = 0 ; 1364if (cached_bytes (layer ,expert ,total , false) >=total ) { 1365io_pf_skips_ .fetch_add (1 , std::memory_order_relaxed ); 1366continue ; 1367 } 1368size_t v = 0 ; 1369bool fill = false; 1370uint8_t * dst = nullptr ; 1371 { 1372 std::lock_guard < std::mutex > lk (stage_mu_ ); 1373if (stage_blob_ == 0 )continue ; 1374const bool have = claim_stage ((int64_t )layer * n_expert_ + expert ,v ,fill ,/*ahead=*/ true); 1375if (have || !fill )continue ;// already staged or being read, or no buffer 1376stage_pf_ [v ]= 1 ; 1377dst = stage_buf_ [v ].get (); 1378 } 1379const bool ok = copy_from_files (layer ,expert ,dst ); 1380io_pf_blobs_ .fetch_add (1 , std::memory_order_relaxed ); 1381if (ok )file_read_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 1382if (ok )note_rate (layer_blob_bytes_ [(size_t )layer ]); 1383 { 1384 std::lock_guard < std::mutex > lk (stage_mu_ ); 1385stage_busy_ [v ]= 0 ; 1386if (!ok ) { 1387stage_of_ .erase (stage_key_ [v ]); 1388stage_key_ [v ]= -1 ; 1389stage_pf_ [v ]= 0 ; 1390 } 1391 } 1392stage_cv_ .notify_all (); 1393 } 1394} 1395 1396// The decode's hand-out of a blob in the experts.bin file tier with io prefetch on: what a layer's prediction read 1397// ahead is staged; a blob whose pages are all cached is the mapping itself (no copy); the rest is read with one 1398// pread into a staging buffer, not faulted in by the kernels one small request at a time. 1399const uint8_t * FileExpertSource ::io_blob (int64_t layer ,int64_t expert ) { 1400const int64_t key = layer * n_expert_ + expert ; 1401if (io_fill_ ) { 1402const uint8_t * b = mapped_blob (layer ,expert ); 1403if (b != nullptr ) { 1404const uint64_t total = layer_blob_bytes_ [(size_t )layer ]; 1405file_read_bytes_ .fetch_add (total , std::memory_order_relaxed ); 1406 } 1407return b ; 1408 } 1409bool have ; 1410 { 1411 std::lock_guard < std::mutex > lk (stage_mu_ ); 1412have = stage_of_ .find (key )!= stage_of_ .end (); 1413 } 1414if (!have ) { 1415// prefetch() (every decode layer calls it first) staged what was not cached: what is not staged is cached 1416const uint8_t * b = mapped_blob (layer ,expert ); 1417if (b != nullptr ) { 1418const uint64_t total = layer_blob_bytes_ [(size_t )layer ]; 1419io_cached_ .fetch_add (total , std::memory_order_relaxed ); 1420file_read_bytes_ .fetch_add (total , std::memory_order_relaxed ); 1421return b ; 1422 } 1423 } 1424return staged_blob (layer ,expert ); 1425} 1426 1427bool FileExpertSource ::open (const std::string & pack_dir ,int64_t n_layers ,int64_t n_expert , std::string & err ) { 1428close (); 1429if (n_layers <=0 || n_expert <=0 ) {err = "FileExpertSource: the geometry is empty" ;return false; } 1430const auto & layout = strata::kernels::cpu::expert_layout (); 1431if (layout .n_layers != n_layers || layout .n_expert != n_expert ) { 1432err = "FileExpertSource: the requested geometry does not match the loaded expert layout" ; 1433return false; 1434 } 1435if ((uint64_t )n_layers > (uint64_t ) std::numeric_limits < int64_t > ::max () / (uint64_t )n_expert ) { 1436err = "FileExpertSource: the expert count overflows" ; 1437return false; 1438 } 1439const uint64_t blob_count = (uint64_t )n_layers * (uint64_t )n_expert ; 1440if (blob_count > (uint64_t ) std::numeric_limits < int64_t > ::max ()|| 1441 (uint64_t )n_layers > (uint64_t ) std::numeric_limits < size_t > ::max ()) { 1442err = "FileExpertSource: the expert count overflows" ; 1443return false; 1444 } 1445 1446 std::vector < uint64_t > layer_offsets ((size_t )n_layers ),layer_blob_bytes ((size_t )n_layers ); 1447const uint64_t want = layout .total ; 1448if (want == 0 || want > (uint64_t ) std::numeric_limits < size_t > ::max ()) { 1449err = "FileExpertSource: the loaded expert layout has an invalid size" ; 1450return false; 1451 } 1452if (!layout .native ) { 1453if (blob_count > std::numeric_limits < uint64_t > ::max () / (uint64_t ) strata::kernels::cpu::BLOB ) { 1454err = "FileExpertSource: the canonical expert size overflows" ; 1455return false; 1456 } 1457const uint64_t canonical_size = blob_count * (uint64_t ) strata::kernels::cpu::BLOB ; 1458if (want != canonical_size ) { 1459err = "FileExpertSource: the canonical expert layout has an inconsistent size" ; 1460return false; 1461 } 1462const uint64_t bytes = (uint64_t ) strata::kernels::cpu::BLOB ; 1463const uint64_t layer_bytes = (uint64_t )n_expert * bytes ; 1464for (int64_t layer = 0 ;layer < n_layers ;++ layer ) { 1465layer_offsets [(size_t )layer ]= (uint64_t )layer * layer_bytes ; 1466layer_blob_bytes [(size_t )layer ]= bytes ; 1467 } 1468 }else { 1469if (layout .offset .size ()!= (size_t )n_layers || layout .bytes .size ()!= (size_t )n_layers || 1470layout .fmt .size ()!= (size_t )n_layers ) { 1471err = "FileExpertSource: the native expert layout is incomplete" ; 1472return false; 1473 } 1474uint64_t at = 0 ; 1475for (int64_t layer = 0 ;layer < n_layers ;++ layer ) { 1476const size_t i = (size_t )layer ; 1477const uint64_t bytes = (uint64_t )layout .fmt [i ].bytes ; 1478if (layout .offset [i ]!= at || bytes == 0 || layout .bytes [i ]!= bytes || 1479bytes > std::numeric_limits < uint64_t > ::max () / (uint64_t )n_expert ) { 1480err = "FileExpertSource: the native expert layout is invalid at layer " + std::to_string (layer ); 1481return false; 1482 } 1483const uint64_t layer_bytes = bytes * (uint64_t )n_expert ; 1484if (at > want || layer_bytes > want - at ) { 1485err = "FileExpertSource: the native expert layout exceeds its declared size at layer " + 1486 std::to_string (layer ); 1487return false; 1488 } 1489layer_offsets [i ]= layout .offset [i ]; 1490layer_blob_bytes [i ]= bytes ; 1491at += layer_bytes ; 1492 } 1493if (at != want ) { 1494err = "FileExpertSource: the native expert layout has an inconsistent size" ; 1495return false; 1496 } 1497 } 1498const std::string path = pack_dir + "/experts.bin" ; 1499if (layout .native && !gguf_ .empty ()&& !std::filesystem::exists (path )) { 1500// CS-T: no experts.bin - the model's GGUF shards, read in place 1501blobs_ = (int64_t )blob_count ; 1502n_layers_ = n_layers ; 1503n_expert_ = n_expert ; 1504layer_offsets_ = std::move (layer_offsets ); 1505layer_blob_bytes_ = std::move (layer_blob_bytes ); 1506if (!open_gguf (err )) {close ();return false; } 1507record_inputs (path ,gguf_ ,layout , true); 1508return true; 1509 } 1510 1511#if defined(_WIN32 ) 1512// UTF-8 -> UTF-16: the pack may live under a path with non-ASCII characters, and `CreateFileA` would 1513// silently mangle it into a file-not-found. 1514const int wide = MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,nullptr ,0 ); 1515 std::vector < wchar_t > wpath ((size_t ) (wide > 0 ?wide :1 )); 1516if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,wpath .data (),wide ); 1517// **`FILE_FLAG_RANDOM_ACCESS` WAS HERE AND IT COST 14x.** 1518// 1519// The design depends on the OS page cache holding the whole 34 GB expert set, because this machine has 1520// 64 GB of DDR5 and `L9` measured the CPU path at 44.14 GB/s from DRAM. `FILE_FLAG_RANDOM_ACCESS` tells 1521// the cache manager the opposite: it disables read-ahead AND it lets the manager drop the pages again 1522// quickly, on the assumption that a large randomly-accessed file will not be re-read. Measured, on 1523// `strata generate --max-new 24`: **1.93 GB/s** - disk speed, 344 ms/token, and it never warmed up over 25 1524// tokens, because the pages were being evicted as fast as they were faulted in. 1525// 1526// The correct flag is NO flag. The access pattern IS random (10 of 512 experts per layer, a different 10 1527// each layer), but every byte read is read again on the next token, so retention is the whole game. 1528HANDLE f = CreateFileW (wpath .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 1529FILE_ATTRIBUTE_NORMAL ,nullptr ); 1530if (f == INVALID_HANDLE_VALUE ) { 1531err = "FileExpertSource: cannot open " + path ; 1532return false; 1533 } 1534LARGE_INTEGER sz {}; 1535if (!GetFileSizeEx (f ,& sz )) { 1536CloseHandle (f ); 1537err = "FileExpertSource: cannot size " + path ; 1538return false; 1539 } 1540if ((uint64_t )sz .QuadPart != want ) { 1541char buf [400 ]; 1542 std::snprintf (buf ,sizeof buf , 1543"FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not " 1544"the pack this geometry came from" , 1545path .c_str (), (unsigned long long )sz .QuadPart , (unsigned long long )want ); 1546CloseHandle (f ); 1547err = buf ; 1548return false; 1549 } 1550HANDLE m = CreateFileMappingW (f ,nullptr ,PAGE_READONLY ,0 ,0 ,nullptr ); 1551if (m == nullptr ) { 1552CloseHandle (f ); 1553err = "FileExpertSource: CreateFileMapping failed on " + path ; 1554return false; 1555 } 1556void * view = MapViewOfFile (m ,FILE_MAP_READ ,0 ,0 ,0 ); 1557if (view == nullptr ) { 1558CloseHandle (m ); 1559CloseHandle (f ); 1560err = "FileExpertSource: MapViewOfFile failed on " + path ; 1561return false; 1562 } 1563file_ = f ; 1564mapping_ = m ; 1565base_ = (const uint8_t * )view ; 1566paths_ .assign (1 ,path ); 1567#else 1568const int fd = ::open (path .c_str (),O_RDONLY ); 1569if (fd < 0 ) {err = "FileExpertSource: cannot open " + path ;return false; } 1570struct stat st {}; 1571if (fstat (fd ,& st )!= 0 ) { ::close (fd );err = "FileExpertSource: cannot stat " + path ;return false; } 1572if (st .st_size < 0 || (uint64_t )st .st_size != want ) { 1573char buf [400 ]; 1574 std::snprintf (buf ,sizeof buf , 1575"FileExpertSource: %s is %llu B but the loaded expert layout requires %llu B - this is not " 1576"the pack this geometry came from" , 1577path .c_str (), (unsigned long long ) (st .st_size < 0 ?0 :st .st_size ), 1578 (unsigned long long )want ); 1579 ::close (fd ); 1580err = buf ; 1581return false; 1582 } 1583void * view = mmap (nullptr , (size_t )want ,PROT_READ ,MAP_SHARED ,fd ,0 ); 1584if (view == MAP_FAILED ) { ::close (fd );err = "FileExpertSource: mmap failed on " + path ;return false; } 1585fd_ = fd ; 1586base_ = (const uint8_t * )view ; 1587paths_ .assign (1 ,path );// #286: open_direct opens it again with O_DIRECT 1588#endif 1589blobs_ = (int64_t )blob_count ; 1590n_layers_ = n_layers ; 1591n_expert_ = n_expert ; 1592mapped_bytes_ = want ; 1593layer_offsets_ = std::move (layer_offsets ); 1594layer_blob_bytes_ = std::move (layer_blob_bytes ); 1595record_inputs (path ,gguf_ ,layout , false); 1596return true; 1597} 1598 1599void FileExpertSource ::close () { 1600prefetch_end (); 1601latent_io_stop (); 1602ram_stop (); 1603io_stop (); 1604inputs_ .clear (); 1605if (complement_arena_ != nullptr ) { 1606if (complement_pinned_ && !complement_registered_ ) (void )cudaFreeHost (complement_arena_ ); 1607else { 1608if (complement_registered_ ) (void )cudaHostUnregister (complement_arena_ ); 1609if (complement_locked_ > 0 ) 1610 strata::platform::unlock_resident ((uint8_t * )complement_arena_ + complement_lock_off_ ,complement_locked_ ); 1611 std::free (complement_arena_ ); 1612 } 1613 } 1614if (xstage_ != nullptr ) { 1615if (xstage_pinned_ ) (void )cudaFreeHost (xstage_ ); 1616else std::free (xstage_ ); 1617 } 1618xstage_ = nullptr ; 1619xstage_pinned_ = false; 1620xstage_cap_ = 0 ; 1621xstage_blob_ = 0 ; 1622override_ .clear (); 1623staged_ .clear (); 1624exchange_storage_ .clear (); 1625exchanges_ = 0 ; 1626file_reads_ .store (0 ); 1627complement_arena_ = nullptr ; 1628complement_host_ = nullptr ; 1629complement_device_ = nullptr ; 1630complement_bytes_ = 0 ; 1631complement_offsets_ .clear (); 1632complement_pinned_ = false; 1633complement_partial_ = false; 1634complement_registered_ = false; 1635complement_pin_limit_ = 0 ; 1636complement_lock_off_ = 0 ; 1637complement_ready_ = false; 1638complement_locked_ = 0 ; 1639complement_lent_slots_ = 0 ; 1640if (!maps_ .empty ()) { 1641for (Map & m :maps_ ) { 1642#if defined(_WIN32 ) 1643if (m .base != nullptr && !m .closed )UnmapViewOfFile ((LPCVOID )m .base ); 1644if (m .mapping != nullptr )CloseHandle ((HANDLE )m .mapping ); 1645if (m .file != nullptr )CloseHandle ((HANDLE )m .file ); 1646#else 1647if (m .base != nullptr && !m .closed )munmap ((void * )m .base , (size_t )m .bytes ); 1648if (m .fd >=0 ) ::close (m .fd ); 1649#endif 1650 } 1651maps_ .clear (); 1652base_ = nullptr ;// one of the views above 1653unmapped_ = false; 1654 } 1655role_ptr_ .clear (); 1656role_bytes_ .clear (); 1657role_file_ .clear (); 1658paths_ .clear (); 1659for (void * h :direct_ )close_direct (h ); 1660direct_ .clear (); 1661for (void * h :pdirect_ )close_direct (h ); 1662pdirect_ .clear (); 1663 { 1664 std::lock_guard < std::mutex > lk (stage_mu_ ); 1665// the buffers' last copies end before they are freed (#1237) 1666if (!stage_ev_ .empty ()) (void )cudaDeviceSynchronize (); 1667stage_free_events (); 1668stage_buf_ .clear (); 1669stage_key_ .clear (); 1670stage_epoch_ .clear (); 1671stage_used_ .clear (); 1672stage_busy_ .clear (); 1673stage_pf_ .clear (); 1674stage_of_ .clear (); 1675stage_blob_ = 0 ; 1676stage_seq_ = 0 ; 1677epoch_ = 0 ; 1678last_layer_ = -1 ; 1679stage_grew_ = false; 1680 } 1681ram_reads_ .store (0 ); 1682warm_stamp_ .reset (); 1683warm_hits_ .store (0 ); 1684warm_count_ .store (0 ); 1685file_read_bytes_ .store (0 ); 1686file_blob_bytes_ .store (0 ); 1687file_us_ .store (0 ); 1688io_cached_ .store (0 );io_uncached_ .store (0 );io_pread_bytes_ .store (0 );io_pread_us_ .store (0 );io_pread_n_ .store (0 ); 1689io_pf_jobs_ .store (0 );io_pf_blobs_ .store (0 );io_pf_skips_ .store (0 );io_pf_dropped_ .store (0 ); 1690io_pf_used_ .store (0 );io_pf_unused_ .store (0 );io_crit_us_ .store (0 );io_crit_n_ .store (0 ); 1691#if defined(_WIN32 ) 1692if (base_ != nullptr && !unmapped_ )UnmapViewOfFile ((LPCVOID )base_ ); 1693unmapped_ = false; 1694if (mapping_ != nullptr )CloseHandle ((HANDLE )mapping_ ); 1695if (file_ != nullptr )CloseHandle ((HANDLE )file_ ); 1696mapping_ = nullptr ; 1697file_ = nullptr ; 1698#else 1699if (base_ != nullptr )munmap ((void * )base_ , (size_t )mapped_bytes_ ); 1700if (fd_ >=0 ) ::close (fd_ ); 1701fd_ = -1 ; 1702#endif 1703base_ = nullptr ; 1704blobs_ = 0 ; 1705n_layers_ = 0 ; 1706n_expert_ = 0 ; 1707mapped_bytes_ = 0 ; 1708layer_offsets_ .clear (); 1709layer_blob_bytes_ .clear (); 1710reads_ = 0 ; 1711} 1712 1713 1714bool ExpertSource ::copy_blob (int64_t layer ,int64_t expert ,uint8_t * dst ) { 1715const uint8_t * b = blob (layer ,expert ); 1716if (b == nullptr || dst == nullptr )return false; 1717 std::memcpy (dst ,b , (size_t ) strata::kernels::cpu::expert_layout ().blob_bytes (layer )); 1718return true; 1719} 1720 1721bool ExpertSource ::copy_blobs (const int32_t * layers ,const int32_t * experts ,uint8_t * const * dst ,size_t n ) { 1722for (size_t i = 0 ;i < n ;++ i ) 1723if (!copy_blob (layers [i ],experts [i ],dst [i ]))return false; 1724return true; 1725} 1726 1727// ================================ CS-T: THE GGUF SHARDS IN PLACE ================================ 1728// 1729// A native pack without experts.bin: every file native_experts.txt names is mapped (MapViewOfFile / mmap, no 1730// flag - the same retention argument as experts.bin above), and an expert's blob [gate rows | up rows | down rows] 1731// is three slices of three tensors, possibly in two shards (UD-Q4_K_XL's layer 11). Nothing is read at open; a 1732// blob is assembled when it is asked for (`blob`, into a small pool of buffers) or copied where it is needed 1733// (`copy_blob`: the RAM copy, the prompt path's pinned stager buffers). 1734bool FileExpertSource ::open_gguf (std::string & err ) { 1735const auto & lay = strata::kernels::cpu::expert_layout (); 1736if (!check_experts_gguf (gguf_ ,lay ,err )) {err = "FileExpertSource: " + err ;return false; } 1737const size_t cut = gguf_ .find_last_of ("/\\" ); 1738const std::string dir = cut == std::string::npos ? std::string () :gguf_ .substr (0 ,cut + 1 ); 1739 std::map < std::string ,size_t > index ; 1740role_ptr_ .assign ((size_t ) (3 * n_layers_ ),nullptr ); 1741role_bytes_ .assign ((size_t ) (3 * n_layers_ ),0 ); 1742role_file_ .assign ((size_t ) (3 * n_layers_ ),0 ); 1743for (int64_t l = 0 ;l < n_layers_ ;++ l ) { 1744const auto & fm = lay .fmt [(size_t )l ]; 1745const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,lay .bytes [(size_t )l ]- fm .down_off }; 1746for (int r = 0 ;r < 3 ;++ r ) { 1747const size_t i = (size_t ) (3 * l + r ); 1748const std::string path = lay .gguf_file .size ()> i && !lay .gguf_file [i ].empty () ?dir + lay .gguf_file [i ] 1749 :gguf_ ; 1750auto it = index .find (path ); 1751if (it == index .end ()) { 1752Map m ; 1753#if defined(_WIN32 ) 1754const int wide = MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,nullptr ,0 ); 1755 std::vector < wchar_t > wpath ((size_t ) (wide > 0 ?wide :1 )); 1756if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,wpath .data (),wide ); 1757HANDLE f = CreateFileW (wpath .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 1758FILE_ATTRIBUTE_NORMAL ,nullptr ); 1759LARGE_INTEGER sz {}; 1760if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx (f ,& sz )) { 1761if (f != INVALID_HANDLE_VALUE )CloseHandle (f ); 1762err = "FileExpertSource: cannot open " + path ; 1763return false; 1764 } 1765HANDLE mh = CreateFileMappingW (f ,nullptr ,PAGE_READONLY ,0 ,0 ,nullptr ); 1766void * view = mh != nullptr ?MapViewOfFile (mh ,FILE_MAP_READ ,0 ,0 ,0 ) :nullptr ; 1767if (view == nullptr ) { 1768if (mh != nullptr )CloseHandle (mh ); 1769CloseHandle (f ); 1770err = "FileExpertSource: cannot map " + path ; 1771return false; 1772 } 1773m .file = f ; 1774m .mapping = mh ; 1775m .bytes = (uint64_t )sz .QuadPart ; 1776m .base = (const uint8_t * )view ; 1777#else 1778const int fd = ::open (path .c_str (),O_RDONLY ); 1779struct stat st {}; 1780if (fd < 0 || fstat (fd ,& st )!= 0 || st .st_size <=0 ) { 1781if (fd >=0 ) ::close (fd ); 1782err = "FileExpertSource: cannot open " + path ; 1783return false; 1784 } 1785void * view = mmap (nullptr , (size_t )st .st_size ,PROT_READ ,MAP_SHARED ,fd ,0 ); 1786if (view == MAP_FAILED ) { ::close (fd );err = "FileExpertSource: cannot map " + path ;return false; } 1787m .fd = fd ; 1788m .bytes = (uint64_t )st .st_size ; 1789m .base = (const uint8_t * )view ; 1790#endif 1791maps_ .push_back (m ); 1792paths_ .push_back (path ); 1793it = index .emplace (path ,maps_ .size ()- 1 ).first ; 1794 } 1795const Map & m = maps_ [it -> second ]; 1796role_file_ [i ]= (int )it -> second ; 1797const uint64_t at = lay .gguf_off [i ],bytes = per [r ]* (uint64_t )n_expert_ ; 1798if (at > m .bytes || bytes > m .bytes - at ) {// check_experts_gguf proved it; the mapping must agree 1799err = "FileExpertSource: an expert span runs past the end of " + path ; 1800return false; 1801 } 1802role_ptr_ [i ]= m .base + (size_t )at ; 1803role_bytes_ [i ]= per [r ]; 1804 } 1805 } 1806base_ = maps_ .front ().base ;// "opened"; mapped_blob answers nullptr in this mode 1807warm_stamp_ .reset (new std::atomic < uint32_t > [(size_t ) (n_layers_ * n_expert_ )]()); 1808for (uint64_t b :layer_blob_bytes_ )stage_blob_ = std::max (stage_blob_ ,b ); 1809return true; 1810} 1811 1812bool FileExpertSource ::copy_from_files (int64_t layer ,int64_t expert ,uint8_t * dst )const { 1813if (dst == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return false; 1814if (!direct_ .empty ()) {// #286: from the drive; a failed read falls back to the mapping below 1815const Fill f {0 ,layer ,expert ,dst }; 1816if (read_direct (& f ,1 ))return true; 1817direct_fallbacks_ .fetch_add (1 , std::memory_order_relaxed ); 1818 } 1819#if defined(__linux__ ) 1820if (io_pf_ || io_stats_ ) {// count what the page cache holds; with io prefetch, read what it does not with pread 1821Span sp [3 ]; 1822const int ns = spans (layer ,expert ,sp ); 1823for (int i = 0 ;i < ns ;++ i ) { 1824const uint64_t res = resident_in (sp [i ].p ,sp [i ].n ); 1825io_cached_ .fetch_add (res , std::memory_order_relaxed ); 1826io_uncached_ .fetch_add (sp [i ].n - res , std::memory_order_relaxed ); 1827const bool dec = in_decode (); 1828if (gate_on_ && dec ) { 1829gate_c_ .fetch_add (res , std::memory_order_relaxed ); 1830gate_u_ .fetch_add (sp [i ].n - res , std::memory_order_relaxed ); 1831 } 1832if (io_pf_ && res < sp [i ].n && sp [i ].fd >= 0 && !(dec && !gate_open ())) { 1833const auto t0 = std::chrono::steady_clock::now (); 1834const bool ok = pread_full (sp [i ].fd ,dst + sp [i ].at ,sp [i ].n ,sp [i ].off ); 1835io_pread_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 1836 std::memory_order_relaxed ); 1837io_pread_n_ .fetch_add (1 , std::memory_order_relaxed ); 1838if (ok ) { 1839io_pread_bytes_ .fetch_add (sp [i ].n , std::memory_order_relaxed ); 1840continue ; 1841 } 1842 } 1843 std::memcpy (dst + sp [i ].at ,sp [i ].p , (size_t )sp [i ].n ); 1844 } 1845if (ns > 0 )return true; 1846 } 1847#endif 1848if (!role_ptr_ .empty ()) { 1849if (unmapped_ )return false;// drop_mapping closed the GGUF views: only the unbuffered reads remain 1850uint64_t at = 0 ; 1851for (int r = 0 ;r < 3 ;++ r ) { 1852const size_t i = (size_t ) (3 * layer + r ); 1853const uint64_t per = role_bytes_ [i ]; 1854 std::memcpy (dst + at ,role_ptr_ [i ]+ (size_t ) ((uint64_t )expert * per ), (size_t )per ); 1855at += per ; 1856 } 1857return true; 1858 } 1859const uint8_t * b = mapped_blob (layer ,expert ); 1860if (b == nullptr )return false; 1861 std::memcpy (dst ,b , (size_t )layer_blob_bytes_ [(size_t )layer ]); 1862return true; 1863} 1864 1865// Pinned stage buffers (PR 1237): opt-in (STRATA_STAGE_PIN=1). On by default they corrupted IQ3_S decode after a 4096-token 1866// prompt in the 0.1.41 release gate (48 tokens of id 0; off = identical to 0.1.40.4): with page-locked buffers the cache-fill 1867// copy is truly asynchronous, so a recycled stage buffer can be overwritten before its copy finishes. Off until that is fixed. 1868#define STAGE_PIN_DEFAULT 0 1869constexpr uint64_t kStagePinFloor = 3ull <<30 ;// RAM left available after a pinned stage buffer 1870void FileExpertSource ::StageBufFree ::operator()(uint8_t * p )const noexcept { 1871if (pinned ) (void )cudaFreeHost (p ); 1872else delete []p ; 1873} 1874 1875// A blob assembled from the three role slices. The buffer of a (layer, expert) is reused for another only once 1876// its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes 1877// first, and never while it is being filled: the pool computes a layer's misses before it starts the next, and a 1878// fill (the GPU cache at startup, an adaptive swap, a helper GPU) copies the blob right away. 1879// 1880// `claim_stage` finds or reserves the buffer of `key` (stage_mu_ held): true when the blob is already there (or 1881// being filled by another thread - the caller then waits), false when the caller must fill buffer `v`. 1882bool FileExpertSource ::claim_stage (int64_t key ,size_t & v ,bool & fill ,bool ahead ) { 1883constexpr uint64_t kStageSeq = 256 ; 1884const uint64_t seq = ++ stage_seq_ ; 1885auto it = stage_of_ .find (key ); 1886fill = false; 1887if (it != stage_of_ .end ()) { 1888v = it -> second ; 1889stage_epoch_ [v ]= epoch_ ; 1890stage_used_ [v ]= seq ; 1891if (!ahead && stage_pf_ [v ]) {// a layer asked for what was read ahead 1892stage_pf_ [v ]= 0 ; 1893io_pf_used_ .fetch_add (1 , std::memory_order_relaxed ); 1894io_pf_used_bytes_ .fetch_add (layer_blob_bytes_ [(size_t ) (key /n_expert_ )], std::memory_order_relaxed ); 1895 } 1896return true; 1897 } 1898v = stage_buf_ .size (); 1899uint64_t oldest = std::numeric_limits < uint64_t > ::max (); 1900for (size_t i = 0 ;i < stage_buf_ .size ();++ i ) 1901if (!stage_busy_ [i ]&& (stage_epoch_ [i ]+ kStageAge <=epoch_ || stage_used_ [i ]+ kStageSeq <=seq )&& 1902stage_used_ [i ]< oldest ) { 1903oldest = stage_used_ [i ]; 1904v = i ; 1905 } 1906if (v == stage_buf_ .size ()) { 1907// Pinned, where the driver allows: a stage buffer is the source of the cache fill's cudaMemcpyAsync, 1908// and a pageable source is staged through the driver's bounce buffer - an extra copy at a fraction of 1909// the transfer rate, on the calling thread. A failure falls back to pageable for this buffer. 1910// STRATA_STAGE_PIN: 0 keeps them pageable (as before 0.1.41), 1 always tries to pin, unset (the default) pins while 1911// the host has kStagePinFloor of RAM to spare beside this buffer (the pool grows to ~257 buffers, 0.4-0.6 GiB): 1912// a low-RAM box keeps pageable ones instead of paying for the pinning (recommend, never force). 1913static const int pin_mode = [] {const char * v = std::getenv ("STRATA_STAGE_PIN" );return v == nullptr ?-1 : (std::atoi (v )!= 0 ?1 :0 ); }(); 1914bool want_pin = pin_mode != 0 ; 1915if (pin_mode < 0 ) { 1916uint64_t avail = 0 ; 1917want_pin = STAGE_PIN_DEFAULT && available_memory_bytes (avail )&& avail >= (uint64_t )stage_blob_ + kStagePinFloor ; 1918 } 1919void * p = nullptr ; 1920cudaError_t pin_err = cudaSuccess ; 1921if (want_pin )pin_err = cudaHostAlloc (& p , (size_t )stage_blob_ ,cudaHostAllocDefault ); 1922const bool pinned = want_pin && pin_err == cudaSuccess && p != nullptr ; 1923if (!pinned ) (void )cudaGetLastError ();// the failed alloc's sticky error is ours, not the caller's 1924uint8_t * raw = pinned ? (uint8_t * )p :new (std::nothrow )uint8_t [(size_t )stage_blob_ ]; 1925if (raw == nullptr )return false; 1926stage_buf_ .emplace_back (raw ,StageBufFree {pinned }); 1927stage_idx_ [raw ]= stage_buf_ .size ()- 1 ; 1928stage_ev_ .push_back (nullptr ); 1929stage_ev_live_ .push_back (0 ); 1930if (pinned && !stage_pin_said_ ) { 1931stage_pin_said_ = true; 1932 std::fprintf (stderr ,"FileExpertSource: the stage buffers are pinned (cudaHostAlloc)\n" ); 1933 }else if (!pinned && want_pin && !stage_pin_failed_said_ ) { 1934stage_pin_failed_said_ = true; 1935 std::fprintf (stderr ,"FileExpertSource: cudaHostAlloc failed for a stage buffer (%s) - pageable it is\n" , 1936cudaGetErrorString (pin_err )); 1937 } 1938stage_key_ .push_back (-1 ); 1939stage_epoch_ .push_back (0 ); 1940stage_used_ .push_back (0 ); 1941stage_busy_ .push_back (0 ); 1942stage_pf_ .push_back (0 ); 1943if (stage_buf_ .size ()== 512 && !stage_grew_ ) { 1944stage_grew_ = true; 1945 std::fprintf (stderr ,"FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n" , 1946stage_buf_ .size (), (double )stage_buf_ .size ()* (double )stage_blob_ /1073741824.0 ); 1947 } 1948 }else { 1949stage_of_ .erase (stage_key_ [v ]); 1950if (stage_pf_ [v ]) {stage_pf_ [v ]= 0 ;io_pf_unused_ .fetch_add (1 , std::memory_order_relaxed ); }// read ahead, never asked for 1951// #1237: a page-locked buffer is read by the DMA after the copy call returned: it is refilled only once the 1952// last copy queued out of it (note_async_read) has finished. Rare: the pool is sized so that a buffer asked 1953// for has long been consumed; a wait here means the stream is more than a pool behind. 1954if (v < stage_ev_live_ .size ()&& stage_ev_live_ [v ]) { 1955stage_ev_live_ [v ]= 0 ; 1956if (stage_ev_ [v ]!= nullptr ) { 1957if (cudaEventQuery ((cudaEvent_t )stage_ev_ [v ])== cudaErrorNotReady ) { 1958stage_fence_waits_ .fetch_add (1 , std::memory_order_relaxed ); 1959 (void )cudaEventSynchronize ((cudaEvent_t )stage_ev_ [v ]); 1960 } 1961 (void )cudaGetLastError (); 1962 } 1963 } 1964 } 1965stage_key_ [v ]= key ; 1966stage_epoch_ [v ]= epoch_ ; 1967stage_used_ [v ]= seq ; 1968stage_busy_ [v ]= 1 ; 1969stage_of_ [key ]= v ; 1970fill = true; 1971if (reuse_on ()&& in_decode ())reuse_note (key ); 1972return false; 1973} 1974 1975bool FileExpertSource ::reuse_on () { 1976static const bool on = [] {const char * v = std::getenv ("STRATA_FILE_REUSE" );return v != nullptr && std::atoi (v )!= 0 ; }(); 1977return on ; 1978} 1979 1980void FileExpertSource ::reuse_note (int64_t key ) { 1981const size_t pairs = (size_t ) (n_layers_ * n_expert_ ); 1982if (reuse_last_ .size ()!= pairs ) {reuse_last_ .assign (pairs ,0 );reuse_reads_ .assign (pairs ,0 ); } 1983if (key < 0 || (size_t )key >=pairs )return ; 1984const uint32_t last = reuse_last_ [(size_t )key ]; 1985size_t b = 7 ;// never read before 1986if (last != 0 ) { 1987const uint32_t gap = reuse_window_ - (last - 1 ); 1988b = gap == 0 ?0 :gap == 1 ?1 :gap == 2 ?2 :gap <=4 ?3 :gap <=8 ?4 :gap <=16 ?5 :6 ; 1989 } 1990++ reuse_hist_ [b ]; 1991reuse_last_ [(size_t )key ]= reuse_window_ + 1 ; 1992++ reuse_reads_ [(size_t )key ]; 1993} 1994 1995std::string FileExpertSource ::reuse_report () { 1996if (!reuse_on ())return {}; 1997 std::lock_guard < std::mutex > lk (stage_mu_ ); 1998uint64_t reads = 0 ; 1999for (const uint64_t h :reuse_hist_ )reads += h ; 2000if (reads == 0 || n_layers_ <=0 || n_expert_ <=0 )return {}; 2001const double gb = (double )expert_bytes () / (double ) (n_layers_ * n_expert_ ) /1e9 ;// mean blob 2002const uint32_t windows = reuse_window_ - reuse_window0_ ; 2003 std::vector < uint32_t > per ; 2004for (const uint32_t r :reuse_reads_ )if (r != 0 )per .push_back (r ); 2005 std::sort (per .begin (),per .end (), std::greater < uint32_t > ()); 2006auto top = [& ](size_t n ) { 2007uint64_t s = 0 ; 2008for (size_t i = 0 ;i < n && i < per .size ();++ i )s += per [i ]; 2009return (double )s * gb ; 2010 }; 2011const auto & h = reuse_hist_ ; 2012char b [640 ]; 2013 std::snprintf (b ,sizeof b , 2014"file reuse: %llu decode reads (%.1f GB) over %u windows, %zu distinct pairs (%.1f GB); windows since " 2015"the same expert's last read: 0 %llu, 1 %llu, 2 %llu, 3-4 %llu, 5-8 %llu, 9-16 %llu, >16 %llu, first %llu; " 2016"re-reads within 1/2/4/8 windows %.1f/%.1f/%.1f/%.1f GB; most-read 240/480/960 pairs %.1f/%.1f/%.1f GB" , 2017 (unsigned long long )reads , (double )reads * gb ,windows ,per .size (), (double )per .size ()* gb , 2018 (unsigned long long )h [0 ], (unsigned long long )h [1 ], (unsigned long long )h [2 ], (unsigned long long )h [3 ], 2019 (unsigned long long )h [4 ], (unsigned long long )h [5 ], (unsigned long long )h [6 ], (unsigned long long )h [7 ], 2020 (double ) (h [0 ]+ h [1 ])* gb , (double ) (h [0 ]+ h [1 ]+ h [2 ])* gb , (double ) (h [0 ]+ h [1 ]+ h [2 ]+ h [3 ])* gb , 2021 (double ) (h [0 ]+ h [1 ]+ h [2 ]+ h [3 ]+ h [4 ])* gb ,top (240 ),top (480 ),top (960 )); 2022reuse_hist_ = {}; 2023 std::fill (reuse_reads_ .begin (),reuse_reads_ .end (),0 ); 2024reuse_window0_ = reuse_window_ ; 2025return b ; 2026} 2027 2028// 149 STRATA_IO_PF_GATE: whether this thread reads for the decode (the dispatch's thread, and the fetch threads it starts) 2029namespace { thread_localbool tl_decode = false; } 2030FileExpertSource ::DecodeScope ::DecodeScope () :prev (tl_decode ) {tl_decode = true; } 2031FileExpertSource ::DecodeScope ::~DecodeScope () {tl_decode = prev ; } 2032bool FileExpertSource ::in_decode () {return tl_decode ; } 2033 2034// once a decode window: the share of the window's demand bytes the page cache held, an EWMA, and the gate's state 2035void FileExpertSource ::gate_tick () { 2036if (!gate_on_ )return ; 2037const uint64_t c = gate_c_ .load (std::memory_order_relaxed ),u = gate_u_ .load (std::memory_order_relaxed ); 2038const uint64_t dc = c - gate_prev_c_ ,du = u - gate_prev_u_ ; 2039gate_prev_c_ = c ; 2040gate_prev_u_ = u ; 2041if (dc + du < (64ull <<20 )) {// too few bytes read this window to judge; the state stays 2042if (!gate_open_ .load (std::memory_order_relaxed ))++ gate_closed_w_ ; 2043return ; 2044 } 2045const double h = (double )dc / (double ) (dc + du ); 2046gate_ewma_ = gate_ewma_ < 0.0 ?h :0.8 * gate_ewma_ + 0.2 * h ;// reported only 2047if (!gate_open_ .load (std::memory_order_relaxed ))++ gate_closed_w_ ; 2048} 2049 2050namespace { 2051// The room the page cache has for the experts: in a memory-limited cgroup (v2; the tightest limit of the group and its 2052// ancestors) the limit less what is not page cache (the group's memory.current - its "file" pages); otherwise 2053// MemAvailable (free + reclaimable cache). 0 when unknown. 2054uint64_t gate_cache_room () { 2055#if defined(__linux__ ) 2056auto read_u64 = [](const std::string & path ,uint64_t & v ) { 2057 std::ifstream f (path ); 2058 std::string s ; 2059if (!(f >>s )|| s == "max" )return false; 2060v = std::strtoull (s .c_str (),nullptr ,10 ); 2061return v > 0 ; 2062 }; 2063 std::string rel ; 2064 { 2065 std::ifstream g ("/proc/self/cgroup" ); 2066 std::string line ; 2067while (std::getline (g ,line )) 2068if (line .rfind ("0::" ,0 )== 0 ) {rel = line .substr (3 );break ; } 2069 } 2070uint64_t best = 0 ; 2071if (!rel .empty ()) { 2072const std::string base = "/sys/fs/cgroup" ; 2073for (std::string at = rel ;; ) { 2074const std::string dir = base + (at == "/" ? std::string () :at ); 2075uint64_t mx = 0 ,cur = 0 ,file = 0 ; 2076if (read_u64 (dir + "/memory.max" ,mx )&& read_u64 (dir + "/memory.current" ,cur )) { 2077 std::ifstream st (dir + "/memory.stat" ); 2078 std::string k ; 2079uint64_t v = 0 ; 2080while (st >>k >>v ) 2081if (k == "file" ) {file = v ;break ; } 2082const uint64_t used = cur > file ?cur - file :0 ; 2083const uint64_t room = mx > used ?mx - used :0 ; 2084if (best == 0 || room < best )best = room ; 2085 } 2086if (at .empty ()|| at == "/" )break ; 2087const size_t cut = at .find_last_of ('/' ); 2088at = cut == 0 || cut == std::string::npos ? std::string ("/" ) :at .substr (0 ,cut ); 2089 } 2090 } 2091if (best > 0 )return best ; 2092 std::ifstream info ("/proc/meminfo" ); 2093 std::stringstream text ; 2094text <<info .rdbuf (); 2095return detail::meminfo_bytes (text .str (),"MemAvailable" ); 2096#else 2097return 0 ; 2098#endif 2099} 2100} 2101 2102double FileExpertSource ::cache_room_ratio ()const { 2103const uint64_t total = expert_bytes (),room = gate_cache_room (); 2104return total == 0 || room == 0 ?0.0 : (double )room / (double )total ; 2105} 2106 2107void FileExpertSource ::gate_capacity () { 2108if (!gate_on_ || (gate_win_ ++ %16 )!= 0 )return ; 2109const uint64_t total = expert_bytes (),room = gate_cache_room (); 2110if (total == 0 || room == 0 )return ;// unknown: the state stays 2111gate_ratio_ = (double )room / (double )total ; 2112// and the read-ahead must pay: the share of its bytes a layer then used, over these 16 windows (64 MB at least read 2113// ahead to judge). Below STRATA_IO_PF_GATE_USEFUL (0.10) it closes (a RAM tier holds what it would read: an 18 GiB 2114// RAM tier, 0% used, -9..-15% decode); closed for that reason, it opens again for a probe every 256 windows. 2115const uint64_t pf = io_pf_bytes_ .load (std::memory_order_relaxed ),used = io_pf_used_bytes_ .load (std::memory_order_relaxed ); 2116const uint64_t dpf = pf - gate_prev_pf_ ,dused = used - gate_prev_used_ ; 2117gate_prev_pf_ = pf ; 2118gate_prev_used_ = used ; 2119if (dpf >= (64ull <<20 ))gate_useful_ = (double )dused / (double )dpf ; 2120const bool open = gate_open_ .load (std::memory_order_relaxed ); 2121const bool room_ok = open ?gate_ratio_ >=gate_lo_ :gate_ratio_ > gate_hi_ ; 2122bool want = room_ok ; 2123// too little to read ahead (< 128 MB in 16 windows: the RAM and VRAM tiers hold what is predicted) costs the look-ahead's 2124// second layer and the I/O threads for nothing (an 18 GiB RAM tier: 2.5 GB read ahead in a run, -9..-16% decode) 2125if (room_ok && open && gate_win_ > 16 && (dpf < (128ull <<20 )|| gate_useful_ < gate_min_useful_ )) { 2126want = false; 2127gate_useless_ = true; 2128gate_useless_since_ = gate_win_ ; 2129 }else if (room_ok && !open && gate_useless_ ) { 2130want = gate_win_ - gate_useless_since_ >=256 ;// the probe 2131if (want )gate_useless_ = false; 2132 } 2133if (!room_ok )gate_useless_ = false; 2134if (want != open ) {gate_open_ .store (want , std::memory_order_relaxed );++ gate_flips_ ; } 2135} 2136 2137// Fills buffer `v` (reserved by claim_stage) outside the lock, then publishes it. 2138bool FileExpertSource ::fill_stage (size_t v ,int64_t layer ,int64_t expert ,uint8_t * dst ) { 2139const auto t0 = std::chrono::steady_clock::now (); 2140const bool ok = copy_from_files (layer ,expert ,dst ); 2141publish_stage (v ,layer ,ok , std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count ()); 2142return ok ; 2143} 2144 2145void FileExpertSource ::publish_stage (size_t v ,int64_t layer ,bool ok ,double us ) { 2146file_us_ .fetch_add ((uint64_t )us , std::memory_order_relaxed ); 2147if (ok ) { 2148file_read_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 2149file_blob_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 2150 } 2151 { 2152 std::lock_guard < std::mutex > lk (stage_mu_ ); 2153stage_busy_ [v ]= 0 ; 2154if (!ok ) { 2155stage_of_ .erase (stage_key_ [v ]); 2156stage_key_ [v ]= -1 ; 2157 } 2158 } 2159stage_cv_ .notify_all (); 2160} 2161 2162void FileExpertSource ::note_async_read (const uint8_t * blob ,void * stream ) { 2163if (blob == nullptr )return ; 2164 std::lock_guard < std::mutex > lk (stage_mu_ ); 2165const auto it = stage_idx_ .find (blob ); 2166if (it == stage_idx_ .end ())return ;// not a stage buffer: the mapping or the resident arena 2167const size_t v = it -> second ; 2168if (!stage_buf_ [v ].get_deleter ().pinned )return ;// pageable: the driver copied it before the call returned 2169if (stage_ev_ [v ]== nullptr ) { 2170cudaEvent_t ev = nullptr ; 2171if (cudaEventCreateWithFlags (& ev ,cudaEventDisableTiming )!= cudaSuccess ) { 2172 (void )cudaGetLastError (); 2173 (void )cudaStreamSynchronize ((cudaStream_t )stream );// no event: wait for the copy itself 2174return ; 2175 } 2176stage_ev_ [v ]= ev ; 2177 } 2178if (cudaEventRecord ((cudaEvent_t )stage_ev_ [v ], (cudaStream_t )stream )!= cudaSuccess ) { 2179 (void )cudaGetLastError (); 2180 (void )cudaStreamSynchronize ((cudaStream_t )stream ); 2181return ; 2182 } 2183stage_ev_live_ [v ]= 1 ; 2184} 2185 2186void FileExpertSource ::stage_free_events () { 2187for (void *& e :stage_ev_ ) 2188if (e != nullptr ) { (void )cudaEventDestroy ((cudaEvent_t )e );e = nullptr ; } 2189stage_ev_ .clear (); 2190stage_ev_live_ .clear (); 2191stage_idx_ .clear (); 2192} 2193 2194const uint8_t * FileExpertSource ::staged_blob (int64_t layer ,int64_t expert ) { 2195const int64_t key = layer * n_expert_ + expert ; 2196size_t v = 0 ; 2197bool fill = false; 2198uint8_t * dst = nullptr ; 2199const auto t0 = std::chrono::steady_clock::now (); 2200auto crit = [& ] { 2201if (!io_pf_ )return ; 2202io_crit_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 2203 std::memory_order_relaxed ); 2204io_crit_n_ .fetch_add (1 , std::memory_order_relaxed ); 2205 }; 2206 { 2207 std::unique_lock < std::mutex > lk (stage_mu_ ); 2208const bool have = claim_stage (key ,v ,fill ); 2209if (!have && !fill )return nullptr ; 2210dst = stage_buf_ [v ].get (); 2211if (have ) { 2212// another thread (a prefetch, the adaptive tier) is filling it: wait for that 2213stage_cv_ .wait (lk , [& ] {return !stage_busy_ [v ]|| stage_key_ [v ]!= key ; }); 2214if (stage_key_ [v ]!= key )return nullptr ;// its fill failed 2215lk .unlock (); 2216crit (); 2217return dst ; 2218 } 2219 } 2220const bool ok = fill_stage (v ,layer ,expert ,dst ); 2221crit (); 2222return ok ?dst :nullptr ; 2223} 2224 2225void FileExpertSource ::prefetch (int64_t layer ,const int64_t * experts ,int64_t n ) { 2226if (!staged ()|| n <=0 || layer < 0 || layer >=n_layers_ )return ; 2227if (io_fill_ && io_pf_ && direct_ .empty ()) {// hand the layer's uncached blobs to the workers and go on: the kernels 2228for (int64_t i = 0 ;i < n ;++ i ) {// that reach one before it lands wait on its pages, the rest compute 2229const int64_t e = experts [i ]; 2230if (e < 0 || e >=n_expert_ )continue ; 2231const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )e ; 2232if (pf_mark_ && pf_mark_ [index ].exchange (0 , std::memory_order_relaxed )) {// 149-prefetch: read ahead, now asked for 2233io_pf_used_ .fetch_add (1 , std::memory_order_relaxed ); 2234io_pf_used_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 2235 } 2236if (complement_ready_ && resident_blob (index )!= nullptr )continue ; 2237if (!override_ .empty ()&& override_ [index ]!= nullptr )continue ; 2238uint64_t total = 0 ; 2239if (cached_bytes (layer ,e ,total , false) >=total )continue ; 2240io_pf_demand_ .fetch_add (1 , std::memory_order_relaxed ); 2241io_enqueue (layer ,e ); 2242 } 2243return ; 2244 } 2245 std::vector < Fill > todo ; 2246const auto t0 = std::chrono::steady_clock::now (); 2247claim_todo (layer ,experts ,n ,todo ,nullptr ); 2248fill_many (todo ); 2249if (io_pf_ && !todo .empty ()) { 2250io_crit_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 2251 std::memory_order_relaxed ); 2252io_crit_n_ .fetch_add (1 , std::memory_order_relaxed ); 2253 } 2254} 2255 2256void FileExpertSource ::claim_todo (int64_t layer ,const int64_t * experts ,int64_t n , std::vector < Fill >& todo ,uint8_t * pending , 2257bool zc ) { 2258// 149-cold mode 3: the GGUF in place, mapped and buffered: an expert the page cache holds whole is computed from 2259// the mapping (its three tensors' rows), not assembled into a stage buffer first. Decided here, before the lock. 2260zc_keys_ .clear (); 2261 std::vector < char > zc_ok ; 2262if (zc && !role_ptr_ .empty ()&& !unmapped_ && direct_ .empty ()&& strata::kernels::cpu::expert_layout ().native && 2263 strata::kernels::cpu::expert_layout ().fmt [(size_t )layer ].tail_off == 0 ) { 2264zc_ok .assign ((size_t )n ,0 ); 2265for (int64_t i = 0 ;i < n ;++ i ) { 2266const int64_t e = experts [i ]; 2267if (e < 0 || e >=n_expert_ )continue ; 2268const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )e ; 2269if (complement_ready_ && resident_blob (index )!= nullptr )continue ;// in the RAM copy: no residency query 2270if (!override_ .empty ()&& override_ [index ]!= nullptr )continue ; 2271uint64_t total = 0 ; 2272const uint64_t c = cached_bytes (layer ,e ,total , true); 2273zc_ok [(size_t )i ]= total > 0 && c >=total ?1 :0 ;// no residency query (not Linux): never 2274 } 2275 } 2276// experts.bin with io prefetch: a blob whose pages are cached is handed out as the mapping (io_blob); only the 2277// uncached ones are read here, together, on the fetch threads 2278const bool only_uncached = io_pf_ && role_ptr_ .empty ()&& direct_ .empty (); 2279 std::vector < char > cold ; 2280if (only_uncached ) { 2281cold .assign ((size_t )n ,0 ); 2282for (int64_t i = 0 ;i < n ;++ i ) { 2283const int64_t e = experts [i ]; 2284if (e < 0 || e >=n_expert_ )continue ; 2285uint64_t total = 0 ; 2286cold [(size_t )i ]= cached_bytes (layer ,e ,total , false)< total ?1 :0 ; 2287 } 2288 } 2289 { 2290 std::lock_guard < std::mutex > lk (stage_mu_ ); 2291for (int64_t i = 0 ;i < n ;++ i ) { 2292const int64_t e = experts [i ]; 2293if (e < 0 || e >=n_expert_ )continue ; 2294const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )e ; 2295if (complement_ready_ && resident_blob (index )!= nullptr ) 2296continue ;// in the RAM copy 2297if (!override_ .empty ()&& override_ [index ]!= nullptr )continue ; 2298if (only_uncached && !cold [(size_t )i ]&& stage_of_ .find (layer * n_expert_ + e )== stage_of_ .end ())continue ; 2299if (!zc_ok .empty ()&& zc_ok [(size_t )i ]&& stage_of_ .find (layer * n_expert_ + e )== stage_of_ .end ()) { 2300zc_keys_ .push_back (layer * n_expert_ + e );// read from the mapping by the kernels themselves 2301continue ; 2302 } 2303size_t v = 0 ; 2304bool fill = false; 2305if (!claim_stage (layer * n_expert_ + e ,v ,fill )&& fill ) { 2306todo .push_back ({v ,layer ,e ,stage_buf_ [v ].get ()}); 2307if (pending != nullptr )pending [i ]= 1 ; 2308if (warm_stamp_ ) { 2309const uint32_t s = warm_stamp_ [index ].load (std::memory_order_relaxed ); 2310if (s != 0 && (uint64_t )s + 3 >=epoch_ + 1 )warm_hits_ .fetch_add (1 , std::memory_order_relaxed ); 2311 } 2312 }else if (pending != nullptr && fill == false) { 2313// being filled by another thread (a read ahead, the adaptive tier): not ready yet either 2314const auto it = stage_of_ .find (layer * n_expert_ + e ); 2315if (it != stage_of_ .end ()&& stage_busy_ [it -> second ])pending [i ]= 1 ; 2316 } 2317 } 2318 } 2319} 2320 2321// 149-cold STRATA_COLD_OVERLAP=1: the claimed blobs are read on background threads (the decode thread computes the 2322// ready experts meanwhile); the same reads as fill_many, on as many threads, each blob published as it lands. 2323int64_t FileExpertSource ::prefetch_begin (int64_t layer ,const int64_t * experts ,int64_t n ,uint8_t * pending ) { 2324for (int64_t i = 0 ;i < n ;++ i )pending [i ]= 0 ; 2325if (!staged ()|| n <=0 || layer < 0 || layer >=n_layers_ )return 0 ; 2326if (io_fill_ && io_pf_ && direct_ .empty ()) {// the page-fill mode: nothing is staged here, the kernels wait on pages 2327prefetch (layer ,experts ,n ); 2328return 0 ; 2329 } 2330prefetch_end (); 2331async_todo_ .clear (); 2332async_fill_us_ = 0 ; 2333static const int mode_env = [] {// as the dispatch reads it (0.2.0: unset = 4 for the GGUF read in place on Linux) 2334const char * v = std::getenv ("STRATA_COLD_OVERLAP" ); 2335return v == nullptr || v [0 ]== '\0' ?-1 : std::atoi (v ); 2336 }(); 2337const int mode = mode_env >=0 ?mode_env : (linux_file_defaults () ?4 :0 ); 2338claim_todo (layer ,experts ,n ,async_todo_ ,pending ,mode >=3 ); 2339if (mode == 4 ) {// zero-copy only: the blobs that must be read are read here, as `prefetch` reads them 2340const auto t0 = std::chrono::steady_clock::now (); 2341fill_many (async_todo_ ); 2342if (io_pf_ && !async_todo_ .empty ()) { 2343io_crit_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 2344 std::memory_order_relaxed ); 2345io_crit_n_ .fetch_add (1 , std::memory_order_relaxed ); 2346 } 2347async_todo_ .clear (); 2348for (int64_t i = 0 ;i < n ;++ i )pending [i ]= 0 ;// one another thread still fills: `blob` waits for it 2349return 0 ; 2350 } 2351int64_t np = 0 ; 2352for (int64_t i = 0 ;i < n ;++ i )np += pending [i ] ?1 :0 ; 2353if (async_todo_ .empty ())return np ; 2354async_t0_ = std::chrono::steady_clock::now (); 2355async_next_ .store (0 , std::memory_order_relaxed ); 2356async_end_ns_ .store (0 , std::memory_order_relaxed ); 2357const bool direct = !direct_ .empty (); 2358const bool dec = tl_decode ; 2359auto work = [this ,direct ,dec ] { 2360tl_decode = dec ; 2361const std::vector < Fill >& todo = async_todo_ ; 2362if (direct ) { 2363for (size_t at ; (at = async_next_ .fetch_add (16 ))< todo .size ();) { 2364const size_t k = std::min < size_t > (16 ,todo .size ()- at ); 2365const auto t0 = std::chrono::steady_clock::now (); 2366const bool ok = read_direct (todo .data ()+ at ,k ); 2367const double us = std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (); 2368for (size_t i = at ;i < at + k ;++ i ) { 2369const Fill & f = todo [i ]; 2370if (ok )publish_stage (f .v ,f .layer , true,us / (double )k ); 2371else (void )fill_stage (f .v ,f .layer ,f .e ,f .dst ); 2372 } 2373 } 2374 }else { 2375for (size_t i ; (i = async_next_ .fetch_add (1 ))< todo .size ();) 2376 (void )fill_stage (todo [i ].v ,todo [i ].layer ,todo [i ].e ,todo [i ].dst ); 2377 } 2378const int64_t ns = (int64_t ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 2379 std::chrono::steady_clock::now ()- async_t0_ ).count (); 2380int64_t cur = async_end_ns_ .load (std::memory_order_relaxed ); 2381while (ns > cur && !async_end_ns_ .compare_exchange_weak (cur ,ns , std::memory_order_relaxed )) {} 2382 }; 2383const size_t nt = direct ? std::min < size_t > (4 , (async_todo_ .size ()+ 15 ) /16 ) 2384 : std::min < size_t > (async_todo_ .size (), (size_t ) std::max (1 ,fetch_threads_ )); 2385for (size_t t = 0 ;t < nt ;++ t )async_th_ .emplace_back (work ); 2386return np ; 2387} 2388 2389int64_t FileExpertSource ::wait_landed (int64_t layer ,const int64_t * experts ,int64_t n ,uint8_t * state ) { 2390 std::unique_lock < std::mutex > lk (stage_mu_ ); 2391int64_t got = 0 ; 2392stage_cv_ .wait (lk , [& ] { 2393bool left = false; 2394for (int64_t i = 0 ;i < n ;++ i ) { 2395if (state [i ]!= 1 )continue ; 2396const auto it = stage_of_ .find (layer * n_expert_ + experts [i ]); 2397// published (or failed: then `blob` reads it again on this thread, as before) 2398if (it == stage_of_ .end ()|| !stage_busy_ [it -> second ]) {state [i ]= 2 ;++ got ; } 2399else left = true; 2400 } 2401return got > 0 || !left ; 2402 }); 2403return got ; 2404} 2405 2406bool FileExpertSource ::zc_roles (int64_t layer ,int64_t expert ,const uint8_t ** p ) { 2407const int64_t key = layer * n_expert_ + expert ; 2408if (std::find (zc_keys_ .begin (),zc_keys_ .end (),key )== zc_keys_ .end ())return false; 2409for (int r = 0 ;r < 3 ;++ r ) { 2410const size_t i = (size_t ) (3 * layer + r ); 2411p [r ]= role_ptr_ [i ]+ (size_t ) ((uint64_t )expert * role_bytes_ [i ]); 2412 } 2413file_read_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 2414if (complement_ready_ )file_reads_ .fetch_add (1 , std::memory_order_relaxed ); 2415reads_ .fetch_add (1 , std::memory_order_relaxed ); 2416if (io_stats_ )io_cached_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 2417if (gate_on_ && tl_decode )gate_c_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 2418return true; 2419} 2420 2421void FileExpertSource ::prefetch_end () { 2422if (async_th_ .empty ())return ; 2423for (std::thread & t :async_th_ )t .join (); 2424async_th_ .clear (); 2425async_fill_us_ = (double )async_end_ns_ .load (std::memory_order_relaxed ) /1e3 ; 2426if (io_pf_ && !async_todo_ .empty ()) {// the reads' wall time, as the synchronous fill counts it 2427io_crit_us_ .fetch_add ((uint64_t )async_fill_us_ , std::memory_order_relaxed ); 2428io_crit_n_ .fetch_add (1 , std::memory_order_relaxed ); 2429 } 2430async_todo_ .clear (); 2431} 2432 2433bool FileExpertSource ::latent_fetch_begin (int64_t layer ,const int64_t * experts ,int64_t n ) { 2434if (direct_ .empty ()|| experts == nullptr || layer < 0 || layer >=n_layers_ || 2435n < 1 || n > 16 || !latent_fetch_wait ())return false; 2436 { 2437 std::lock_guard < std::mutex > lk (latent_io_mu_ ); 2438if (!latent_io_thread_ .joinable ()) 2439latent_io_thread_ = std::thread ([this ] {latent_io_worker (); }); 2440 } 2441 std::vector < Fill > todo ; 2442todo .reserve ((size_t )n ); 2443try { 2444claim_todo (layer ,experts ,n ,todo ,nullptr ); 2445 }catch (...) { 2446for (const Fill & f :todo )publish_stage (f .v ,f .layer , false,0 ); 2447throw ; 2448 } 2449if (todo .empty ())return true; 2450 { 2451 std::lock_guard < std::mutex > lk (latent_io_mu_ ); 2452latent_io_todo_ = std::move (todo ); 2453latent_io_ok_ = true; 2454latent_io_busy_ = true; 2455 } 2456latent_io_cv_ .notify_one (); 2457return true; 2458} 2459 2460bool FileExpertSource ::latent_fetch_wait () { 2461 std::unique_lock < std::mutex > lk (latent_io_mu_ ); 2462latent_io_cv_ .wait (lk , [& ] {return !latent_io_busy_ ; }); 2463return latent_io_ok_ ; 2464} 2465 2466void FileExpertSource ::latent_io_worker () { 2467 strata::platform::name_this_thread ("strata-lat-io" ); 2468for (;;) { 2469 std::vector < Fill > todo ; 2470 { 2471 std::unique_lock < std::mutex > lk (latent_io_mu_ ); 2472latent_io_cv_ .wait (lk , [& ] {return latent_io_quit_ || latent_io_busy_ ; }); 2473if (latent_io_quit_ && !latent_io_busy_ )return ; 2474todo = std::move (latent_io_todo_ ); 2475 } 2476bool ok = true; 2477size_t published = 0 ; 2478try { 2479const auto t0 = std::chrono::steady_clock::now (); 2480const bool direct_ok = read_direct (todo .data (),todo .size ()); 2481const double us = std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (); 2482for (;published < todo .size ();++ published ) { 2483const Fill & f = todo [published ]; 2484if (direct_ok )publish_stage (f .v ,f .layer , true,us / (double )todo .size ()); 2485else if (!fill_stage (f .v ,f .layer ,f .e ,f .dst ))ok = false; 2486 } 2487 }catch (...) { 2488ok = false; 2489for (;published < todo .size ();++ published ) 2490publish_stage (todo [published ].v ,todo [published ].layer , false,0 ); 2491 } 2492 { 2493 std::lock_guard < std::mutex > lk (latent_io_mu_ ); 2494latent_io_ok_ = ok ; 2495latent_io_busy_ = false; 2496 } 2497latent_io_cv_ .notify_all (); 2498 } 2499} 2500 2501void FileExpertSource ::latent_io_stop () { 2502 { 2503 std::lock_guard < std::mutex > lk (latent_io_mu_ ); 2504latent_io_quit_ = true; 2505 } 2506latent_io_cv_ .notify_all (); 2507if (latent_io_thread_ .joinable ())latent_io_thread_ .join (); 2508 std::lock_guard < std::mutex > lk (latent_io_mu_ ); 2509latent_io_todo_ .clear (); 2510latent_io_quit_ = latent_io_busy_ = false; 2511latent_io_ok_ = true; 2512} 2513 2514void FileExpertSource ::prefetch_pairs (const std::pair < int32_t ,int32_t >* pairs ,int64_t n ) { 2515if (direct_ .empty ()|| pairs == nullptr || n <=0 )return ;// unbuffered only: the mapped fill stays as it was 2516 std::vector < Fill > todo ; 2517 { 2518 std::lock_guard < std::mutex > lk (stage_mu_ ); 2519for (int64_t i = 0 ;i < std::min < int64_t > (n ,64 );++ i ) { 2520const int64_t l = pairs [i ].first ,e = pairs [i ].second ; 2521if (l < 0 || e < 0 || l >=n_layers_ || e >=n_expert_ )continue ; 2522size_t v = 0 ; 2523bool fill = false; 2524if (!claim_stage (l * n_expert_ + e ,v ,fill )&& fill )todo .push_back ({v ,l ,e ,stage_buf_ [v ].get ()}); 2525 } 2526 } 2527fill_many (todo ); 2528} 2529 2530bool FileExpertSource ::advise_pairs (const std::pair < int32_t ,int32_t >* pairs ,int64_t n )const { 2531if (base_ == nullptr || unmapped_ || !direct_ .empty ()|| !strata::platform::read_ahead_enabled ())return false; 2532for (int64_t i = 0 ;pairs != nullptr && i < n ;++ i ) { 2533const int64_t l = pairs [i ].first ,e = pairs [i ].second ; 2534if (l < 0 || e < 0 || l >=n_layers_ || e >=n_expert_ )continue ; 2535if (role_ptr_ .empty ()) {// experts.bin: the blob is one contiguous range 2536if (const uint8_t * b = mapped_blob (l ,e )) strata::platform::advise_willneed (b ,layer_blob_bytes_ [(size_t )l ]); 2537continue ; 2538 } 2539for (int r = 0 ;r < 3 ;++ r ) { 2540const size_t k = (size_t ) (3 * l + r ); 2541 strata::platform::advise_willneed (role_ptr_ [k ]+ (size_t ) ((uint64_t )e * role_bytes_ [k ]),role_bytes_ [k ]); 2542 } 2543 } 2544return true; 2545} 2546 2547void FileExpertSource ::fill_many (const std::vector < Fill >& todo ) { 2548if (todo .empty ())return ; 2549if (!direct_ .empty ()) { 2550// #286: overlapped batches - every role window of 16 blobs in flight at once; a big batch (the profile 2551// fill) on up to 4 threads, a decode layer's few misses on this one 2552 std::atomic < size_t > next {0 }; 2553auto work = [& ] { 2554for (size_t at ; (at = next .fetch_add (16 ))< todo .size ();) { 2555const size_t k = std::min < size_t > (16 ,todo .size ()- at ); 2556const auto t0 = std::chrono::steady_clock::now (); 2557const bool ok = read_direct (todo .data ()+ at ,k ); 2558const double us = std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (); 2559for (size_t i = at ;i < at + k ;++ i ) { 2560const Fill & f = todo [i ]; 2561// a failed batch: each blob again on its own (copy_from_files falls back to the mapping) 2562if (ok )publish_stage (f .v ,f .layer , true,us / (double )k ); 2563else (void )fill_stage (f .v ,f .layer ,f .e ,f .dst ); 2564 } 2565 } 2566 }; 2567const size_t nt = std::min < size_t > (4 , (todo .size ()+ 15 ) /16 ); 2568 std::vector < std::thread > th ; 2569for (size_t t = 1 ;t < nt ;++ t )th .emplace_back (work ); 2570work (); 2571for (auto & t :th )t .join (); 2572return ; 2573 } 2574#if defined(_WIN32 ) 2575// One PrefetchVirtualMemory call for every slice about to be copied: the memory manager reads them in large 2576// requests, all queued at once, where the copies' page faults would read a few clusters each. The copies below 2577// then find the pages resident (or in flight). STRATA_FETCH_PVM=0 is the A/B arm. 2578 { 2579using Pvm = BOOL (WINAPI * )(HANDLE ,ULONG_PTR ,PWIN32_MEMORY_RANGE_ENTRY ,ULONG ); 2580static const Pvm pvm = [] { 2581const char * v = std::getenv ("STRATA_FETCH_PVM" ); 2582if (v != nullptr && std::atoi (v )== 0 )return (Pvm )nullptr ; 2583return (Pvm ) (void * )GetProcAddress (GetModuleHandleW (L"kernel32.dll" ),"PrefetchVirtualMemory" ); 2584 }(); 2585if (pvm != nullptr ) { 2586 std::vector < WIN32_MEMORY_RANGE_ENTRY > ranges ; 2587ranges .reserve (todo .size ()* 3 ); 2588for (const Fill & f :todo ) 2589for (int r = 0 ;r < 3 ;++ r ) { 2590const size_t i = (size_t ) (3 * f .layer + r ); 2591ranges .push_back ({(PVOID ) (role_ptr_ [i ]+ (size_t ) ((uint64_t )f .e * role_bytes_ [i ])), 2592 (SIZE_T )role_bytes_ [i ]}); 2593 } 2594 (void )pvm (GetCurrentProcess (), (ULONG_PTR )ranges .size (),ranges .data (),0 ); 2595 } 2596 } 2597#endif 2598// the page faults of a mapped read are one outstanding request each: several threads keep the SSD's queue full 2599 std::atomic < size_t > next {0 }; 2600const bool dec = tl_decode ; 2601auto work = [& ] { 2602tl_decode = dec ; 2603for (size_t i ; (i = next .fetch_add (1 ))< todo .size ();) 2604 (void )fill_stage (todo [i ].v ,todo [i ].layer ,todo [i ].e ,todo [i ].dst ); 2605 }; 2606const size_t nt = std::min < size_t > (todo .size (), (size_t )fetch_threads_ ); 2607 std::vector < std::thread > th ; 2608for (size_t t = 1 ;t < nt ;++ t )th .emplace_back (work ); 2609work (); 2610for (auto & t :th )t .join (); 2611} 2612 2613uint64_t FileExpertSource ::expert_bytes ()const { 2614uint64_t total = 0 ; 2615for (uint64_t b :layer_blob_bytes_ )total += b * (uint64_t )n_expert_ ; 2616return total ; 2617} 2618 2619bool FileExpertSource ::open_direct (std::string & why ) { 2620#if defined(_WIN32 ) 2621for (const std::string & path :paths_ ) { 2622const int wide = MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,nullptr ,0 ); 2623 std::vector < wchar_t > w ((size_t ) (wide > 0 ?wide :1 ),L'\0' ); 2624if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,w .data (),wide ); 2625HANDLE h = CreateFileW (w .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 2626FILE_FLAG_NO_BUFFERING |FILE_FLAG_OVERLAPPED ,nullptr ); 2627if (h == INVALID_HANDLE_VALUE ) { 2628why += "; cannot open " + path + " unbuffered (error " + std::to_string ((unsigned long long )GetLastError ())+ 2629"), read through the file cache" ; 2630for (void * d :direct_ )CloseHandle ((HANDLE )d ); 2631direct_ .clear (); 2632return false; 2633 } 2634direct_ .push_back (h ); 2635 } 2636if (role_ptr_ .empty ()) {// experts.bin: blob() now assembles into the stage buffers, sized for the largest blob 2637 std::lock_guard < std::mutex > lk (stage_mu_ ); 2638for (uint64_t b :layer_blob_bytes_ )stage_blob_ = std::max (stage_blob_ ,b ); 2639 } 2640return true; 2641#elif defined(__linux__ ) 2642// O_DIRECT: the reads bypass the page cache, as FILE_FLAG_NO_BUFFERING does (4 KiB-aligned windows, read_direct) 2643for (const std::string & path :paths_ ) { 2644const int fd = ::open (path .c_str (),O_RDONLY |O_DIRECT |O_CLOEXEC ); 2645if (fd < 0 ) { 2646why += "; cannot open " + path + " with O_DIRECT (" + std::strerror (errno )+ "), read through the file cache" ; 2647for (void * d :direct_ )close_direct (d ); 2648direct_ .clear (); 2649return false; 2650 } 2651direct_ .push_back ((void * ) (intptr_t )fd ); 2652 } 2653if (role_ptr_ .empty ()) {// experts.bin: blob() now assembles into the stage buffers, sized for the largest blob 2654 std::lock_guard < std::mutex > lk (stage_mu_ ); 2655for (uint64_t b :layer_blob_bytes_ )stage_blob_ = std::max (stage_blob_ ,b ); 2656 } 2657return true; 2658#else 2659 (void )why ; 2660return false; 2661#endif 2662} 2663 2664bool FileExpertSource ::open_prompt_direct (std::string & why ) { 2665#if defined(__linux__ ) 2666if (base_ == nullptr || paths_ .empty ()) {why = "no expert files open" ;return false; } 2667if (!direct_ .empty ()) {why = "the file tier reads unbuffered already" ;return false; } 2668if (!pdirect_ .empty ())return true; 2669for (const std::string & path :paths_ ) { 2670const int fd = ::open (path .c_str (),O_RDONLY |O_DIRECT |O_CLOEXEC ); 2671if (fd < 0 ) { 2672why = "cannot open " + path + " with O_DIRECT (" + std::strerror (errno )+ ")" ; 2673for (void * d :pdirect_ )close_direct (d ); 2674pdirect_ .clear (); 2675return false; 2676 } 2677pdirect_ .push_back ((void * ) (intptr_t )fd ); 2678 } 2679return true; 2680#else 2681why = "Linux only (NTFS serves unbuffered reads of a mapped file one at a time)" ; 2682return false; 2683#endif 2684} 2685 2686bool FileExpertSource ::set_unbuffered (uint64_t ram_bytes , std::string & why ) { 2687#if defined(_WIN32 )|| defined(__linux__ ) 2688if (base_ == nullptr || paths_ .empty ()|| !direct_ .empty ()) { 2689why = !direct_ .empty () ?"already unbuffered" :"no expert files open" ; 2690return !direct_ .empty (); 2691 } 2692// #577: the file tier reads the experts outside the RAM copy, not every byte of the shards (dense weights, the 2693// PLE table), and the copy holds at most every expert - the budget asked for can be more than that 2694const uint64_t experts = expert_bytes (); 2695const uint64_t arena = std::min (ram_bytes ,experts ); 2696if (!file_tier_unbuffered (paths_ ,arena ,experts - arena ,why ))return false; 2697return open_direct (why ); 2698#else 2699 (void )ram_bytes ; 2700why = "through the file cache (no unbuffered reads on this platform)" ; 2701return false; 2702#endif 2703} 2704 2705bool FileExpertSource ::recheck_unbuffered (std::string & why ) { 2706#if defined(_WIN32 )|| defined(__linux__ ) 2707if (const char * env = std::getenv ("STRATA_UNBUFFERED_LOAD" );env != nullptr && env [0 ]!= '\0' ) { 2708why = std::string ("STRATA_UNBUFFERED_LOAD=" )+ env ; 2709return !direct_ .empty (); 2710 } 2711if (base_ == nullptr || paths_ .empty ()) { 2712why = "no expert files open" ; 2713return false; 2714 } 2715// #577: the RAM copy is built (and already out of the available RAM), so what the file cache would have to keep 2716// is exactly the experts outside it - the GPU cache's (refilled after a prompt borrowed their slots) and the 2717// ones neither holds 2718const uint64_t experts = expert_bytes (); 2719const uint64_t read = experts > complement_bytes_ ?experts - complement_bytes_ :0 ; 2720 std::string w ; 2721const bool ub = file_tier_unbuffered (paths_ ,0 ,read ,w ); 2722char head [96 ]; 2723 std::snprintf (head ,sizeof head ,"re-checked with the RAM copy built (%.2f GiB): " , 2724 (double )complement_bytes_ /1073741824.0 ); 2725why = head + w ; 2726if (ub == !direct_ .empty ())return ub ; 2727if (ub )return open_direct (why ); 2728// through the file cache after all: the mapped reads take over (staged() stays true for the GGUF in place) 2729for (void * d :direct_ )close_direct (d ); 2730direct_ .clear (); 2731return false; 2732#else 2733why = "through the file cache (no unbuffered reads on this platform)" ; 2734return false; 2735#endif 2736} 2737 2738bool FileExpertSource ::drop_mapping (std::string & why ) { 2739#if defined(_WIN32 ) 2740if (direct_ .empty ()) {why = "the reads are not unbuffered" ;return false; } 2741if (!role_ptr_ .empty ()|| !maps_ .empty ()) { 2742// the GGUF in place: nothing in the engine reads the shards through these views any more (the token embedding is 2743// copied into pinned host memory at load, the dense weights and the head into VRAM, the PLE table has its own 2744// reader), so every shard goes: with one mapped, NTFS runs the unbuffered reads of that file one at a time 2745if (unmapped_ ) {why = "already closed" ;return true; } 2746for (Map & m :maps_ ) { 2747if (m .closed )continue ; 2748if (m .base != nullptr && !UnmapViewOfFile ((LPCVOID )m .base )) {why = "UnmapViewOfFile failed" ;return false; } 2749m .closed = true;// m.base stays: the read offsets are taken from it 2750if (m .mapping != nullptr )CloseHandle ((HANDLE )m .mapping ); 2751m .mapping = nullptr ; 2752if (m .file != nullptr )CloseHandle ((HANDLE )m .file ); 2753m .file = nullptr ; 2754 } 2755unmapped_ = true; 2756char note [160 ]; 2757 std::snprintf (note ,sizeof note ,"%zu GGUF shard%s unmapped; every expert outside RAM and VRAM is read unbuffered" , 2758maps_ .size (),maps_ .size ()== 1 ?"" :"s" ); 2759why = note ; 2760return true; 2761 } 2762if (base_ == nullptr || unmapped_ ) {why = base_ == nullptr ?"not open" :"already closed" ;return unmapped_ ; } 2763if (!UnmapViewOfFile ((LPCVOID )base_ )) {why = "UnmapViewOfFile failed" ;return false; } 2764unmapped_ = true; 2765if (mapping_ != nullptr )CloseHandle ((HANDLE )mapping_ ); 2766mapping_ = nullptr ; 2767// the cached handle too: only the unbuffered handles (direct_) read the file from here on 2768if (file_ != nullptr )CloseHandle ((HANDLE )file_ ); 2769file_ = nullptr ; 2770why = "every expert outside RAM and VRAM is read unbuffered" ; 2771return true; 2772#else 2773// Linux's page cache has no such lock: only the tests close the GGUF views (STRATA_TEST_UNMAP_GGUF=1), to run the 2774// unmapped path the Windows file tier takes 2775const char * t = std::getenv ("STRATA_TEST_UNMAP_GGUF" ); 2776if (t == nullptr || t [0 ]== '\0' || std::atoi (t )== 0 || role_ptr_ .empty ()) {why = "not Windows" ;return false; } 2777if (direct_ .empty ()) {why = "the reads are not unbuffered" ;return false; } 2778if (unmapped_ ) {why = "already closed" ;return true; } 2779for (Map & m :maps_ ) { 2780if (m .closed )continue ; 2781if (m .base != nullptr && munmap ((void * )m .base , (size_t )m .bytes )!= 0 ) {why = "munmap failed" ;return false; } 2782m .closed = true; 2783if (m .fd >=0 ) ::close (m .fd ); 2784m .fd = -1 ; 2785 } 2786unmapped_ = true; 2787why = std::to_string (maps_ .size ())+ " GGUF shard(s) unmapped (STRATA_TEST_UNMAP_GGUF); every expert outside RAM and VRAM is read unbuffered" ; 2788return true; 2789#endif 2790} 2791 2792uint64_t FileExpertSource ::drop_cached_pages (const std::function < bool (int64_t ,int64_t )>& keep ) { 2793#if defined(__linux__ ) 2794if (unmapped_ )return 0 ; 2795const uint64_t page = (uint64_t )sysconf (_SC_PAGESIZE ); 2796uint64_t released = 0 ; 2797// the whole pages of [p, p + n): a page that also holds a neighbouring blob stays (that neighbour may be kept) 2798auto drop = [& ](const uint8_t * p ,uint64_t n ,int fd ,uint64_t off ) { 2799const uint64_t a = ((uint64_t ) (uintptr_t )p + page - 1 )& ~(page - 1 ); 2800const uint64_t b = ((uint64_t ) (uintptr_t )p + n )& ~(page - 1 ); 2801if (p == nullptr || b <=a )return ; 2802if (madvise ((void * ) (uintptr_t )a , (size_t ) (b - a ),MADV_DONTNEED )!= 0 )return ; 2803if (fd >=0 ) (void )posix_fadvise (fd , (off_t ) (off + (a - (uint64_t ) (uintptr_t )p )), (off_t ) (b - a ),POSIX_FADV_DONTNEED ); 2804released += b - a ; 2805 }; 2806for (int64_t l = 0 ;l < n_layers_ ;++ l ) 2807for (int64_t e = 0 ;e < n_expert_ ;++ e ) { 2808if (keep && keep (l ,e ))continue ; 2809if (!role_ptr_ .empty ()) { 2810for (int r = 0 ;r < 3 ;++ r ) { 2811const size_t i = (size_t ) (3 * l + r ); 2812const uint64_t per = role_bytes_ [i ]; 2813const uint8_t * p = role_ptr_ [i ]+ (size_t ) ((uint64_t )e * per ); 2814const size_t f = (size_t )role_file_ [i ]; 2815if (f >=maps_ .size ()|| maps_ [f ].closed )continue ; 2816drop (p ,per ,maps_ [f ].fd , (uint64_t ) (p - maps_ [f ].base )); 2817 } 2818 }else if (const uint8_t * b = mapped_blob (l ,e )) { 2819drop (b ,layer_blob_bytes_ [(size_t )l ],fd_ , (uint64_t ) (b - base_ )); 2820 } 2821 } 2822return released ; 2823#else 2824 (void )keep ; 2825return 0 ; 2826#endif 2827} 2828 2829bool FileExpertSource ::begin_startup_unbuffered (std::string & why ) { 2830#if defined(_WIN32 ) 2831if (const char * v = std::getenv ("STRATA_STARTUP_UNBUFFERED" );v != nullptr && v [0 ]!= '\0' && std::atoi (v )== 0 ) { 2832why = "STRATA_STARTUP_UNBUFFERED=0" ; 2833return false; 2834 } 2835if (base_ == nullptr || unmapped_ || startup_ub_ || !role_ptr_ .empty ()|| !maps_ .empty ()|| paths_ .size ()!= 1 || 2836layer_blob_bytes_ .empty ()) { 2837why = "experts.bin only" ; 2838return false; 2839 } 2840if (!direct_ .empty ()) {why = "the file tier reads unbuffered already" ;return false; } 2841const auto t0 = std::chrono::steady_clock::now (); 2842const uint8_t * m = mapped_blob (0 ,0 );// the first blob as the mapping reads it, for the check below 2843if (m == nullptr ) {why = "the first blob is not mapped" ;return false; } 2844const std::vector < uint8_t > ref (m ,m + (size_t )layer_blob_bytes_ [0 ]); 2845// NTFS runs the unbuffered reads of a file one at a time while it is mapped or open buffered (drop_mapping), so 2846// the view, the section and the handle all go. The first unbuffered open with no buffered handle left purges the 2847// file's cached pages: 1.2-2.5 s after a mapped start had left IQ2_XS's 33 GiB experts.bin on the standby list, 2848// 3 ms after an unbuffered start. A buffered handle held open instead keeps the cache and serializes the reads 2849UnmapViewOfFile ((LPCVOID )base_ ); 2850unmapped_ = true; 2851if (mapping_ != nullptr )CloseHandle ((HANDLE )mapping_ ); 2852mapping_ = nullptr ; 2853if (file_ != nullptr )CloseHandle ((HANDLE )file_ ); 2854file_ = nullptr ; 2855 std::string fail ; 2856if (open_direct (fail )) { 2857// the first blob both ways: a drive that does not read it unbuffered keeps the mapped copy 2858 std::vector < uint8_t > probe (ref .size ()); 2859const Fill f {0 ,0 ,0 ,probe .data ()}; 2860if (read_direct (& f ,1 )&& std::memcmp (probe .data (),ref .data (),ref .size ())== 0 ) { 2861startup_ub_ = true; 2862startup_blob_bytes_ = file_blob_bytes_ .load (); 2863startup_us_ = file_us_ .load (); 2864char note [96 ]; 2865 std::snprintf (note ,sizeof note ,"the view closed until the RAM copy is built; %.0f ms" , 2866 std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count ()); 2867why = note ; 2868return true; 2869 } 2870fail = "an unbuffered read of the first blob failed or differed from the mapping" ; 2871for (void * d :direct_ )close_direct (d ); 2872direct_ .clear (); 2873 std::lock_guard < std::mutex > lk (stage_mu_ ); 2874stage_blob_ = 0 ; 2875 } 2876 std::string again ; 2877why = map_view (again ) ?fail :fail + "; " + again ; 2878return false; 2879#else 2880why = "Windows only" ; 2881return false; 2882#endif 2883} 2884 2885bool FileExpertSource ::end_startup_unbuffered (std::string & why ) { 2886if (!startup_ub_ )return true; 2887startup_ub_ = false; 2888// the view first: closing the unbuffered handles beside a buffered one purges nothing 2889if (!map_view (why )) { 2890why += ": the file tier reads it unbuffered" ; 2891return false;// as after drop_mapping: every read goes through read_direct 2892 } 2893for (void * d :direct_ )close_direct (d ); 2894direct_ .clear (); 2895 {// the mapped tier hands out the mapping: the startup's stage buffers go 2896 std::lock_guard < std::mutex > lk (stage_mu_ ); 2897stage_buf_ .clear (); 2898stage_key_ .clear (); 2899stage_epoch_ .clear (); 2900stage_used_ .clear (); 2901stage_busy_ .clear (); 2902stage_pf_ .clear (); 2903stage_of_ .clear (); 2904stage_blob_ = 0 ; 2905 } 2906file_blob_bytes_ .store (startup_blob_bytes_ ); 2907file_us_ .store (startup_us_ ); 2908return true; 2909} 2910 2911bool FileExpertSource ::map_view (std::string & why ) { 2912#if defined(_WIN32 ) 2913// open's mapping of experts.bin, again 2914const std::string & path = paths_ .front (); 2915const int wide = MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,nullptr ,0 ); 2916 std::vector < wchar_t > wpath ((size_t ) (wide > 0 ?wide :1 ),L'\0' ); 2917if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,path .c_str (),-1 ,wpath .data (),wide ); 2918HANDLE f = CreateFileW (wpath .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING ,FILE_ATTRIBUTE_NORMAL , 2919nullptr ); 2920LARGE_INTEGER sz {}; 2921const bool same = f != INVALID_HANDLE_VALUE && GetFileSizeEx (f ,& sz )&& (uint64_t )sz .QuadPart == mapped_bytes_ ; 2922HANDLE m = same ?CreateFileMappingW (f ,nullptr ,PAGE_READONLY ,0 ,0 ,nullptr ) :nullptr ; 2923void * view = m != nullptr ?MapViewOfFile (m ,FILE_MAP_READ ,0 ,0 ,0 ) :nullptr ; 2924if (view == nullptr ) { 2925why = f != INVALID_HANDLE_VALUE && !same 2926 ? std::string ("experts.bin changed size since it was opened" ) 2927 :"experts.bin could not be mapped again (error " + std::to_string ((unsigned long long )GetLastError ())+ ")" ; 2928if (m != nullptr )CloseHandle (m ); 2929if (f != INVALID_HANDLE_VALUE )CloseHandle (f ); 2930return false; 2931 } 2932file_ = f ; 2933mapping_ = m ; 2934base_ = (const uint8_t * )view ; 2935unmapped_ = false; 2936return true; 2937#else 2938why = "Windows only" ; 2939return false; 2940#endif 2941} 2942 2943bool FileExpertSource ::read_direct (const Fill * fills ,size_t n )const { 2944#if defined(_WIN32 ) 2945// NTFS runs the unbuffered reads of a file one at a time while the file is mapped or cached anywhere (the engine 2946// maps the GGUF shards for the token embedding and the PLE table): measured on a PCIe 5 drive, 512 KiB reads at 2947// queue depth 48 make 10.4 GB/s on a file nobody maps and 3.4 GB/s on a mapped one, 8 MiB reads 8.6 GB/s. So 2948// windows less than kGap apart (the same role of nearby experts) are merged into requests of up to kMerge bytes. 2949constexpr uint64_t kSector = 4096 ,kGap = 1ull <<20 ,kMerge = 32ull <<20 ; 2950struct Window {int file ;uint64_t a0 ,size ,skip ,n ,at ;uint8_t * dst ;size_t req ;uint64_t in_req ; }; 2951struct Req {HANDLE h ;uint64_t a0 ,size ,pos ; }; 2952// this thread's aligned buffer and events, kept for its next batch 2953struct Scratch { 2954uint8_t * buf = nullptr ; 2955size_t cap = 0 ; 2956 std::vector < HANDLE > ev ; 2957 std::vector < OVERLAPPED > ov ; 2958 std::vector < Window > win ; 2959 std::vector < size_t > order ; 2960 std::vector < Req > req ; 2961 std::vector < DWORD > got ; 2962 ~Scratch () { 2963if (buf != nullptr )VirtualFree (buf ,0 ,MEM_RELEASE ); 2964for (HANDLE e :ev )CloseHandle (e ); 2965 } 2966 }; 2967 thread_localScratch sc ; 2968sc .win .clear (); 2969for (size_t k = 0 ;k < n ;++ k ) { 2970const Fill & f = fills [k ]; 2971if (f .dst == nullptr || f .layer < 0 || f .e < 0 || f .layer >=n_layers_ || f .e >=n_expert_ )return false; 2972if (role_ptr_ .empty ()) {// experts.bin: the blob is one contiguous range 2973const uint64_t per = layer_blob_bytes_ [(size_t )f .layer ]; 2974const uint64_t off = layer_offsets_ [(size_t )f .layer ]+ (uint64_t )f .e * per ; 2975const uint64_t a0 = off /kSector * kSector ,a1 = (off + per + kSector - 1 ) /kSector * kSector ; 2976sc .win .push_back ({0 ,a0 ,a1 - a0 ,off - a0 ,per ,0 ,f .dst ,0 ,0 }); 2977continue ; 2978 } 2979uint64_t at = 0 ; 2980for (int r = 0 ;r < 3 ;++ r ) { 2981const size_t i = (size_t ) (3 * f .layer + r ); 2982const uint64_t per = role_bytes_ [i ]; 2983const Map & m = maps_ [(size_t )role_file_ [i ]]; 2984const uint64_t off = (uint64_t ) (role_ptr_ [i ]- m .base )+ (uint64_t )f .e * per ; 2985const uint64_t a0 = off /kSector * kSector ,a1 = (off + per + kSector - 1 ) /kSector * kSector ; 2986sc .win .push_back ({role_file_ [i ],a0 ,a1 - a0 ,off - a0 ,per ,at ,f .dst ,0 ,0 }); 2987at += per ; 2988 } 2989 } 2990sc .order .resize (sc .win .size ()); 2991for (size_t w = 0 ;w < sc .win .size ();++ w )sc .order [w ]= w ; 2992 std::sort (sc .order .begin (),sc .order .end (), [& ](size_t a ,size_t b ) { 2993return sc .win [a ].file != sc .win [b ].file ?sc .win [a ].file < sc .win [b ].file :sc .win [a ].a0 < sc .win [b ].a0 ; 2994 }); 2995sc .req .clear (); 2996uint64_t total = 0 ; 2997int last_file = -1 ; 2998for (size_t w :sc .order ) { 2999Window & x = sc .win [w ]; 3000if (!sc .req .empty ()&& x .file == last_file ) { 3001Req & q = sc .req .back (); 3002const uint64_t end = q .a0 + q .size ,xend = x .a0 + x .size ; 3003if (x .a0 <=end + kGap && std::max (end ,xend )- q .a0 <=kMerge ) { 3004if (xend > end ) { 3005total += xend - end ; 3006q .size = xend - q .a0 ; 3007 } 3008x .req = sc .req .size ()- 1 ; 3009x .in_req = x .a0 - q .a0 ; 3010continue ; 3011 } 3012 } 3013sc .req .push_back ({(HANDLE )direct_ [(size_t )x .file ],x .a0 ,x .size ,total }); 3014total += x .size ; 3015last_file = x .file ; 3016x .req = sc .req .size ()- 1 ; 3017x .in_req = 0 ; 3018 } 3019if (total > sc .cap ) { 3020if (sc .buf != nullptr )VirtualFree (sc .buf ,0 ,MEM_RELEASE ); 3021sc .cap = (size_t ) ((total + (1u <<20 )- 1 ) >>20 <<20 ); 3022sc .buf = (uint8_t * )VirtualAlloc (nullptr ,sc .cap ,MEM_COMMIT |MEM_RESERVE ,PAGE_READWRITE ); 3023if (sc .buf == nullptr ) {sc .cap = 0 ;return false; } 3024 } 3025while (sc .ev .size ()< sc .req .size ()) { 3026HANDLE e = CreateEventW (nullptr , TRUE, FALSE,nullptr ); 3027if (e == nullptr )return false; 3028sc .ev .push_back (e ); 3029 } 3030sc .ov .assign (sc .req .size (),OVERLAPPED {}); 3031// every request in flight before the first wait: the drive sees the whole batch as one queue 3032size_t issued = 0 ; 3033bool ok = true; 3034for (size_t q = 0 ;q < sc .req .size ();++ q ) { 3035const Req & r = sc .req [q ]; 3036OVERLAPPED & o = sc .ov [q ]; 3037o .Offset = (DWORD )r .a0 ; 3038o .OffsetHigh = (DWORD ) (r .a0 >>32 ); 3039o .hEvent = sc .ev [q ]; 3040if (!ReadFile (r .h ,sc .buf + r .pos , (DWORD )r .size ,nullptr ,& o )&& GetLastError ()!= ERROR_IO_PENDING ) { 3041ok = false; 3042break ; 3043 } 3044++ issued ; 3045 } 3046 std::vector < DWORD >& got = sc .got ; 3047got .assign (sc .req .size (),0 ); 3048for (size_t q = 0 ;q < issued ;++ q ) 3049if (!GetOverlappedResult (sc .req [q ].h ,& sc .ov [q ],& got [q ], TRUE))ok = false; 3050if (!ok || issued < sc .req .size ())return false; 3051for (const Window & x :sc .win ) { 3052// a request may run past the end of the file: only the role's own bytes have to arrive 3053if ((uint64_t )got [x .req ]< x .in_req + x .skip + x .n )return false; 3054 std::memcpy (x .dst + x .at ,sc .buf + sc .req [x .req ].pos + x .in_req + x .skip , (size_t )x .n ); 3055 } 3056return true; 3057#elif defined(__linux__ ) 3058// Linux: O_DIRECT descriptors (open_direct) and the kernel's asynchronous reads - every window of the batch is 3059// queued with one io_submit before the first wait, so the drive sees the batch as one queue, as the overlapped 3060// ReadFiles above do. No NTFS here: windows are merged only where they touch (the 4 KiB rounding of adjacent 3061// slices, consecutive experts of a role), never across a gap that would be read for nothing. Each thread has its 3062// own context and aligned buffer, kept for its next batch, so concurrent batches never see each other's events. 3063constexpr uint64_t kSector = 4096 ,kMerge = 32ull <<20 ; 3064constexpr long kDepth = 256 ;// requests in flight per thread; a larger batch is read in waves of this many 3065struct Window {int file ;uint64_t a0 ,size ,skip ,n ,at ;uint8_t * dst ;size_t req ;uint64_t in_req ; }; 3066struct Req {int fd ;uint64_t a0 ,size ,pos ; }; 3067struct Scratch { 3068uint8_t * buf = nullptr ; 3069size_t cap = 0 ; 3070aio_context_t ctx = 0 ; 3071 std::vector < Window > win ; 3072 std::vector < size_t > order ; 3073 std::vector < Req > req ; 3074 std::vector < int64_t > got ; 3075 std::vector < iocb > cb ; 3076 std::vector < iocb *> cbp ; 3077 std::vector < io_event > ev ; 3078 ~Scratch () { 3079 std::free (buf ); 3080if (ctx != 0 ) (void )syscall (SYS_io_destroy ,ctx ); 3081 } 3082 }; 3083 thread_localScratch sc ; 3084if (sc .ctx == 0 && syscall (SYS_io_setup ,kDepth ,& sc .ctx )!= 0 ) { 3085sc .ctx = 0 ; 3086return false;// no AIO (a seccomp profile, aio-max-nr): the caller falls back to the mapped copy 3087 } 3088sc .win .clear (); 3089for (size_t k = 0 ;k < n ;++ k ) { 3090const Fill & f = fills [k ]; 3091if (f .dst == nullptr || f .layer < 0 || f .e < 0 || f .layer >=n_layers_ || f .e >=n_expert_ )return false; 3092if (role_ptr_ .empty ()) {// experts.bin: the blob is one contiguous range 3093const uint64_t per = layer_blob_bytes_ [(size_t )f .layer ]; 3094const uint64_t off = layer_offsets_ [(size_t )f .layer ]+ (uint64_t )f .e * per ; 3095const uint64_t a0 = off /kSector * kSector ,a1 = (off + per + kSector - 1 ) /kSector * kSector ; 3096sc .win .push_back ({0 ,a0 ,a1 - a0 ,off - a0 ,per ,0 ,f .dst ,0 ,0 }); 3097continue ; 3098 } 3099uint64_t at = 0 ; 3100for (int r = 0 ;r < 3 ;++ r ) { 3101const size_t i = (size_t ) (3 * f .layer + r ); 3102const uint64_t per = role_bytes_ [i ]; 3103const Map & m = maps_ [(size_t )role_file_ [i ]]; 3104const uint64_t off = (uint64_t ) (role_ptr_ [i ]- m .base )+ (uint64_t )f .e * per ; 3105const uint64_t a0 = off /kSector * kSector ,a1 = (off + per + kSector - 1 ) /kSector * kSector ; 3106sc .win .push_back ({role_file_ [i ],a0 ,a1 - a0 ,off - a0 ,per ,at ,f .dst ,0 ,0 }); 3107at += per ; 3108 } 3109 } 3110sc .order .resize (sc .win .size ()); 3111for (size_t w = 0 ;w < sc .win .size ();++ w )sc .order [w ]= w ; 3112 std::sort (sc .order .begin (),sc .order .end (), [& ](size_t a ,size_t b ) { 3113return sc .win [a ].file != sc .win [b ].file ?sc .win [a ].file < sc .win [b ].file :sc .win [a ].a0 < sc .win [b ].a0 ; 3114 }); 3115sc .req .clear (); 3116uint64_t total = 0 ; 3117int last_file = -1 ; 3118for (size_t w :sc .order ) { 3119Window & x = sc .win [w ]; 3120if (!sc .req .empty ()&& x .file == last_file ) { 3121Req & q = sc .req .back (); 3122const uint64_t end = q .a0 + q .size ,xend = x .a0 + x .size ; 3123if (x .a0 <=end && std::max (end ,xend )- q .a0 <=kMerge ) { 3124if (xend > end ) { 3125total += xend - end ; 3126q .size = xend - q .a0 ; 3127 } 3128x .req = sc .req .size ()- 1 ; 3129x .in_req = x .a0 - q .a0 ; 3130continue ; 3131 } 3132 } 3133sc .req .push_back ({(int ) (intptr_t ) (direct_ .empty () ?pdirect_ :direct_ )[(size_t )x .file ],x .a0 ,x .size ,total }); 3134total += x .size ; 3135last_file = x .file ; 3136x .req = sc .req .size ()- 1 ; 3137x .in_req = 0 ; 3138 } 3139if (total > sc .cap ) { 3140 std::free (sc .buf ); 3141sc .cap = (size_t ) ((total + (1u <<20 )- 1 ) >>20 <<20 ); 3142void * p = nullptr ; 3143sc .buf = posix_memalign (& p , (size_t )kSector ,sc .cap )== 0 ? (uint8_t * )p :nullptr ; 3144if (sc .buf == nullptr ) {sc .cap = 0 ;return false; } 3145 } 3146sc .got .assign (sc .req .size (),-1 ); 3147sc .cb .resize (std::min < size_t > (sc .req .size (), (size_t )kDepth )); 3148sc .cbp .resize (sc .cb .size ()); 3149sc .ev .resize (sc .cb .size ()); 3150bool ok = true; 3151for (size_t w0 = 0 ;ok && w0 < sc .req .size ();w0 += (size_t )kDepth ) { 3152const size_t wn = std::min < size_t > ((size_t )kDepth ,sc .req .size ()- w0 ); 3153for (size_t j = 0 ;j < wn ;++ j ) { 3154const Req & r = sc .req [w0 + j ]; 3155iocb & c = sc .cb [j ]; 3156 std::memset (& c ,0 ,sizeof c ); 3157c .aio_lio_opcode = IOCB_CMD_PREAD ; 3158c .aio_fildes = (uint32_t )r .fd ; 3159c .aio_buf = (uint64_t ) (uintptr_t ) (sc .buf + r .pos ); 3160c .aio_nbytes = r .size ; 3161c .aio_offset = (int64_t )r .a0 ; 3162c .aio_data = (uint64_t ) (w0 + j ); 3163sc .cbp [j ]= & c ; 3164 } 3165// every request of the wave queued; a refused submit ends the batch once what was queued has completed 3166// (the kernel still writes into the buffer until then) 3167size_t queued = 0 ; 3168while (queued < wn ) { 3169const long r = syscall (SYS_io_submit ,sc .ctx , (long ) (wn - queued ),sc .cbp .data ()+ queued ); 3170if (r > 0 ) {queued += (size_t )r ;continue ; } 3171if (r < 0 && errno == EINTR )continue ; 3172ok = false; 3173break ; 3174 } 3175for (size_t done = 0 ;done < queued ;) { 3176const long r = syscall (SYS_io_getevents ,sc .ctx ,1L , (long ) (queued - done ),sc .ev .data (),nullptr ); 3177if (r < 0 ) { 3178if (errno == EINTR )continue ; 3179// the context is in an unknown state: drop it (io_destroy waits for what is still in flight) 3180 (void )syscall (SYS_io_destroy ,sc .ctx ); 3181sc .ctx = 0 ; 3182return false; 3183 } 3184for (long j = 0 ;j < r ;++ j ) { 3185const io_event & e = sc .ev [(size_t )j ]; 3186sc .got [(size_t )e .data ]= e .res ; 3187if (e .res < 0 )ok = false; 3188 } 3189done += (size_t )r ; 3190 } 3191 } 3192if (!ok )return false; 3193for (const Window & x :sc .win ) { 3194// a request may run past the end of the file: only the role's own bytes have to arrive 3195if (sc .got [x .req ]< 0 || (uint64_t )sc .got [x .req ]< x .in_req + x .skip + x .n )return false; 3196 std::memcpy (x .dst + x .at ,sc .buf + sc .req [x .req ].pos + x .in_req + x .skip , (size_t )x .n ); 3197 } 3198return true; 3199#else 3200 (void )fills ; (void )n ; 3201return false; 3202#endif 3203} 3204 3205void FileExpertSource ::warm (int64_t layer ,const int64_t * experts ,int64_t n ) { 3206if ((role_ptr_ .empty ()&& !io_pf_ )|| n <=0 || layer < 0 || layer >=n_layers_ )return ; 3207uint32_t stamp ; 3208 { 3209 std::lock_guard < std::mutex > lk (stage_mu_ ); 3210stamp = (uint32_t )epoch_ + 1 ; 3211 } 3212#if defined(_WIN32 ) 3213using Pvm = BOOL (WINAPI * )(HANDLE ,ULONG_PTR ,PWIN32_MEMORY_RANGE_ENTRY ,ULONG ); 3214static const Pvm pvm = (Pvm ) (void * )GetProcAddress (GetModuleHandleW (L"kernel32.dll" ),"PrefetchVirtualMemory" ); 3215 std::vector < WIN32_MEMORY_RANGE_ENTRY > ranges ; 3216#endif 3217for (int64_t j = 0 ;j < n ;++ j ) { 3218const int64_t e = experts [j ]; 3219if (e < 0 || e >=n_expert_ )continue ; 3220const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )e ; 3221if (complement_ready_ && resident_blob (index )!= nullptr ) 3222continue ;// in the RAM copy 3223if (warm_stamp_ )warm_stamp_ [index ].store (stamp , std::memory_order_relaxed ); 3224warm_count_ .fetch_add (1 , std::memory_order_relaxed ); 3225if (io_pf_ && direct_ .empty ()&& gate_open ()) {// read it ahead with pread on the I/O threads (instead of an madvise hint) 3226if (io_ahead_ )io_enqueue (layer ,e , true); 3227continue ; 3228 } 3229if (role_ptr_ .empty ()|| unmapped_ )continue ; 3230for (int r = 0 ;r < 3 ;++ r ) { 3231const size_t i = (size_t ) (3 * layer + r ); 3232const uint8_t * p = role_ptr_ [i ]+ (size_t ) ((uint64_t )e * role_bytes_ [i ]); 3233#if defined(_WIN32 ) 3234ranges .push_back ({(PVOID )p , (SIZE_T )role_bytes_ [i ]}); 3235#else 3236const uintptr_t pg = 4096 ,a = (uintptr_t )p & ~(pg - 1 ); 3237 (void )madvise ((void * )a , (size_t ) ((uintptr_t )p + role_bytes_ [i ]- a ),MADV_WILLNEED ); 3238#endif 3239 } 3240 } 3241#if defined(_WIN32 ) 3242if (pvm != nullptr && !ranges .empty ()) (void )pvm (GetCurrentProcess (), (ULONG_PTR )ranges .size (),ranges .data (),0 ); 3243#endif 3244} 3245 3246static inline int la_pc64 (uint64_t x ) {// (portable: no compiler builtin) 3247int n = 0 ; 3248for (;x != 0 ;x &=x - 1 )++ n ; 3249return n ; 3250} 3251 3252RouterLookahead ::~RouterLookahead () { 3253 { 3254 std::lock_guard < std::mutex > lk (mu_ ); 3255quit_ = true; 3256 } 3257cv_ .notify_all (); 3258if (thread_ .joinable ())thread_ .join (); 3259} 3260 3261void RouterLookahead ::set_foresight (ForesightSwap * fs ) { 3262for (;;) { 3263 { 3264 std::lock_guard < std::mutex > lk (mu_ ); 3265if (fs != nullptr || !busy_ ) {fs_ = fs ;return ; } 3266 } 3267// detaching: a prediction in progress finishes first (the swap space is about to go away) 3268 std::this_thread::sleep_for (std::chrono::milliseconds (1 )); 3269 } 3270} 3271 3272bool RouterLookahead ::start (std::vector < std::vector < uint16_t >> routers ,int64_t n_embd ,int64_t n_expert ,int k , 3273ExpertSource * src , std::string & err ,bool allow_cold_source ) { 3274if (src == nullptr || (!allow_cold_source && !src -> warms ())) {err = "RouterLookahead: the expert source does not warm" ;return false; } 3275if (n_embd %8 != 0 ) {err = "RouterLookahead: n_embd is not a multiple of 8" ;return false; } 3276for (const auto & r :routers ) 3277if (r .size ()!= (size_t ) (n_embd * n_expert )) {err = "RouterLookahead: a router of another shape" ;return false; } 3278routers_ = std::move (routers ); 3279n_embd_ = n_embd ; 3280n_expert_ = n_expert ; 3281k_ = k < 1 ?1 :k > (int )n_expert ? (int )n_expert :k ; 3282src_ = src ; 3283x_ .assign ((size_t ) (8 * n_embd ),0.f ); 3284thread_ = std::thread ([this ] { 3285 strata::platform::name_this_thread ("strata-lookahead" ); 3286 strata::aux_cpus::pin_current_thread (); 3287run (); 3288 }); 3289return true; 3290} 3291 3292void RouterLookahead ::submit (int64_t layer ,const float * x ,int64_t n_tok ,const int32_t * host_res ) { 3293if (layer + 1 >= (int64_t )routers_ .size ()|| n_tok <=0 || x == nullptr )return ; 3294 { 3295 std::lock_guard < std::mutex > lk (mu_ ); 3296if (busy_ || pending_ ) {skipped_ .fetch_add (1 , std::memory_order_relaxed );return ; } 3297n_tok_ = std::min < int64_t > (n_tok ,8 ); 3298 std::memcpy (x_ .data (),x , (size_t ) (n_tok_ * n_embd_ )* sizeof (float )); 3299layer_ = layer + 1 ; 3300has_res_ = host_res != nullptr ; 3301if (has_res_ ) {// the rows of layer + 1 .. + depth, as they are now: the table changes while this runs 3302const int64_t l1 = std::min < int64_t > (layer_ + depth_ , (int64_t )routers_ .size ()); 3303res_ .assign (host_res + (size_t ) (layer_ * n_expert_ ),host_res + (size_t ) (l1 * n_expert_ )); 3304 } 3305sub_gen_ = gen_ .load (std::memory_order_relaxed ); 3306pending_ = true; 3307 } 3308cv_ .notify_one (); 3309} 3310 3311void RouterLookahead ::enable_stats (int64_t n_layers ) { 3312words_ = (n_expert_ + 63 ) /64 ; 3313pmask_ .reset (new std::atomic < uint64_t > [(size_t ) (n_layers * 3 * words_ )]); 3314pstamp_ .reset (new std::atomic < uint64_t > [(size_t )n_layers ]); 3315for (int64_t i = 0 ;i < n_layers * 3 * words_ ;++ i )pmask_ [(size_t )i ].store (0 , std::memory_order_relaxed ); 3316for (int64_t i = 0 ;i < n_layers ;++ i )pstamp_ [(size_t )i ].store (0 , std::memory_order_relaxed ); 3317pvote_ .reset (new std::atomic < int32_t > [(size_t ) (n_layers * kVoteN )]); 3318for (int64_t i = 0 ;i < n_layers * kVoteN ;++ i )pvote_ [(size_t )i ].store (0 , std::memory_order_relaxed ); 3319stats_on_ = true; 3320} 3321 3322// the dispatch thread: score the prediction made for `layer` against the experts it routes outside the GPU cache 3323void RouterLookahead ::stats_score (int64_t layer ,const int32_t * ids ,int64_t n ,const int32_t * host_res ,int pcie_num ) { 3324if (!stats_on_ || layer < 1 || layer >= (int64_t )routers_ .size ())return ; 3325++ st_layers_ ; 3326if (pstamp_ [(size_t )layer ].load (std::memory_order_acquire )!= gen_ .load (std::memory_order_relaxed )+ 1 ) { 3327++ st_nopred_ ; 3328return ; 3329 } 3330 std::vector < uint64_t > act ((size_t )words_ ,0 ); 3331for (int64_t i = 0 ;i < n ;++ i ) { 3332const int32_t e = ids [i ]; 3333if (e < 0 || e >=n_expert_ )continue ; 3334if (host_res != nullptr && host_res [(size_t ) (layer * n_expert_ + e )] >=0 )continue ; 3335act [(size_t ) (e >>6 )] |=1ull << (e & 63 ); 3336 } 3337uint64_t na = 0 ; 3338for (int64_t w = 0 ;w < words_ ;++ w )na += (uint64_t )la_pc64 (act [(size_t )w ]); 3339st_actual_ += na ; 3340 {// the vote-ranked top M (the experts most tokens predict) against the misses, and against the PCIe share 3341static const int vm [3 ]= {4 ,8 ,12 }; 3342int32_t vt [kVoteN ]; 3343int nv = 0 ; 3344for (int i = 0 ;i < kVoteN ;++ i ) { 3345const int32_t v = pvote_ [(size_t ) (layer * kVoteN + i )].load (std::memory_order_relaxed ); 3346if (v == 0 )break ; 3347vt [nv ++ ]= v - 1 ; 3348 } 3349// the misses in routing order (first appearance), the PCIe share = the last (n_miss * pcie_num / 256) of them 3350 std::vector < int32_t > order_miss ; 3351for (int64_t i = 0 ;i < n ;++ i ) { 3352const int32_t e = ids [i ]; 3353if (e < 0 || e >=n_expert_ )continue ; 3354if (host_res != nullptr && host_res [(size_t ) (layer * n_expert_ + e )] >=0 )continue ; 3355if (std::find (order_miss .begin (),order_miss .end (),e )== order_miss .end ())order_miss .push_back (e ); 3356 } 3357const int m = ((int )order_miss .size ()* pcie_num ) >>8 ; 3358st_pch_ += (uint64_t )m ; 3359for (int s = 0 ;s < 3 ;++ s ) { 3360const int top = std::min (vm [s ],nv ); 3361st_vpred_ [s ]+= (uint64_t )top ; 3362for (int j = 0 ;j < top ;++ j ) { 3363if ((act [(size_t ) (vt [j ] >>6 )] >> (vt [j ]& 63 ))& 1ull )++ st_vhit_ [s ]; 3364const auto it = std::find (order_miss .begin (),order_miss .end (),vt [j ]); 3365if (it != order_miss .end ()&& (int ) (it - order_miss .begin ()) >= (int )order_miss .size ()- m )++ st_pcov_ [s ]; 3366 } 3367 } 3368 } 3369for (int s = 0 ;s < 3 ;++ s ) { 3370uint64_t hit = 0 ,np = 0 ; 3371for (int64_t w = 0 ;w < words_ ;++ w ) { 3372const uint64_t pm = pmask_ [(size_t ) ((layer * 3 + s )* words_ + w )].load (std::memory_order_relaxed ); 3373hit += (uint64_t )la_pc64 (pm & act [(size_t )w ]); 3374np += (uint64_t )la_pc64 (pm ); 3375 } 3376st_hit_ [s ]+= hit ; 3377st_pred_ [s ]+= np ; 3378 } 3379if (layer == (int64_t )routers_ .size ()- 1 && (++ st_windows_ %100 )== 0 ) { 3380const uint64_t scored = st_layers_ - st_nopred_ ; 3381 std::fprintf (stderr ,"strata lookahead stats: %llu windows, %llu layers scored, %llu without a prediction (%.1f%%); " 3382"%.2f actual non-resident experts/layer;" , 3383 (unsigned long long )st_windows_ , (unsigned long long )scored , (unsigned long long )st_nopred_ , 3384st_layers_ ?100.0 * (double )st_nopred_ / (double )st_layers_ :0.0 , 3385scored ? (double )st_actual_ / (double )scored :0.0 ); 3386 std::fprintf (stderr ," predictor thread %.2f ms/window;" , 3387 (double )busy_us_ .load (std::memory_order_relaxed ) /1000.0 / (double )st_windows_ ); 3388static const int add [3 ]= {0 ,4 ,10 }; 3389for (int s = 0 ;s < 3 ;++ s ) 3390 std::fprintf (stderr ," k=%d: recall %.3f precision %.3f (%.2f predicted/layer);" ,k_ + add [s ], 3391st_actual_ ? (double )st_hit_ [s ] / (double )st_actual_ :0.0 , 3392st_pred_ [s ] ? (double )st_hit_ [s ] / (double )st_pred_ [s ] :0.0 , 3393scored ? (double )st_pred_ [s ] / (double )scored :0.0 ); 3394static const int vm [3 ]= {4 ,8 ,12 }; 3395for (int s = 0 ;s < 3 ;++ s ) 3396 std::fprintf (stderr ," votes top%d: %.2f/layer, covers %.3f of the misses (precision %.3f), %.3f of the PCIe share (%.2f/layer);" , 3397vm [s ],scored ? (double )st_vpred_ [s ] / (double )scored :0.0 , 3398st_actual_ ? (double )st_vhit_ [s ] / (double )st_actual_ :0.0 , 3399st_vpred_ [s ] ? (double )st_vhit_ [s ] / (double )st_vpred_ [s ] :0.0 , 3400st_pch_ ? (double )st_pcov_ [s ] / (double )st_pch_ :0.0 , 3401scored ? (double )st_pch_ / (double )scored :0.0 ); 3402 std::fprintf (stderr ,"\n" ); 3403 } 3404} 3405 3406void RouterLookahead ::run () { 3407 std::vector < float > logits ((size_t ) (8 * n_expert_ )); 3408 std::vector < int32_t > order ((size_t )n_expert_ ); 3409 std::vector < int64_t > want ; 3410 std::vector < float > wconf ;// 149-prefetch: per wanted expert, its best rank's confidence (warm_scored) 3411for (;;) { 3412int64_t layer ,nt ; 3413const int32_t * host_res ;// res_: layer_'s row first (submit leaves it alone while busy_) 3414ForesightSwap * fs ; 3415uint64_t sgen ; 3416 { 3417 std::unique_lock < std::mutex > lk (mu_ ); 3418cv_ .wait (lk , [& ] {return quit_ || pending_ ; }); 3419if (quit_ )return ; 3420pending_ = false; 3421busy_ = true; 3422layer = layer_ ; 3423nt = n_tok_ ; 3424host_res = has_res_ ?res_ .data () :nullptr ; 3425fs = fs_ ; 3426sgen = sub_gen_ ; 3427 } 3428const auto t0 = std::chrono::steady_clock::now (); 3429const int64_t layer0 = layer ; 3430const int depth = src_ != nullptr && !src_ -> read_ahead_open () ?1 :depth_ ;// 149: the gate closed 3431for (int dj = 0 ;dj < depth && layer0 + dj < (int64_t )routers_ .size ();++ dj ) { 3432layer = layer0 + dj ; 3433want .clear (); 3434wconf .clear (); 3435const bool scored = src_ -> wants_scores (); 3436// The router dot is AVX2 (kq_avx2.cpp); a CPU without AVX2 (the experimental older-CPU builds) takes the AVX1 3437// one (kq_avx1.cpp) or, without AVX, the same sums in plain C++. From the Strata_Dirigo fork (rwkeyes): an 3438// AVX-only Xeon E5-2687W died here (vpmovzxwd) on its first request. An estimate only (which experts to 3439// prefetch); the order of the additions differs between the three, the output does not depend on it. 3440#if defined(__aarch64__ )&& !defined(STRATA_GPU_METAL )// Metal (Apple silicon) keeps the plain loop below: its bf16_rows_dot_multi is a stub 3441 strata::kernels::cpu::bf16_rows_dot_multi (routers_ [(size_t )layer ].data (), (int )n_expert_ , (int )n_embd_ , 3442x_ .data (), (int )nt ,logits .data ()); 3443#else 3444if (strata::kernels::cpu::cpu_avx2_ok ()) { 3445 strata::kernels::cpu::bf16_rows_dot_multi (routers_ [(size_t )layer ].data (), (int )n_expert_ , (int )n_embd_ , 3446x_ .data (), (int )nt ,logits .data ()); 3447 }else if (strata::kernels::cpu::cpu_avx1_ok ()) { 3448 strata::kernels::cpu::bf16_rows_dot_multi_avx1 (routers_ [(size_t )layer ].data (), (int )n_expert_ , 3449 (int )n_embd_ ,x_ .data (), (int )nt ,logits .data ()); 3450 }else { 3451// a mul and an add, not std::fma: without an FMA instruction that is a libm call per element (74x 3452// slower on a Xeon E5-2665, measured by the fork) 3453const uint16_t * rw = routers_ [(size_t )layer ].data (); 3454for (int64_t r = 0 ;r < n_expert_ ;++ r ) { 3455const uint16_t * wr = rw + (size_t )r * (size_t )n_embd_ ; 3456for (int64_t t = 0 ;t < nt ;++ t ) { 3457const float * xr = x_ .data ()+ (size_t )t * (size_t )n_embd_ ; 3458float acc = 0.0f ; 3459for (int64_t c = 0 ;c < n_embd_ ;++ c ) { 3460const uint32_t bits = (uint32_t )wr [c ] <<16 ; 3461float wf ; 3462 std::memcpy (& wf ,& bits ,sizeof wf ); 3463acc += wf * xr [c ]; 3464 } 3465logits [(size_t )t * (size_t )n_expert_ + (size_t )r ]= acc ; 3466 } 3467 } 3468 } 3469#endif 3470const int kmax = stats_on_ ? (int ) std::min < int64_t > (k_ + 10 ,n_expert_ ) :k_ ; 3471const int ks [3 ]= {k_ , (int ) std::min < int64_t > (k_ + 4 ,n_expert_ ),kmax }; 3472 std::vector < uint64_t > sm ; 3473if (stats_on_ )sm .assign ((size_t ) (3 * words_ ),0 ); 3474for (int64_t t = 0 ;t < nt ;++ t ) { 3475const float * lt = logits .data ()+ (size_t ) (t * n_expert_ ); 3476for (int64_t e = 0 ;e < n_expert_ ;++ e )order [(size_t )e ]= (int32_t )e ; 3477 std::partial_sort (order .begin (),order .begin ()+ kmax ,order .end (), 3478 [& ](int32_t a ,int32_t b ) {return lt [(size_t )a ]> lt [(size_t )b ]; }); 3479for (int j = 0 ;j < kmax ;++ j ) { 3480const int64_t e = order [(size_t )j ]; 3481if (host_res != nullptr && host_res [(size_t ) ((layer - layer0 )* n_expert_ + e )] >=0 )continue ;// on the GPU 3482if (j < k_ ) { 3483const auto it = std::find (want .begin (),want .end (),e ); 3484// confidence: 1 for a token's top pick down to 1/k_ for its k_-th, the best over the window's tokens, 3485// halved for every layer further ahead than the next (a deeper guess is less often right) 3486const float c = (float ) (k_ - j ) / (float )k_ * (dj == 0 ?1.0f : std::pow (0.5f , (float )dj )); 3487if (it == want .end ()) {want .push_back (e );wconf .push_back (c ); } 3488else if (scored && c > wconf [(size_t ) (it - want .begin ())])wconf [(size_t ) (it - want .begin ())]= c ; 3489 } 3490if (stats_on_ && dj == 0 ) 3491for (int s = 0 ;s < 3 ;++ s ) 3492if (j < ks [s ])sm [(size_t ) (s * words_ + (e >>6 ))] |=1ull << (e & 63 ); 3493 } 3494 } 3495if (stats_on_ && dj == 0 ) { 3496// votes: how many tokens put each non-resident expert in their top k_ 3497 std::vector < std::pair < int ,int32_t >> votes ;// (sum of 64 - rank, expert) 3498for (int64_t t = 0 ;t < nt ;++ t ) { 3499const float * lt = logits .data ()+ (size_t ) (t * n_expert_ ); 3500for (int64_t e = 0 ;e < n_expert_ ;++ e )order [(size_t )e ]= (int32_t )e ; 3501 std::partial_sort (order .begin (),order .begin ()+ k_ ,order .end (), 3502 [& ](int32_t a ,int32_t b ) {return lt [(size_t )a ]> lt [(size_t )b ]; }); 3503for (int j = 0 ;j < k_ ;++ j ) { 3504const int32_t e = order [(size_t )j ]; 3505if (host_res != nullptr && host_res [(size_t ) ((layer - layer0 )* n_expert_ + e )] >=0 )continue ; 3506auto it = std::find_if (votes .begin (),votes .end (), [& ](const auto & v ) {return v .second == e ; }); 3507if (it == votes .end ())votes .emplace_back (64 - j ,e ); 3508else it -> first += 64 - j ; 3509 } 3510 } 3511 std::sort (votes .begin (),votes .end (), [](const auto & a ,const auto & b ) {return a .first > b .first ; }); 3512for (int i = 0 ;i < kVoteN ;++ i ) 3513pvote_ [(size_t ) (layer * kVoteN + i )].store (i < (int )votes .size () ?votes [(size_t )i ].second + 1 :0 , 3514 std::memory_order_relaxed ); 3515for (int64_t i = 0 ;i < 3 * words_ ;++ i ) 3516pmask_ [(size_t ) (layer * 3 * words_ + i )].store (sm [(size_t )i ], std::memory_order_relaxed ); 3517pstamp_ [(size_t )layer ].store (sgen + 1 , std::memory_order_release ); 3518 } 3519if (scored )src_ -> warm_scored (layer ,want .data (),wconf .data (), (int64_t )want .size (),dj + 1 ); 3520else src_ -> warm (layer ,want .data (), (int64_t )want .size ()); 3521if (fs != nullptr && dj == 0 )// the next layer only: a deeper guess is too often wrong to spend a copy on 3522for (const int64_t e :want )fs -> predict (src_ ,layer , (int32_t )e ); 3523predicted_ .fetch_add ((int64_t )want .size (), std::memory_order_relaxed ); 3524 } 3525busy_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 3526 std::memory_order_relaxed ); 3527 { 3528 std::lock_guard < std::mutex > lk (mu_ ); 3529busy_ = false; 3530 } 3531 } 3532} 3533 3534void FileExpertSource ::begin_layer (int64_t layer ,const int32_t * ids ,int64_t k ) { 3535 (void )ids ; 3536 (void )k ; 3537if (!staged ())return ; 3538bool new_window = false; 3539 { 3540 std::lock_guard < std::mutex > lk (stage_mu_ ); 3541if (layer != last_layer_ ) { 3542++ epoch_ ; 3543new_window = layer < last_layer_ ; 3544if (new_window )++ reuse_window_ ; 3545last_layer_ = layer ; 3546io_epoch_ .store (epoch_ , std::memory_order_relaxed );// 149-prefetch: the workers' deadline clock 3547 } 3548 } 3549if (new_window && io_sched_ )io_window_tick (); 3550if (new_window && gate_on_ && tl_decode ) {gate_capacity ();gate_tick (); } 3551} 3552 3553bool FileExpertSource ::transient (int64_t layer ,int64_t expert )const { 3554// the io-prefetch staging of the experts.bin tier is the decode's: the prompt path keeps reading the mapping 3555// (its own read-ahead hints), so this answers as it did without io prefetch - unless STRATA_PROMPT_DIRECT=1 3556// opened the prompt path's own unbuffered descriptors, which only copy_blobs (the stager) reads through 3557if ((role_ptr_ .empty ()&& direct_ .empty ()&& pdirect_ .empty ())|| layer < 0 || expert < 0 || layer >=n_layers_ || 3558expert >=n_expert_ )return false; 3559const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 3560if (complement_ready_ && resident_blob (index )!= nullptr ) 3561return false; 3562return override_ .empty ()|| override_ [index ]== nullptr ; 3563} 3564 3565double FileExpertSource ::cached_share (int64_t samples )const { 3566#if defined(__linux__ ) 3567if (role_ptr_ .empty ()|| unmapped_ || samples <=0 || n_layers_ <=0 || n_expert_ <=0 )return -1.0 ; 3568// an even spread over the (layer, expert) grid, every page of each of the expert's three slices through mincore 3569const int64_t total = (int64_t )n_layers_ * (int64_t )n_expert_ ; 3570const int64_t n = std::min < int64_t > (samples ,total ); 3571uint64_t pages = 0 ,resident = 0 ; 3572 std::vector < unsigned char > vec ; 3573for (int64_t s = 0 ;s < n ;++ s ) { 3574const int64_t idx = std::min < int64_t > (total - 1 , (s * total ) /n + (s * 7919 ) % std::max < int64_t > (1 ,total /n )); 3575const int64_t layer = idx /n_expert_ ,expert = idx %n_expert_ ; 3576if (!transient (layer ,expert ))continue ; 3577for (int r = 0 ;r < 3 ;++ r ) { 3578const size_t i = (size_t ) (3 * layer + r ); 3579if (role_ptr_ [i ]== nullptr || role_bytes_ [i ]== 0 )continue ; 3580const uint8_t * p = role_ptr_ [i ]+ (size_t ) ((uint64_t )expert * role_bytes_ [i ]); 3581const uintptr_t pg = 4096 ,a = (uintptr_t )p & ~(pg - 1 ); 3582const size_t len = (size_t ) ((uintptr_t )p + role_bytes_ [i ]- a ),np = (len + pg - 1 ) /pg ; 3583vec .assign (np ,0 ); 3584if (mincore ((void * )a ,len ,vec .data ())!= 0 )return -1.0 ; 3585pages += np ; 3586for (unsigned char v :vec )resident += v & 1 ; 3587 } 3588 } 3589return pages ? (double )resident / (double )pages :-1.0 ; 3590#else 3591 (void )samples ; 3592return -1.0 ;// no cheap residency query for a file mapping here: the caller keeps its SSD assumption 3593#endif 3594} 3595 3596bool FileExpertSource ::copy_blob (int64_t layer ,int64_t expert ,uint8_t * dst ) { 3597if (base_ == nullptr || dst == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ ) 3598return false; 3599const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 3600const uint64_t bytes = layer_blob_bytes_ [(size_t )layer ]; 3601if (complement_ready_ ) { 3602const uint8_t * held = 3603resident_blob (index ); 3604if (held == nullptr && !override_ .empty ())held = override_ [index ]; 3605if (held != nullptr ) { 3606 std::memcpy (dst ,held , (size_t )bytes ); 3607return true; 3608 } 3609 } 3610const auto t0 = std::chrono::steady_clock::now (); 3611if (!copy_from_files (layer ,expert ,dst ))return false; 3612file_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 3613 std::memory_order_relaxed ); 3614file_read_bytes_ .fetch_add (bytes , std::memory_order_relaxed ); 3615return true; 3616} 3617 3618// pp-opt: the prompt path streams a chunk's experts in file order, so a stager thread's run of jobs is mostly 3619// neighbouring blobs of experts.bin. One read_direct batch merges them into requests of up to 32 MiB (kMerge) where 3620// copy_blob made one ~2 MB request each - and NTFS serves the unbuffered reads of a mapped file one at a time, so the 3621// request size is what sets the rate (see read_direct). The blobs the RAM copy holds are copied as before. 3622bool FileExpertSource ::copy_blobs (const int32_t * layers ,const int32_t * experts ,uint8_t * const * dst ,size_t n ) { 3623if ((direct_ .empty ()&& pdirect_ .empty ())|| n <=1 )return ExpertSource ::copy_blobs (layers ,experts ,dst ,n ); 3624 thread_local std::vector < Fill > fills ; 3625fills .clear (); 3626uint64_t bytes = 0 ; 3627for (size_t i = 0 ;i < n ;++ i ) { 3628const int64_t l = layers [i ],e = experts [i ]; 3629if (base_ == nullptr || dst [i ]== nullptr || l < 0 || e < 0 || l >=n_layers_ || e >=n_expert_ )return false; 3630const size_t index = (size_t )l * (size_t )n_expert_ + (size_t )e ; 3631if (complement_ready_ && 3632 (resident_blob (index )!= nullptr || (!override_ .empty ()&& override_ [index ]!= nullptr ))) { 3633if (!copy_blob (l ,e ,dst [i ]))return false; 3634continue ; 3635 } 3636fills .push_back ({0 ,l ,e ,dst [i ]}); 3637bytes += layer_blob_bytes_ [(size_t )l ]; 3638 } 3639if (fills .empty ())return true; 3640const auto t0 = std::chrono::steady_clock::now (); 3641if (!read_direct (fills .data (),fills .size ())) 3642for (const Fill & f :fills )// a failed batch: each blob on its own (copy_from_files falls back to the mapping) 3643if (!copy_from_files (f .layer ,f .e ,f .dst ))return false; 3644file_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 3645 std::memory_order_relaxed ); 3646file_read_bytes_ .fetch_add (bytes , std::memory_order_relaxed ); 3647return true; 3648} 3649 3650const uint8_t * FileExpertSource ::mapped_blob (int64_t layer ,int64_t expert )const { 3651if (!role_ptr_ .empty ())return nullptr ;// the GGUF in place: no contiguous blob in any file 3652if (unmapped_ )return nullptr ;// pp-opt: drop_mapping closed the view; read_direct reads them 3653if (base_ == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return nullptr ; 3654const size_t i = (size_t )layer ; 3655if (i >=layer_offsets_ .size ()|| i >=layer_blob_bytes_ .size ())return nullptr ; 3656const uint64_t blob_bytes = layer_blob_bytes_ [i ]; 3657if (blob_bytes == 0 || (uint64_t )expert > std::numeric_limits < uint64_t > ::max () /blob_bytes )return nullptr ; 3658const uint64_t expert_offset = (uint64_t )expert * blob_bytes ; 3659const uint64_t layer_offset = layer_offsets_ [i ]; 3660if (layer_offset > mapped_bytes_ || expert_offset > mapped_bytes_ - layer_offset )return nullptr ; 3661const uint64_t offset = layer_offset + expert_offset ; 3662if (blob_bytes > mapped_bytes_ - offset )return nullptr ; 3663return base_ + (size_t )offset ; 3664} 3665 3666uint64_t FileExpertSource ::release (int64_t layer ,int64_t expert ) { 3667#if defined(_WIN32 ) 3668static const bool enabled = [] { 3669const char * v = std::getenv ("STRATA_FILE_RELEASE" ); 3670return v != nullptr && std::strcmp (v ,"1" )== 0 ; 3671 }(); 3672if (!enabled || base_ == nullptr || unmapped_ || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ ) 3673return 0 ; 3674static const uint64_t page = [] { 3675SYSTEM_INFO info {}; 3676GetSystemInfo (& info ); 3677return (uint64_t )info .dwPageSize ; 3678 }(); 3679// These read-only file views are not CUDA-registered. blob() may instead return pinned RAM or an exchange 3680// buffer, so resolve the file spans directly. A shared boundary page stays for the neighboring expert. 3681auto trim = [& ](const uint8_t * p ,uint64_t bytes )-> uint64_t { 3682const uint64_t misalignment = (uintptr_t )p %page ; 3683const uint64_t skip = misalignment == 0 ?0 :page - misalignment ; 3684if (bytes <=skip )return 0 ; 3685const uint64_t whole = (bytes - skip ) /page * page ; 3686if (whole == 0 )return 0 ; 3687SetLastError (ERROR_SUCCESS ); 3688if (!VirtualUnlock ((LPVOID ) (p + (size_t )skip ), (SIZE_T )whole )) { 3689const DWORD error = GetLastError (); 3690// VirtualUnlock trims an unlocked range and reports FALSE / ERROR_NOT_LOCKED for that success. 3691if (error != ERROR_NOT_LOCKED ) { 3692 std::fprintf (stderr ,"FileExpertSource: cannot trim mapped pages for layer %lld expert %lld " 3693"(%llu bytes, Windows error %lu)\n" , 3694 (long long )layer , (long long )expert , (unsigned long long )whole , 3695 (unsigned long )error ); 3696 std::fflush (stderr ); 3697return 0 ; 3698 } 3699 } 3700return whole ;// bytes advised, not a measurement of physical RAM reclaimed 3701 }; 3702if (role_ptr_ .empty ()) { 3703const uint8_t * p = mapped_blob (layer ,expert ); 3704return p == nullptr ?0 :trim (p ,layer_blob_bytes_ [(size_t )layer ]); 3705 } 3706uint64_t bytes = 0 ; 3707for (int r = 0 ;r < 3 ;++ r ) { 3708const size_t i = (size_t ) (3 * layer + r ); 3709bytes += trim (role_ptr_ [i ]+ (size_t ) ((uint64_t )expert * role_bytes_ [i ]),role_bytes_ [i ]); 3710 } 3711return bytes ; 3712#else 3713 (void )layer ; (void )expert ; 3714return 0 ; 3715#endif 3716} 3717 3718bool FileExpertSource ::pin_cache_complement ( 3719const ExpertCache & cache , std::string & err ,bool pin , 3720const std::vector < std::pair < int32_t ,int32_t >>& additional_gpu_pairs ,int64_t lend_from_slot , 3721uint64_t headroom_bytes ,uint64_t budget_bytes ,const std::vector < std::pair < int32_t ,int32_t >>* rank ) { 3722err .clear (); 3723const auto pin_t0 = std::chrono::steady_clock::now (); 3724if (base_ == nullptr ) {err = "FileExpertSource: open the mapped experts before pinning a complement" ;return false; } 3725if (complement_ready_ ) {err = "FileExpertSource: the cache complement is already pinned" ;return false; } 3726if (!cache .valid ()) {err = "FileExpertSource: the GPU expert cache is not open" ;return false; } 3727if (cache .fills ()!= cache .resident ()) { 3728err = "FileExpertSource: the GPU expert cache is not fully filled" ; 3729return false; 3730 } 3731const cudaError_t sync = cudaDeviceSynchronize (); 3732if (sync != cudaSuccess ) { 3733err = std::string ("FileExpertSource: GPU expert cache is not ready: " )+ cudaGetErrorString (sync ); 3734 (void )cudaGetLastError (); 3735return false; 3736 } 3737 3738// The GPU cache's experts, and the bytes each slot's expert takes here (for the lend region below). 3739const int64_t n_slots = cache .slots (); 3740 std::vector < std::pair < int32_t ,int32_t >> primary_gpu_pairs ; 3741 std::vector < int32_t > pair_slot ; 3742 std::vector < uint64_t > slot_bytes ((size_t ) std::max < int64_t > (n_slots ,0 ),0 ); 3743primary_gpu_pairs .reserve ((size_t )cache .resident ()); 3744pair_slot .reserve ((size_t )cache .resident ()); 3745for (int64_t layer = 0 ;layer < n_layers_ ;++ layer ) { 3746for (int64_t expert = 0 ;expert < n_expert_ ;++ expert ) { 3747const int32_t slot = cache .slot_of (layer ,expert ); 3748if (slot == kNotResident )continue ; 3749primary_gpu_pairs .emplace_back ((int32_t )layer , (int32_t )expert ); 3750pair_slot .push_back (slot ); 3751if (slot >=0 && slot < n_slots )slot_bytes [(size_t )slot ]= layer_blob_bytes_ [(size_t )layer ]; 3752 } 3753 } 3754 std::vector < uint64_t > offsets ; 3755uint64_t bytes = 0 ; 3756if (!detail::make_cache_complement_plan (n_layers_ ,n_expert_ ,layer_blob_bytes_ ,primary_gpu_pairs , 3757additional_gpu_pairs ,offsets ,bytes ,err ))return false; 3758#if defined(_WIN32 ) 3759// #467: the GPU cache's pre-fill touched its experts through the mapping (~19 GiB on a 24 GB card), and Windows 3760// counts those file pages in this process's working set, not as available: a 32 GB PC read 0.44 GiB here 3761// (20.7 GiB before the start). Trimmed, they move to the standby list (still cached, counted as available). 3762// Resident mode only: nothing else calls this function. Locked/pinned pages stay; the rest fault back softly. 3763 { 3764uint64_t before = 0 ,after = 0 ; 3765const bool read_before = available_memory_bytes (before ); 3766 (void )SetProcessWorkingSetSize (GetCurrentProcess (), (SIZE_T )- 1 , (SIZE_T )- 1 ); 3767if (read_before && available_memory_bytes (after )) 3768 std::fprintf (stderr ,"FileExpertSource: available RAM %.2f GiB, %.2f GiB after the mapped experts left the " 3769"process working set (#467)\n" , 3770 (double )before /1073741824.0 , (double )after /1073741824.0 ); 3771 } 3772#endif 3773const bool what_fits = budget_bytes == kResidentWhatFits ;// #467: the soft mode's second try 3774int64_t budget_lent = 0 ,budget_lendable = 0 ;// the lend region's slots kept by a budget (below), and its size 3775uint64_t budget_physical = 0 ;// #403: reuse the memory snapshot a budget was sized from 3776uint64_t budget_commit = std::numeric_limits < uint64_t > ::max (); 3777if (budget_bytes > 0 ) { 3778// CS-T: a RAM budget. The complement's experts in `rank` order (the expert profile, hottest first) while 3779// they fit, the rest left on the mapped files; Windows commit capacity also limits the allocation (#730). 3780uint64_t physical = 0 ; 3781if (!available_memory_bytes (physical ,& budget_commit )) { 3782err = budget_automatic_ ?"FileExpertSource: cannot determine available memory for the automatic RAM copy" 3783 :"FileExpertSource: cannot determine available memory for --resident-budget-gib" ; 3784return false; 3785 } 3786budget_physical = physical ; 3787const uint64_t available = std::min (physical ,budget_commit ); 3788const char * limit = budget_commit < physical ?"commit" :"RAM" ; 3789const uint64_t clamped = detail::clamp_resident_budget (budget_bytes ,physical ,budget_commit ,headroom_bytes ); 3790if (budget_bytes > clamped ) { 3791// #403: 256 MiB under the room, so the engine's own allocations after this reading still leave the 3792// headroom (a budget clamped to exactly the room failed the safety check below on a reading a few MB 3793// lower). An unclamped budget is unchanged. 3794// the automatic RAM copy names no flag: none was given (its line used to say --resident-budget-gib) 3795const ResidentBudgetFrom from = what_fits ?ResidentBudgetFrom ::WhatFits 3796 :budget_automatic_ ?ResidentBudgetFrom ::Automatic :ResidentBudgetFrom ::Flag ; 3797 std::fputs (resident_clamp_line (from ,budget_bytes ,limit ,available ,headroom_bytes ,clamped ).c_str (),stderr ); 3798budget_bytes = clamped ; 3799 } 3800 std::vector < uint64_t > ranked (offsets .size (),kNoComplement ); 3801uint64_t at = 0 ; 3802int64_t held = 0 ; 3803if (rank != nullptr ) 3804for (const auto & pr :* rank ) { 3805if (pr .first < 0 || pr .second < 0 || pr .first >=n_layers_ || pr .second >=n_expert_ )continue ; 3806const size_t i = (size_t )pr .first * (size_t )n_expert_ + (size_t )pr .second ; 3807if (offsets [i ]== kNoComplement || ranked [i ]!= kNoComplement )continue ;// on a GPU, or twice 3808const uint64_t b = layer_blob_bytes_ [(size_t )pr .first ]; 3809if (b > budget_bytes - at )continue ; 3810ranked [i ]= at ; 3811at += b ; 3812++ held ; 3813 } 3814if (what_fits && held == 0 ) {// #467: nothing to keep - the caller's plain mmap fallback, not an empty copy 3815err = "FileExpertSource: available memory cannot hold any expert of the complement" ; 3816return false; 3817 } 3818 std::fprintf (stderr ,"FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does " 3819"not hold, by profile rank; the rest are read from the files\n" , 3820 (double )budget_bytes /1073741824.0 , (long long )held , (double )bytes /1073741824.0 ); 3821// The prompt path's lend region under a budget. Until now a budget turned the loan off (`lend_from_slot = -1` 3822// below), so every lent slot's expert was read from the pack during every prompt chunk and again when the slot 3823// was refilled after the prompt - even with room left in the budget. Measured on an RX 6900 XT 16 GB with 3824// --resident-budget-gib 71 and UD-Q4_K_XL: the copy kept all 63.47 GiB of the experts outside the cache, 7.5 3825// GiB of the budget stayed unused, and every agent turn read 0.5-2.6 GB of the 1,231 lent slots' experts (3.6 3826// GiB) from the GGUF (a fresh 17K-token prompt 24 GB). As the unbudgeted path does, take the lend region's 3827// experts from the last slot down (the order the borrowing takes them) while they fit in what the budget has 3828// left; the ones past it keep the file fallback, and `rank` keeps its precedence (the hottest experts first). 3829if (lend_from_slot >=0 && lend_from_slot < n_slots && additional_gpu_pairs .empty ()) { 3830budget_lendable = n_slots - lend_from_slot ; 3831 std::vector < size_t > order ;// the pairs in the lend region, highest slot first 3832for (size_t i = 0 ;i < primary_gpu_pairs .size ();++ i ) 3833if (pair_slot [i ] >=lend_from_slot && pair_slot [i ]< n_slots )order .push_back (i ); 3834 std::sort (order .begin (),order .end (), [& ](size_t a ,size_t b ) {return pair_slot [a ]> pair_slot [b ]; }); 3835const uint64_t at0 = at ; 3836for (size_t i :order ) { 3837const auto & pr = primary_gpu_pairs [i ]; 3838const size_t idx = (size_t )pr .first * (size_t )n_expert_ + (size_t )pr .second ; 3839const uint64_t b = layer_blob_bytes_ [(size_t )pr .first ]; 3840if (b > budget_bytes - at )break ;// a contiguous tail of the region: a short prompt lends only the last few 3841if (ranked [idx ]!= kNoComplement )continue ; 3842ranked [idx ]= at ; 3843at += b ; 3844++ budget_lent ; 3845 } 3846 std::fprintf (stderr ,"FileExpertSource: the prompt path's lend region: %lld of its %lld slots keep their experts " 3847"in RAM too (%.2f GiB of the budget's remaining %.2f GiB)\n" , 3848 (long long )budget_lent , (long long )budget_lendable , (double ) (at - at0 ) /1073741824.0 , 3849 (double ) (budget_bytes - at0 ) /1073741824.0 ); 3850 } 3851offsets .swap (ranked ); 3852bytes = at ; 3853lend_from_slot = -1 ; 3854 } 3855 3856const bool lend = lend_from_slot >=0 && lend_from_slot < n_slots && additional_gpu_pairs .empty (); 3857uint64_t budget = std::numeric_limits < uint64_t > ::max (); 3858if (bytes > 0 || lend ) { 3859// #403: with a budget, the reading it was sized from - a second reading a few MB lower (the engine's own 3860// allocations, the file cache) failed a budget the first one had clamped. (A budget turns `lend` off.) 3861uint64_t physical = budget_physical ; 3862uint64_t commit = budget_commit ; 3863if (physical == 0 && !available_memory_bytes (physical ,& commit )) { 3864err = "FileExpertSource: cannot determine available memory for the resident-memory safety check" ; 3865return false; 3866 } 3867const uint64_t available = std::min (physical ,commit ); 3868budget = available > headroom_bytes ?available - headroom_bytes :0 ; 3869if (bytes > budget ) { 3870char message [320 ]; 3871 std::snprintf (message ,sizeof message , 3872"FileExpertSource: resident complement %.2f GiB exceeds available %s (%.2f GiB) minus the " 3873"%.0f GiB safety headroom" , 3874 (double )bytes /1073741824.0 ,commit < physical ?"commit" :"RAM" , 3875 (double )available /1073741824.0 , (double )headroom_bytes /1073741824.0 ); 3876err = message ; 3877#if defined(__linux__ ) 3878if (std::ifstream mi ("/proc/meminfo" );mi ) { 3879 std::stringstream mt ; 3880mt <<mi .rdbuf (); 3881err += detail::page_cache_hint (mt .str ()); 3882 } 3883#endif 3884return false; 3885 } 3886 } 3887// The prompt path's lend region: its slots' experts are streamed from here during a prompt and copied back into 3888// their slots after it, so the ones that fit are kept here too (from the last slot down: a short prompt lends 3889// only the last few). The rest keep the mapped-file fallback. 3890int64_t keep_from = n_slots ; 3891if (lend ) { 3892keep_from = detail::choose_resident_keep_from (slot_bytes ,bytes ,budget ,lend_from_slot ); 3893if (keep_from < 0 )keep_from = n_slots ; 3894if (keep_from < n_slots ) { 3895 std::vector < std::pair < int32_t ,int32_t >> core ; 3896core .reserve (primary_gpu_pairs .size ()); 3897for (size_t i = 0 ;i < primary_gpu_pairs .size ();++ i ) 3898if (pair_slot [i ]< keep_from )core .push_back (primary_gpu_pairs [i ]); 3899if (!detail::make_cache_complement_plan (n_layers_ ,n_expert_ ,layer_blob_bytes_ ,core , 3900additional_gpu_pairs ,offsets ,bytes ,err ))return false; 3901 } 3902 } 3903 3904// A layer split: generate hands the copy every stage's lend region (`stage_lend_regions`, set before the 3905// call). The prompt path borrows the tail slots of EVERY part's cache, and with `additional_gpu_pairs` 3906// non-empty the single lend region above is off - so without this the borrowed experts sat in neither 3907// VRAM nor RAM during a prompt and came back through page faults from the mapped shards: measured 3908// 2026-10-06 on an RTX 2000 Ada + 5060 Ti rig (17/48 split, IQ3_S mapped from the GGUF, --prefill auto, 3909// one 73K-token prompt) 3.7 GiB read from the NVMe for the one prompt (arena mode reads 1.1 GiB), and one 3910// 8192-token chunk spent 1.5 s of its 3.9 s on host staging (arena: 0.37 s). The regions walk each 3911// stage's highest slots first, as the borrowing does; the whole copy - complement and regions 3912// together - stays within one budget, and experts past it keep the file fallback they had. 3913int64_t stage_lent = 0 ; 3914uint64_t stage_lent_bytes = 0 ; 3915if (!stage_lend_regions_ .empty ()) { 3916if (budget == std::numeric_limits < uint64_t > ::max ()) {// #403: the one reading, taken now 3917uint64_t physical = budget_physical ,commit = budget_commit ; 3918if (physical == 0 && !available_memory_bytes (physical ,& commit )) { 3919err = "FileExpertSource: cannot determine available memory for the stage lend regions" ; 3920return false; 3921 } 3922const uint64_t available = std::min (physical ,commit ); 3923budget = available > headroom_bytes ?available - headroom_bytes :0 ; 3924 } 3925uint64_t cap = budget ;// an explicit --resident-budget-gib caps the whole copy, regions included 3926if (budget_bytes > 0 && budget_bytes != kResidentWhatFits && budget_bytes < cap )cap = budget_bytes ; 3927const uint64_t before = bytes ; 3928stage_lent = detail::append_stage_lend_regions (n_layers_ ,n_expert_ ,layer_blob_bytes_ ,offsets ,bytes ,cap , 3929stage_lend_regions_ ,err ); 3930if (stage_lent < 0 )return false; 3931stage_lent_bytes = bytes - before ; 3932 } 3933 3934void * arena = nullptr ; 3935const uint8_t * host = nullptr ; 3936const uint8_t * device = nullptr ; 3937bool pinned_ok = false; 3938bool paced = false;///< #1250: the pages are taken in steps and page-locked afterwards 3939uint64_t locked = 0 ; 3940uint64_t partial_pin = 0 ;///< CS-T: a registered prefix of a locked arena 3941uint64_t lock_off = 0 ;///< where the working-set lock starts (after the registered prefix) 3942 std::string note ; 3943#if defined(__linux__ ) 3944NumaComplementPlacement numa ;///< STRATA_NUMA_SPLIT step B; inert unless the live pool split on real nodes 3945#endif 3946auto release = [& ]() { 3947if (arena == nullptr )return ; 3948if (pinned_ok ) (void )cudaFreeHost (arena ); 3949else { 3950if (partial_pin > 0 ) (void )cudaHostUnregister (arena ); 3951if (locked > 0 ) strata::platform::unlock_resident ((uint8_t * )arena + lock_off ,locked ); 3952 std::free (arena ); 3953 } 3954arena = nullptr ; 3955 }; 3956#if defined(__linux__ ) 3957// #1250: the cached pages of the model files this source maps (the engine read them itself), given back 3958auto drop_file_cache = [& ]() { 3959auto drop = [](const uint8_t * at ,uint64_t len ,int fd ) { 3960if (at != nullptr && len > 0 ) (void )madvise ((void * )at , (size_t )len ,MADV_DONTNEED ); 3961if (fd >=0 ) (void )posix_fadvise (fd ,0 ,0 ,POSIX_FADV_DONTNEED ); 3962 }; 3963if (maps_ .empty ())drop (base_ ,mapped_bytes_ ,fd_ ); 3964else for (const Map & m :maps_ )drop (m .closed ?nullptr :m .base ,m .bytes ,m .fd ); 3965// the files read at start outside this source (set_extra_drop_files): their pages are already copied to VRAM 3966// or RAM, and they sat on whichever node read them (~2.2 GiB on node 0 measured on the 3090 box) 3967// CBA: whole files by path; a file read at start but not listed stays cached (the per-node free line shows 3968// it), a registry of the files the loaders open if that ever bites 3969for (const std::string & p :extra_drop_files_ ) { 3970const int fd = ::open (p .c_str (),O_RDONLY |O_CLOEXEC ); 3971if (fd >=0 ) { 3972 (void )posix_fadvise (fd ,0 ,0 ,POSIX_FADV_DONTNEED ); 3973 ::close (fd ); 3974 } 3975 } 3976 }; 3977#endif 3978if (bytes > 0 ) { 3979 std::fprintf (stderr ,"FileExpertSource: allocating %.2f GiB %s cache complement\n" , 3980 (double )bytes /1073741824.0 ,pin ?"page-locked" :"pageable resident" ); 3981log_complement_memory ("before complement allocation" ,bytes ); 3982 std::fflush (stderr ); 3983// #1250: the driver takes page-locked pages in one go and cannot wait for the kernel to reclaim file cache: with 3984// the cache of the model files the engine read itself in the way (MemFree low, MemAvailable high) a host was 3985// OOM-killed here. First give those pages back (the engine's own mappings); when what is really free still 3986// does not cover the complement, register it in steps, each only while the RAM left stays above the reserve. 3987// STRATA_PIN_GUARD=0 pages-locks in one go as before, =2 always registers in steps (a test); STRATA_PIN_RESERVE_GIB 3988// is the RAM that must stay above every step (default: the resident headroom, at least 2 GiB) 3989// STRATA_NUMA_SPLIT placement forces the drop and the paced path whatever the guard (STRATA_PIN_GUARD=0 included) 3990const uint64_t pace_reserve = [& ] { 3991const char * v = std::getenv ("STRATA_PIN_RESERVE_GIB" ); 3992return v != nullptr && std::atof (v )> 0 ? (uint64_t ) (std::atof (v )* 1073741824.0 ) 3993 : std::max < uint64_t > (headroom_bytes ,2ull <<30 ); 3994 }(); 3995#if defined(__linux__ ) 3996if (pin ) { 3997static const int guard = [] { 3998const char * v = std::getenv ("STRATA_PIN_GUARD" ); 3999return v == nullptr ?1 : std::atoi (v ); 4000 }(); 4001uint64_t free_now = 0 ; 4002numa .init (offsets ,n_expert_ ,layer_blob_bytes_ ,role_bytes_ );// STRATA_NUMA_SPLIT: placed by the paced loop 4003if (numa .place ) { 4004// the engine's own mapped model pages sit on whichever node read them, and a toucher on a full node 4005// gets its pages from the other one (no local reclaim): give them back first, as the guard=1 path does 4006drop_file_cache (); 4007numa .free_after = NumaComplementPlacement ::node_free (); 4008 std::fprintf (stderr ,"FileExpertSource: NUMA placement: the model files' cached pages were released; " 4009"free after the drop: %s\n" , 4010NumaComplementPlacement ::free_text (numa .free_after ).c_str ()); 4011// CBA: half the pace reserve as each node's share of the headroom; a per-node reserve if one node 4012// carries the host's other allocations 4013numa .check_room (pace_reserve /2 ); 4014if (guard == 0 ) 4015 std::fprintf (stderr ,"FileExpertSource: STRATA_PIN_GUARD=0 overridden: NUMA placement needs the " 4016"paced path\n" ); 4017 } 4018if (guard == 2 || numa .place ) { 4019paced = true; 4020 std::fprintf (stderr ,"FileExpertSource: %s: page-locking the complement in steps\n" , 4021guard == 2 ?"STRATA_PIN_GUARD=2" :"STRATA_NUMA_SPLIT" ); 4022 }else if (guard != 0 && free_memory_bytes (free_now )&& 4023 detail::pin_depends_on_reclaim (free_now ,bytes ,pace_reserve )) { 4024drop_file_cache (); 4025const uint64_t before = free_now ; 4026if (free_memory_bytes (free_now )) 4027 std::fprintf (stderr ,"FileExpertSource: %.2f GiB really free for a %.2f GiB page-locked complement; " 4028"the model files' cached pages were released: %.2f GiB free\n" , 4029 (double )before /1073741824.0 , (double )bytes /1073741824.0 , 4030 (double )free_now /1073741824.0 ); 4031paced = detail::pin_depends_on_reclaim (free_now ,bytes ,pace_reserve ); 4032if (paced ) 4033 std::fprintf (stderr ,"FileExpertSource: the rest comes from reclaimed cache of other files: " 4034"page-locking it in steps, as far as the RAM allows (#1250)\n" ); 4035 } 4036 }else if (strata::kernels::cpu::active_numa_split ().on && !strata::kernels::cpu::active_numa_split ().test ) { 4037 std::fprintf (stderr ,"FileExpertSource: WARNING: NUMA placement FAILED: the complement is not page-locked, " 4038"nothing placed\n" ); 4039 } 4040#endif 4041if (pin && !paced ) { 4042const cudaError_t allocated = cudaHostAlloc (& arena , (size_t )bytes , 4043cudaHostAllocMapped |cudaHostAllocPortable ); 4044if (allocated == cudaSuccess ) { 4045void * alias = nullptr ; 4046const cudaError_t aliased = cudaHostGetDevicePointer (& alias ,arena ,0 ); 4047if (aliased == cudaSuccess && alias != nullptr ) { 4048device = (const uint8_t * )alias ; 4049pinned_ok = true; 4050note = "page-locked and mapped" ; 4051 }else { 4052note = std::string ("no device alias (" )+ cudaGetErrorString (aliased )+ ")" ; 4053 (void )cudaGetLastError (); 4054 (void )cudaFreeHost (arena ); 4055arena = nullptr ; 4056 } 4057 }else { 4058// Refused (the driver's page-locked limit): the same bytes in ordinary memory, locked in the working 4059// set instead, as the arena does - resident either way, only copied by the CPU instead of by DMA. 4060note = std::string ("page-locking refused (" )+ cudaGetErrorString (allocated )+ ")" ; 4061 (void )cudaGetLastError (); 4062arena = nullptr ; 4063 } 4064 } 4065if (arena == nullptr ) { 4066if (!note .empty ()) { 4067 std::fprintf (stderr ,"FileExpertSource: %s; trying pageable memory\n" ,note .c_str ()); 4068log_complement_memory ("before pageable allocation" ,bytes ); 4069 std::fflush (stderr ); 4070 } 4071errno = 0 ; 4072if (paced ) {// page-aligned: the steps are registered on page boundaries 4073#if !defined(_WIN32 ) 4074void * aligned = nullptr ; 4075const uint64_t page = 4096 ; 4076if (posix_memalign (& aligned , (size_t )page , (size_t ) ((bytes + page - 1 ) /page * page ))== 0 )arena = aligned ; 4077#endif 4078#if defined(__linux__ ) 4079// STRATA_NUMA_SPLIT: a 2 MiB huge page would put several slices on its toucher's node, so the arena 4080// takes 4 KiB pages (one call, no VMA split) 4081if (arena != nullptr && numa .place ) { 4082if (madvise (arena , (size_t ) ((bytes + page - 1 ) /page * page ),MADV_NOHUGEPAGE )!= 0 ) 4083 std::fprintf (stderr ,"FileExpertSource: WARNING: madvise(MADV_NOHUGEPAGE) on the complement " 4084"failed (errno %d)\n" ,errno ); 4085 } 4086#endif 4087 }else { 4088arena = std::malloc ((size_t )bytes ); 4089 } 4090if (arena == nullptr ) { 4091const int allocation_errno = errno ; 4092err = "FileExpertSource: pageable resident complement allocation failed (malloc errno " + 4093 std::to_string (allocation_errno )+ ": " + std::strerror (allocation_errno )+ ")" ; 4094if (!note .empty ())err += "; " + note ; 4095log_complement_memory ("after pageable allocation failure" ,bytes ); 4096return false; 4097 } 4098if (pin ) { 4099// CS-T, a RAM budget: its bytes are in profile order, hottest first, so the driver is asked to 4100// register the largest prefix it takes (from the cap down in 2 GiB steps). Those experts can be 4101// read by the GPU over PCIe (--pcie-frac) and copied by DMA; only the rest is locked in the working 4102// set (the registered prefix is page-locked by the driver already - locking it twice made the next 4103// device allocation fail). 4104// opt-in (STRATA_PARTIAL_PIN=1): on the RTX 5070 PC the GPU's PCIe share of the misses measured no 4105// faster than the CPU computing them (7.30 / 7.44 tok/s with 24 / 16 GiB registered against 7.05-7.74 4106// unpinned at a 40 GiB budget), and registering adds startup time and driver memory pressure 4107static const bool partial_on = [] { 4108const char * v = std::getenv ("STRATA_PARTIAL_PIN" ); 4109return v != nullptr && std::atoi (v )!= 0 ; 4110 }(); 4111// at most STRATA_PARTIAL_PIN_GIB (default 24): registering 30 GiB of a 40 GiB arena left the driver 4112// unable to page-lock the prompt path's small buffers afterwards (RTX 5070, WDDM) 4113static const uint64_t pin_cap = [] { 4114const char * v = std::getenv ("STRATA_PARTIAL_PIN_GIB" ); 4115return (uint64_t ) ((v != nullptr && std::atof (v )> 0 ? std::atof (v ) :24.0 )* 1073741824.0 ); 4116 }(); 4117if (paced ) { 4118// #1250: the pages are taken in 1 GiB steps by ordinary page faults (which reclaim file cache as 4119// they need to), each only while the RAM available (the cgroup's room included) stays above the 4120// reserve; then the pages that are there are page-locked in ONE registration (nothing is 4121// allocated then, the driver only pins them), so a blob never straddles two registrations. The 4122// hottest experts come first in the arena: they are the pinned ones; the rest is locked pageable 4123// memory, as when the driver refuses the page-locking. 4124constexpr uint64_t kStep = 1ull <<30 ,kPage = 4096 ; 4125uint64_t got = 0 ; 4126const char * stop = nullptr ; 4127while (got < bytes ) { 4128const uint64_t step = std::min < uint64_t > (kStep ,bytes - got ); 4129uint64_t avail_now = 0 ; 4130if (!available_memory_bytes (avail_now )|| !detail::pin_step_fits (avail_now ,step ,pace_reserve )) { 4131stop = "the RAM left would fall under the reserve" ; 4132break ; 4133 } 4134#if defined(__linux__ ) 4135if (numa .place )numa .touch_step ((uint8_t * )arena ,got ,got + step );// slices on their nodes 4136else 4137#endif 4138for (uint64_t at = got ;at < got + step ;at += kPage ) ((volatile uint8_t * )arena )[at ]= 0 ; 4139got += step ; 4140 } 4141// cut at an expert boundary: a blob that runs past the registered range would be refused by a 4142// cudaMemcpyAsync as not page-locked 4143uint64_t w = got ; 4144for (size_t i = 0 ;i < offsets .size ()&& w < bytes ;++ i ) { 4145if (offsets [i ]== kNoComplement )continue ; 4146const uint64_t b = layer_blob_bytes_ [i / (size_t )n_expert_ ]; 4147if (offsets [i ]< got && offsets [i ]+ b > got ) {w = offsets [i ];break ; } 4148 } 4149if (w > 0 ) { 4150if (cudaHostRegister (arena , (size_t )w ,cudaHostRegisterMapped |cudaHostRegisterPortable )== 4151cudaSuccess ) { 4152void * alias = nullptr ; 4153if (cudaHostGetDevicePointer (& alias ,arena ,0 )== cudaSuccess && alias != nullptr ) { 4154device = (const uint8_t * )alias ; 4155partial_pin = w ; 4156 }else { 4157 (void )cudaGetLastError (); 4158 (void )cudaHostUnregister (arena ); 4159if (stop == nullptr )stop = "no device alias" ; 4160 } 4161 }else { 4162 (void )cudaGetLastError (); 4163if (stop == nullptr )stop = "the driver refused to page-lock it" ; 4164 } 4165 } 4166lock_off = partial_pin ; 4167char msg [240 ]; 4168if (stop != nullptr ) 4169 std::snprintf (msg ,sizeof msg ,"WARNING: only %.2f of %.2f GiB could be page-locked (%s); the rest is " 4170"resident but pageable, so its copies to the GPU go through the CPU (#1250)" , 4171 (double )partial_pin /1073741824.0 , (double )bytes /1073741824.0 ,stop ); 4172else 4173 std::snprintf (msg ,sizeof msg ,"%.2f GiB page-locked after taking the pages in steps" , 4174 (double )partial_pin /1073741824.0 ); 4175note += std::string (note .empty () ?"" :"; " )+ msg ; 4176if (stop != nullptr ) std::fprintf (stderr ,"FileExpertSource: %s\n" ,msg ); 4177#if defined(__linux__ ) 4178// judged on the final state: registered pages no longer move; before the copy fills them 4179if (numa .place )numa .report ((const uint8_t * )arena ,got ,partial_pin ,bytes ,stop ); 4180#endif 4181 }else if (budget_bytes > 0 && partial_on ) { 4182const uint64_t step = 2ull <<30 ; 4183for (uint64_t want = std::min (bytes ,pin_cap );want >=step ;want = want > step ?want - step :0 ) { 4184// cut at an expert boundary: a blob that started inside the registered range and ran past it 4185// would be taken as page-locked by a cudaMemcpyAsync and refused ("adaptive refill failed") 4186uint64_t w = want ; 4187for (size_t i = 0 ;i < offsets .size ();++ i ) { 4188if (offsets [i ]== kNoComplement )continue ; 4189const uint64_t b = layer_blob_bytes_ [i / (size_t )n_expert_ ]; 4190if (offsets [i ]< want && offsets [i ]+ b > want ) {w = offsets [i ];break ; } 4191 } 4192if (w == 0 )break ; 4193if (cudaHostRegister (arena , (size_t )w ,cudaHostRegisterMapped |cudaHostRegisterPortable )== 4194cudaSuccess ) { 4195void * alias = nullptr ; 4196if (cudaHostGetDevicePointer (& alias ,arena ,0 )== cudaSuccess && alias != nullptr ) { 4197device = (const uint8_t * )alias ; 4198partial_pin = w ; 4199 }else { 4200 (void )cudaGetLastError (); 4201 (void )cudaHostUnregister (arena ); 4202 } 4203break ; 4204 } 4205 (void )cudaGetLastError (); 4206if (want <=step )break ; 4207 } 4208char msg [160 ]; 4209 std::snprintf (msg ,sizeof msg ,"%.2f GiB of it registered for the GPU (the hottest)" , 4210 (double )partial_pin /1073741824.0 ); 4211note += std::string ("; " )+ msg ; 4212 } 4213if (!paced )lock_off = partial_pin ; 4214// (paced: lock_off was set above) 4215const strata::platform::LockResult lr = 4216lock_off < bytes ? strata::platform::lock_resident ((uint8_t * )arena + lock_off ,bytes - lock_off ) 4217 : strata::platform::LockResult {true,0 ,"" }; 4218locked = lr .locked_bytes ; 4219note += (note .empty () ?"" :"; " )+ lr .note ; 4220 } 4221 } 4222host = (const uint8_t * )arena ; 4223 } 4224 4225// Copied layer by layer on a few threads: the page faults of the mapped file are the cost, and they overlap. 4226#if !defined(_WIN32 ) 4227const long page_size = sysconf (_SC_PAGESIZE ); 4228if (page_size <=0 ) { 4229err = "FileExpertSource: cannot determine page size for mapped-page release" ; 4230release (); 4231return false; 4232 } 4233#endif 4234 std::atomic < int64_t > next_layer {0 },layers_done {0 }; 4235 std::atomic < uint64_t > copied {0 }; 4236 std::atomic < bool > failed {false}; 4237 std::mutex fail_mu ; 4238const auto copy_t0 = std::chrono::steady_clock::now (); 4239 std::string fail_msg ; 4240auto fail = [& ](const std::string & m ) { 4241 std::lock_guard < std::mutex > lock (fail_mu ); 4242if (fail_msg .empty ())fail_msg = m ; 4243failed .store (true); 4244 }; 4245auto worker = [& ]() { 4246for (;;) { 4247const int64_t layer = next_layer .fetch_add (1 ); 4248if (layer >=n_layers_ || failed .load ())return ; 4249const uint64_t blob_bytes = layer_blob_bytes_ [(size_t )layer ]; 4250 std::vector < Fill > batch ;// #286, unbuffered: 32 blobs' reads in flight at once, merged where near 4251auto flush = [& ]() { 4252if (batch .empty ())return true; 4253bool ok = read_direct (batch .data (),batch .size ()); 4254for (size_t i = 0 ; !ok && i < batch .size ();++ i ) 4255if (!copy_from_files (batch [i ].layer ,batch [i ].e ,batch [i ].dst ))return false; 4256copied .fetch_add (blob_bytes * (uint64_t )batch .size ()); 4257batch .clear (); 4258return true; 4259 }; 4260if (direct_ .empty ()) {// mapped reads: ask for the layer's blobs before copying them 4261 std::vector < std::pair < int32_t ,int32_t >> ahead ; 4262for (int64_t expert = 0 ;expert < n_expert_ ;++ expert ) 4263if (offsets [(size_t )layer * (size_t )n_expert_ + (size_t )expert ]!= kNoComplement ) 4264ahead .emplace_back ((int32_t )layer , (int32_t )expert ); 4265 (void )advise_pairs (ahead .data (), (int64_t )ahead .size ()); 4266 } 4267for (int64_t expert = 0 ;expert < n_expert_ ;++ expert ) { 4268const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 4269const uint64_t offset = offsets [index ]; 4270if (offset == kNoComplement )continue ; 4271if (offset > bytes || blob_bytes > bytes - offset ) { 4272fail ("FileExpertSource: invalid blob bounds while building the cache complement" ); 4273return ; 4274 } 4275uint8_t * dst = (uint8_t * )host + (size_t )offset ; 4276if (!direct_ .empty ()) { 4277batch .push_back ({0 ,layer ,expert ,dst }); 4278if (batch .size ()== 32 && !flush ()) { 4279fail ("FileExpertSource: an expert could not be read while building the cache complement" ); 4280return ; 4281 } 4282continue ; 4283 } 4284if (!copy_from_files (layer ,expert ,dst )) { 4285fail ("FileExpertSource: invalid blob bounds while building the cache complement" ); 4286return ; 4287 } 4288copied .fetch_add (blob_bytes ); 4289 } 4290if (!flush ()) { 4291fail ("FileExpertSource: an expert could not be read while building the cache complement" ); 4292return ; 4293 } 4294#if !defined(_WIN32 ) 4295if (role_ptr_ .empty ()) {// experts.bin; the GGUF in place leaves its pages to the OS 4296const uint64_t layer_offset = layer_offsets_ [(size_t )layer ]; 4297const uint64_t layer_bytes = blob_bytes * (uint64_t )n_expert_ ; 4298const uint64_t layer_end = layer_offset + layer_bytes ; 4299const uint64_t page = (uint64_t )page_size ; 4300const uint64_t advice_start = layer_offset - layer_offset %page ; 4301const uint64_t end_remainder = layer_end %page ; 4302const uint64_t extra = end_remainder == 0 ?0 :page - end_remainder ; 4303const uint64_t advice_end = extra > mapped_bytes_ - layer_end ?mapped_bytes_ :layer_end + extra ; 4304if (advice_end > advice_start && 4305madvise ((void * ) (base_ + (size_t )advice_start ), (size_t ) (advice_end - advice_start ),MADV_DONTNEED )!= 0 ) { 4306fail ("FileExpertSource: madvise could not release mapped expert layer " + std::to_string (layer )); 4307return ; 4308 } 4309#if !defined(__APPLE__ )// macOS has no posix_fadvise; the madvise above already released the mapping 4310if (posix_fadvise (fd_ , (off_t )layer_offset , (off_t )layer_bytes ,POSIX_FADV_DONTNEED )!= 0 ) { 4311fail ("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string (layer )); 4312return ; 4313 } 4314#endif 4315 } 4316#endif 4317const int64_t done = layers_done .fetch_add (1 )+ 1 ; 4318#if defined(_WIN32 ) 4319// R5070: the copy reads through the mapped view, and Windows counts those file pages in this process's working 4320// set, not as available: on the owner's 64 GB PC (8 GiB headroom asked for) available RAM fell to 0.9 GiB for 4321// ~10 s during the copy. Every 4 layers the mapped pages go to the standby list (VirtualUnlock on pages that 4322// are not locked does exactly that; the same call runs once after the copy below). No data changes. 4323if (done %4 == 0 && direct_ .empty ()&& maps_ .empty ()&& !unmapped_ ) (void )VirtualUnlock ((LPVOID )base_ , (SIZE_T )mapped_bytes_ ); 4324if (done %4 == 0 && direct_ .empty ())for (const Map & m :maps_ )if (!m .closed ) (void )VirtualUnlock ((LPVOID )m .base , (SIZE_T )m .bytes ); 4325#endif 4326if (done %8 == 0 || done == n_layers_ ) 4327 std::fprintf (stderr ,"FileExpertSource: copied cache complement through layer %lld/%lld (%.2f GiB, %.0f s)\n" , 4328 (long long )done , (long long )n_layers_ , (double )copied .load () /1073741824.0 , 4329 std::chrono::duration < double > (std::chrono::steady_clock::now ()- copy_t0 ).count ()); 4330 } 4331 }; 4332 { 4333const int threads = (int ) std::max < int64_t > (1 , std::min < int64_t > (6 ,n_layers_ )); 4334 std::vector < std::thread > pool ; 4335for (int i = 1 ;i < threads ;++ i )pool .emplace_back (worker ); 4336worker (); 4337for (auto & t :pool )t .join (); 4338 } 4339 std::fflush (stderr ); 4340if (failed .load ()) { 4341err = fail_msg ; 4342release (); 4343return false; 4344 } 4345#if defined(_WIN32 ) 4346// The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the 4347// standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED). 4348// Not with the view closed (begin_startup_unbuffered): its range may hold other memory by now. 4349if (maps_ .empty ()&& !unmapped_ ) (void )VirtualUnlock ((LPVOID )base_ , (SIZE_T )mapped_bytes_ ); 4350for (const Map & m :maps_ )if (!m .closed ) (void )VirtualUnlock ((LPVOID )m .base , (SIZE_T )m .bytes ); 4351#endif 4352if (std::getenv ("STRATA_VERIFY_COMPLEMENT" )!= nullptr && host != nullptr && bytes > 0 ) { 4353// tests: the copy's checksum (FNV-1a of each 1 GiB piece on its own thread, then of those), any reader 4354constexpr uint64_t kPiece = 1ull <<30 ; 4355const size_t pieces = (size_t ) ((bytes + kPiece - 1 ) /kPiece ); 4356 std::vector < uint64_t > ph (pieces ,0 ); 4357 std::atomic < size_t > next_piece {0 }; 4358auto hash_work = [& ] { 4359for (size_t i ; (i = next_piece .fetch_add (1 ))< pieces ;) 4360ph [i ]= fnv1a64 (host + (size_t ) (i * kPiece ), std::min < uint64_t > (kPiece ,bytes - i * kPiece )); 4361 }; 4362 std::vector < std::thread > hth ; 4363for (int t = 1 ;t < 8 ;++ t )hth .emplace_back (hash_work ); 4364hash_work (); 4365for (auto & t :hth )t .join (); 4366uint64_t h = fnv1a64 ((const uint8_t * )offsets .data (), (uint64_t ) (offsets .size ()* sizeof (uint64_t ))); 4367h = fnv1a64 ((const uint8_t * )ph .data (), (uint64_t ) (ph .size ()* sizeof (uint64_t )),h ); 4368 std::fprintf (stderr ,"FileExpertSource: cache complement checksum %016llx (%.2f GiB, its offsets included)\n" , 4369 (unsigned long long )h , (double )bytes /1073741824.0 ); 4370 } 4371 4372complement_arena_ = arena ; 4373complement_host_ = host ; 4374complement_device_ = device ; 4375complement_bytes_ = bytes ; 4376complement_offsets_ = std::move (offsets ); 4377complement_pinned_ = (pinned_ok || partial_pin > 0 )&& bytes > 0 ; 4378complement_pin_limit_ = pinned_ok ?bytes :partial_pin ; 4379complement_registered_ = !pinned_ok && partial_pin > 0 ; 4380// a paced registration that covers the whole arena is as good as a cudaHostAlloc'd one 4381complement_partial_ = complement_registered_ && !(paced && partial_pin >=bytes ); 4382complement_locked_ = locked ; 4383complement_lock_off_ = lock_off ; 4384complement_lent_slots_ = lend ?n_slots - keep_from :budget_lent ;// a budget keeps its own tail of the region 4385complement_lent_slots_ += stage_lent ;// and the split stages' regions: pairs the copy kept of them 4386complement_ready_ = true; 4387 std::fprintf (stderr ,"FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB in %.0f s%s%s\n" , 4388complement_pinned_ ?"mapped pinned" :pin ?"locked resident" :"pageable resident" , 4389 (double )resident_bytes () /1073741824.0 , (double )pinned_bytes () /1073741824.0 , 4390 std::chrono::duration < double > (std::chrono::steady_clock::now ()- pin_t0 ).count (), 4391note .empty () ?"" :"; " ,note .c_str ()); 4392const int64_t lendable_all = lend ?n_slots - lend_from_slot :budget_lendable ;// 0: no lend region at all 4393if (lendable_all > 0 ) 4394 std::fprintf (stderr ,"FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM " 4395"too%s\n" , (long long ) (lend ?n_slots - keep_from :budget_lent ), (long long )lendable_all , 4396 (lend ?n_slots - keep_from :budget_lent )< lendable_all 4397 ?" (the others are read from the file when lent: not enough RAM for them)" :"" ); 4398if (lendable_all > 0 && (lend ?n_slots - keep_from :budget_lent )< lendable_all ) { 4399// #1389: below full coverage the uncovered experts are read from the pack during a long prompt (a 74K prompt 4400// routes through nearly all experts, so the misses repeat). The reporter measured 18% uncovered = -26% prompt 4401// speed on a gfx1100; short prompts barely touch them. A warning, not a refusal. 4402const long long lendable = (long long )lendable_all ; 4403const long long missing = lendable - (long long ) (lend ?n_slots - keep_from :budget_lent ); 4404 std::fprintf (stderr ,"FileExpertSource: WARNING: %lld of %lld lendable slots (%.0f%%) will read their experts from the pack " 4405"during a long prompt; expect a slower prompt read on 50K+ token prompts (one measurement: 18%% uncovered " 4406"cost 26%%). %s and restart; the line above should read N of N.\n" ,missing ,lendable , 4407100.0 * (double )missing / (double ) std::max < long long > (1 ,lendable ), 4408lend ?"Free RAM or lower STRATA_RESIDENT_HEADROOM_GIB (now the RAM left free at start)" 4409 :budget_automatic_ ?"Free more RAM for the automatic RAM copy (the lend region comes after the ranked experts)" 4410 :"Raise --resident-budget-gib (the lend region comes after the ranked experts)" ); 4411 } 4412if (!stage_lend_regions_ .empty ()) { 4413int64_t offered = 0 ; 4414for (const auto & region :stage_lend_regions_ )offered += (int64_t )region .size (); 4415 std::fprintf (stderr ,"FileExpertSource: the split stages lend %lld slots to the prompt path: %lld keep " 4416"their experts in RAM too (%.2f GiB)%s\n" , 4417 (long long )offered , (long long )stage_lent , (double )stage_lent_bytes /1073741824.0 , 4418stage_lent < offered ?" (the rest are read from the file when lent: not enough RAM for them)" :"" ); 4419 } 4420if (!additional_gpu_pairs .empty ()) { 4421 std::fprintf (stderr ,"FileExpertSource: %zu verified additional-GPU experts remain on the mmap fallback\n" , 4422additional_gpu_pairs .size ()); 4423 } 4424 std::fflush (stderr ); 4425return true; 4426} 4427 4428const uint8_t * FileExpertSource ::resident_blob (size_t index )const { 4429if (exchange_storage_ .active ())return exchange_storage_ .resident (index ).host ; 4430return detail::cache_complement_blob_or_fallback (index ,complement_offsets_ ,complement_host_ ,nullptr ); 4431} 4432 4433bool FileExpertSource ::has_resident (int64_t layer ,int64_t expert )const { 4434if (!complement_ready_ || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return false; 4435const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 4436return resident_blob (index )!= nullptr ; 4437} 4438 4439bool FileExpertSource ::reserve_exchanges (int64_t n , std::string & err ,int64_t bounce ) { 4440err .clear (); 4441if (n <=xstage_cap_ )return true; 4442if (!staged_ .empty ()) {err = "FileExpertSource: exchange buffers are in use" ;return false; } 4443if (exchange_storage_ .active ()) { 4444err = "FileExpertSource: reserve maximum exchange capacity before enabling rotation" ; 4445return false;// the original exchange allocation can now contain live resident experts 4446 } 4447uint64_t blob = 0 ; 4448for (const uint64_t b :layer_blob_bytes_ )blob = std::max (blob ,b ); 4449if (blob == 0 || n <=0 ) {err = "FileExpertSource: no expert geometry for the exchange buffers" ;return false; } 4450if (xstage_ != nullptr ) { 4451if (xstage_pinned_ ) (void )cudaFreeHost (xstage_ ); 4452else std::free (xstage_ ); 4453xstage_ = nullptr ; 4454xstage_cap_ = 0 ; 4455 } 4456if ((uint64_t )n > std::numeric_limits < size_t > ::max () /blob ) { 4457err = "FileExpertSource: exchange allocation size overflow" ;return false; 4458 } 4459const char * rotate_env = std::getenv ("STRATA_EXCHANGE_ROTATE" ); 4460const bool requested = rotate_env && std::strcmp (rotate_env ,"1" )== 0 ; 4461// layers of several block sizes (a GGUF's mixed i-quants): spares of every size, see ExchangeStorage 4462bounce = std::max < int64_t > (0 , std::min (bounce ,n )); 4463const uint64_t rotate_total = detail::ExchangeStorage ::exchange_bytes_needed (layer_blob_bytes_ , (size_t )n , (size_t )bounce ); 4464const bool eligible = requested && rotate_total != 0 && rotate_total <= std::numeric_limits < size_t > ::max ()&& 4465complement_pinned_ && !complement_partial_ && 4466complement_host_ && complement_device_ && complement_bytes_ > 0 ; 4467const size_t total = eligible ? (size_t )rotate_total : (size_t )n * (size_t )blob ; 4468void * p = nullptr ; 4469if (cudaHostAlloc (& p ,total ,eligible ?cudaHostAllocMapped :cudaHostAllocDefault )== cudaSuccess && p != nullptr ) { 4470xstage_pinned_ = true; 4471 }else { 4472 (void )cudaGetLastError (); 4473p = std::malloc (total ); 4474xstage_pinned_ = false; 4475if (p == nullptr ) {err = "FileExpertSource: cannot allocate the exchange buffers" ;return false; } 4476 } 4477xstage_ = (uint8_t * )p ; 4478xstage_cap_ = n ; 4479xstage_blob_ = blob ; 4480if (requested ) { 4481 std::string reason = "requires a fully mapped/pinned RAM complement" ; 4482void * device = nullptr ; 4483if (eligible && xstage_pinned_ && cudaHostGetDevicePointer (& device ,p ,0 )== cudaSuccess && device ) { 4484try { 4485 std::vector < uint64_t > sizes (complement_offsets_ .size (),0 ); 4486for (size_t i = 0 ;i < sizes .size ();++ i ) { 4487const size_t layer = n_expert_ > 0 ?i / (size_t )n_expert_ :0 ; 4488sizes [i ]= layer < layer_blob_bytes_ .size () ?layer_blob_bytes_ [layer ] :0 ; 4489 } 4490if (exchange_storage_ .initialize_sized (complement_offsets_ ,sizes , (uint8_t * )complement_host_ ,complement_device_ , 4491complement_bytes_ ,xstage_ , (const uint8_t * )device , (uint64_t )total , (size_t )n , (size_t )bounce ,reason )) { 4492 std::fprintf (stderr ,"FileExpertSource: exchange buffer rotation enabled: %lld buffers in %zu block sizes " 4493"(largest %llu bytes, %.2f GiB page-locked); no host commit memcpy\n" , 4494 (long long )n ,exchange_storage_ .block_sizes (), (unsigned long long )blob , 4495 (double )total /1073741824.0 ); 4496 } 4497 }catch (const std::bad_alloc & ) {reason = "buffer metadata allocation failed" ; } 4498 }else if (eligible ) { 4499 (void )cudaGetLastError (); 4500reason = "exchange buffers could not be pinned and mapped" ; 4501 } 4502if (!exchange_storage_ .active ()) 4503 std::fprintf (stderr ,"FileExpertSource: exchange rotation unavailable; retaining copy path: %s\n" ,reason .c_str ()); 4504 } 4505return true; 4506} 4507 4508uint8_t * FileExpertSource ::exchange_buffer (int64_t q ,int64_t layer )const { 4509if (xstage_ == nullptr || q < 0 || q >=xstage_cap_ )return nullptr ; 4510if (exchange_storage_ .active ()) 4511return layer >=0 && layer < n_layers_ ?exchange_storage_ .spare ((size_t )q , (size_t )layer_blob_bytes_ [(size_t )layer ]).host 4512 :exchange_storage_ .spare ((size_t )q ).host ; 4513return xstage_ + (size_t )q * (size_t )xstage_blob_ ; 4514} 4515 4516bool FileExpertSource ::stage_exchange (int64_t layer ,int64_t in ,int64_t out ,int64_t q ) { 4517if (out < 0 || out >=n_expert_ || !has_resident (layer ,in )|| has_resident (layer ,out )|| 4518exchange_buffer (q ,layer )== nullptr )return false; 4519const size_t i_in = (size_t )layer * (size_t )n_expert_ + (size_t )in ; 4520const size_t i_out = (size_t )layer * (size_t )n_expert_ + (size_t )out ; 4521if (override_ .empty ())override_ .assign ((size_t )blobs_ ,nullptr ); 4522if (override_ [i_out ]!= nullptr )return false; 4523for (const Exchange & x :staged_ ) 4524if (x .in == i_in || x .q == q )return false; 4525override_ [i_out ]= exchange_buffer (q ,layer ); 4526staged_ .push_back ({i_in ,i_out ,q ,layer_blob_bytes_ [(size_t )layer ]}); 4527return true; 4528} 4529 4530bool FileExpertSource ::soft_commit_exchanges () { 4531if (staged_ .empty ())return true; 4532if (exchange_storage_ .active ()|| !xstage_pinned_ || xstage_ == nullptr || !complement_pinned_ || complement_device_ == nullptr ) 4533return false; 4534if (xstage_dev_ == nullptr ) { 4535void * d = nullptr ; 4536if (cudaHostGetDevicePointer (& d ,xstage_ ,0 )!= cudaSuccess || d == nullptr ) { (void )cudaGetLastError ();return false; } 4537xstage_dev_ = (const uint8_t * )d ; 4538 } 4539if (soft_in_ .empty ())soft_in_ .assign ((size_t )blobs_ ,SIZE_MAX ); 4540for (const Exchange & x :staged_ )soft_in_ [x .out ]= x .in ; 4541return true; 4542} 4543 4544void FileExpertSource ::fs_hold_staged (bool hold ) { 4545ForesightSwap * fs = fs_swap_ .load (std::memory_order_acquire ); 4546if (fs == nullptr || n_expert_ <=0 )return ; 4547for (const Exchange & x :staged_ ) 4548for (const size_t i : {x .in ,x .out }) { 4549const int64_t layer = (int64_t ) (i / (size_t )n_expert_ ); 4550const int32_t expert = (int32_t ) (i % (size_t )n_expert_ ); 4551if (hold )fs -> hold (layer ,expert ); 4552else fs -> unhold (layer ,expert ); 4553 } 4554} 4555 4556int64_t FileExpertSource ::commit_exchanges () { 4557int64_t n = 0 ; 4558fs_hold_staged (true);// #2134: both experts' bytes move (in's place takes out's bytes, out leaves its buffer) 4559for (const Exchange & x :staged_ ) 4560if (!soft_in_ .empty ())soft_in_ [x .out ]= SIZE_MAX ; 4561for (const Exchange & x :staged_ ) { 4562const uint8_t * src = override_ [x .out ]; 4563if (exchange_storage_ .active ()) { 4564if (!exchange_storage_ .commit (x .in ,x .out , (size_t )x .q ,src , (size_t )x .bytes )) { 4565// Admitting the GPU swap after a failed RAM ownership update would lose an expert. 4566 std::fprintf (stderr ,"FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n" ); 4567 std::abort (); 4568 } 4569++ n ; 4570override_ [x .out ]= nullptr ; 4571continue ; 4572 } 4573const uint64_t at = complement_offsets_ [x .in ]; 4574if (src != nullptr && at != kNoComplement && at <=complement_bytes_ && x .bytes <=complement_bytes_ - at && 4575complement_host_ != nullptr ) { 4576 std::memcpy ((uint8_t * )complement_host_ + (size_t )at ,src , (size_t )x .bytes ); 4577if (detail::exchange_cache_complement (complement_offsets_ ,x .in ,x .out ))++ n ; 4578 } 4579override_ [x .out ]= nullptr ; 4580 } 4581fs_hold_staged (false); 4582staged_ .clear (); 4583exchanges_ += n ; 4584return n ; 4585} 4586 4587bool FileExpertSource ::replace_resident (int64_t layer ,int64_t in ,int64_t out ) { 4588if (!complement_ready_ || complement_host_ == nullptr || exchange_storage_ .active ()|| !staged_ .empty ()|| 4589layer < 0 || layer >=n_layers_ || in < 0 || out < 0 || in >=n_expert_ || out >=n_expert_ || in == out ) 4590return false; 4591const size_t i_in = (size_t )layer * (size_t )n_expert_ + (size_t )in ; 4592const size_t i_out = (size_t )layer * (size_t )n_expert_ + (size_t )out ; 4593if (i_in >=complement_offsets_ .size ()|| i_out >=complement_offsets_ .size ())return false; 4594if (!override_ .empty ()&& (override_ [i_in ]!= nullptr || override_ [i_out ]!= nullptr ))return false; 4595const uint64_t at = complement_offsets_ [i_out ],bytes = layer_blob_bytes_ [(size_t )layer ]; 4596if (at == kNoComplement || complement_offsets_ [i_in ]!= kNoComplement || at > complement_bytes_ || 4597bytes > complement_bytes_ - at )return false; 4598 (void )at ; 4599// read beside the copy first: a failed read leaves `out` where it was 4600if (ram_adapt_buf_ .size ()< (size_t )bytes )ram_adapt_buf_ .resize ((size_t )bytes ); 4601const auto t0 = std::chrono::steady_clock::now (); 4602if (!copy_from_files (layer ,in ,ram_adapt_buf_ .data ()))return false; 4603file_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 4604 std::memory_order_relaxed ); 4605file_read_bytes_ .fetch_add (bytes , std::memory_order_relaxed ); 4606return install_resident (layer ,in ,out ,ram_adapt_buf_ .data ()); 4607} 4608 4609bool FileExpertSource ::replace_resident_staged (int64_t layer ,int64_t in ,int64_t out ) { 4610if (!complement_ready_ || complement_host_ == nullptr || exchange_storage_ .active ()|| !staged_ .empty ()|| 4611layer < 0 || layer >=n_layers_ || in < 0 || out < 0 || in >=n_expert_ || out >=n_expert_ || in == out ) 4612return false; 4613const size_t i_in = (size_t )layer * (size_t )n_expert_ + (size_t )in ; 4614const size_t i_out = (size_t )layer * (size_t )n_expert_ + (size_t )out ; 4615if (i_in >=complement_offsets_ .size ()|| i_out >=complement_offsets_ .size ())return false; 4616if (!override_ .empty ()&& (override_ [i_in ]!= nullptr || override_ [i_out ]!= nullptr ))return false; 4617const uint64_t at = complement_offsets_ [i_out ],bytes = layer_blob_bytes_ [(size_t )layer ]; 4618if (at == kNoComplement || complement_offsets_ [i_in ]!= kNoComplement || at > complement_bytes_ || 4619bytes > complement_bytes_ - at || bytes > stage_blob_ )return false; 4620ForesightSwap * fs = fs_swap_ .load (std::memory_order_acquire ); 4621bool moved = false; 4622 { 4623// held across the copy: claim_stage cannot hand the buffer to another blob meanwhile 4624 std::lock_guard < std::mutex > lk (stage_mu_ ); 4625const auto it = stage_of_ .find ((int64_t )i_in ); 4626if (it == stage_of_ .end ()|| stage_busy_ [it -> second ]|| stage_key_ [it -> second ]!= (int64_t )i_in )return false; 4627if (fs != nullptr )fs -> hold (layer , (int32_t )out ); 4628 std::memcpy ((uint8_t * )complement_host_ + (size_t )at ,stage_buf_ [it -> second ].get (), (size_t )bytes ); 4629moved = detail::exchange_cache_complement (complement_offsets_ ,i_out ,i_in ); 4630if (fs != nullptr )fs -> unhold (layer , (int32_t )out ); 4631 } 4632if (moved ) {++ ram_adapts_ ;++ ram_staged_ ; } 4633return moved ; 4634} 4635 4636// `in`'s bytes (src) into `out`'s place of the compact copy, and the two offsets swapped - the checks again, as the caller 4637// may have read `src` a while ago (149-prefetch: ram_install) 4638bool FileExpertSource ::install_resident (int64_t layer ,int64_t in ,int64_t out ,const uint8_t * src ) { 4639if (!complement_ready_ || complement_host_ == nullptr || exchange_storage_ .active ()|| !staged_ .empty ()|| 4640layer < 0 || layer >=n_layers_ || in < 0 || out < 0 || in >=n_expert_ || out >=n_expert_ || in == out || src == nullptr ) 4641return false; 4642const size_t i_in = (size_t )layer * (size_t )n_expert_ + (size_t )in ; 4643const size_t i_out = (size_t )layer * (size_t )n_expert_ + (size_t )out ; 4644if (i_in >=complement_offsets_ .size ()|| i_out >=complement_offsets_ .size ())return false; 4645if (!override_ .empty ()&& (override_ [i_in ]!= nullptr || override_ [i_out ]!= nullptr ))return false; 4646const uint64_t at = complement_offsets_ [i_out ],bytes = layer_blob_bytes_ [(size_t )layer ]; 4647if (at == kNoComplement || complement_offsets_ [i_in ]!= kNoComplement || at > complement_bytes_ || 4648bytes > complement_bytes_ - at )return false; 4649// #2134: a Foresight slot may be copying out of `out`'s place right now; it is dropped (never served) before the place is rewritten 4650ForesightSwap * fs = fs_swap_ .load (std::memory_order_acquire ); 4651if (fs != nullptr )fs -> hold (layer , (int32_t )out ); 4652 std::memcpy ((uint8_t * )complement_host_ + (size_t )at ,src , (size_t )bytes ); 4653const bool moved = detail::exchange_cache_complement (complement_offsets_ ,i_out ,i_in ); 4654if (fs != nullptr )fs -> unhold (layer , (int32_t )out ); 4655if (!moved )return false; 4656++ ram_adapts_ ; 4657return true; 4658} 4659 4660// ---- 149-prefetch: staged promotions. The read of `in` runs on this source's own thread (one at a time: the drive's 4661// queue stays the decode's first); the install is the decode thread's (ram_install, at a window boundary). 4662bool FileExpertSource ::ram_stage (int64_t layer ,int64_t in ,int64_t out ) { 4663if (!complement_ready_ || complement_host_ == nullptr || layer < 0 || layer >=n_layers_ || in < 0 || out < 0 || 4664in >=n_expert_ || out >=n_expert_ || in == out ) 4665return false; 4666 { 4667 std::lock_guard < std::mutex > lk (ram_mu_ ); 4668static const size_t cap = [] { 4669const char * v = std::getenv ("STRATA_RAM_ADAPT_QUEUE" ); 4670return v != nullptr ? (size_t ) std::max (1 , std::atoi (v )) : (size_t )64 ; 4671 }(); 4672if (ram_jobs_ .size () >=cap )return false; 4673for (const auto & j :ram_jobs_ ) 4674if (j -> layer == layer && (j -> in == in || j -> out == out || j -> in == out || j -> out == in ))return false; 4675auto j = std::make_unique < RamJob > (); 4676j -> layer = layer ;j -> in = in ;j -> out = out ;j -> state = 0 ; 4677ram_jobs_ .push_back (std::move (j )); 4678if (!ram_thread_ .joinable ()) { 4679ram_quit_ = false; 4680ram_thread_ = std::thread ([this ] {ram_worker (); }); 4681 } 4682 } 4683ram_cv_ .notify_one (); 4684return true; 4685} 4686 4687bool FileExpertSource ::ram_queued (int64_t layer ,int64_t expert )const { 4688 std::lock_guard < std::mutex > lk (ram_mu_ ); 4689for (const auto & j :ram_jobs_ ) 4690if (j -> layer == layer && (j -> in == expert || j -> out == expert ))return true; 4691return false; 4692} 4693 4694void FileExpertSource ::ram_worker () { 4695 strata::platform::name_this_thread ("strata-ram" ); 4696for (;;) { 4697RamJob * job = nullptr ; 4698 { 4699 std::unique_lock < std::mutex > lk (ram_mu_ ); 4700ram_cv_ .wait (lk , [& ] { 4701if (ram_quit_ )return true; 4702for (const auto & j :ram_jobs_ ) 4703if (j -> state == 0 )return true; 4704return false; 4705 }); 4706if (ram_quit_ )return ; 4707for (const auto & j :ram_jobs_ ) 4708if (j -> state == 0 ) {job = j .get ();break ; } 4709job -> state = 1 ; 4710 } 4711const uint64_t bytes = layer_blob_bytes_ [(size_t )job -> layer ]; 4712job -> buf .resize ((size_t )bytes ); 4713const auto t0 = std::chrono::steady_clock::now (); 4714const bool ok = copy_from_files (job -> layer ,job -> in ,job -> buf .data ()); 4715file_us_ .fetch_add ((uint64_t ) std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ()- t0 ).count (), 4716 std::memory_order_relaxed ); 4717if (ok ) { 4718file_read_bytes_ .fetch_add (bytes , std::memory_order_relaxed ); 4719ram_staged_reads_ .fetch_add (1 , std::memory_order_relaxed ); 4720 } 4721 std::lock_guard < std::mutex > lk (ram_mu_ ); 4722job -> state = ok ?2 :3 ; 4723 } 4724} 4725 4726int64_t FileExpertSource ::ram_install (const int32_t * host_res ,int64_t n_expert ) { 4727 std::vector < std::unique_ptr < RamJob >> done ; 4728 { 4729 std::lock_guard < std::mutex > lk (ram_mu_ ); 4730for (auto it = ram_jobs_ .begin ();it != ram_jobs_ .end ();) { 4731if ((* it )-> state >=2 ) {done .push_back (std::move (* it ));it = ram_jobs_ .erase (it ); } 4732else ++ it ; 4733 } 4734 } 4735int64_t n = 0 ; 4736for (const auto & j :done ) { 4737if (j -> state != 2 ) {ram_install_skips_ .fetch_add (1 , std::memory_order_relaxed );continue ; } 4738if (host_res != nullptr && (host_res [(size_t ) (j -> layer * n_expert + j -> in )] >=0 || 4739host_res [(size_t ) (j -> layer * n_expert + j -> out )] >=0 )) { 4740ram_install_gpu_ .fetch_add (1 , std::memory_order_relaxed );// the GPU tier took one of them meanwhile 4741continue ; 4742 } 4743if (install_resident (j -> layer ,j -> in ,j -> out ,j -> buf .data ()))++ n ; 4744else ram_install_skips_ .fetch_add (1 , std::memory_order_relaxed ); 4745 } 4746return n ; 4747} 4748 4749void FileExpertSource ::ram_stop () { 4750 { 4751 std::lock_guard < std::mutex > lk (ram_mu_ ); 4752ram_quit_ = true; 4753 } 4754ram_cv_ .notify_all (); 4755if (ram_thread_ .joinable ())ram_thread_ .join (); 4756 std::lock_guard < std::mutex > lk (ram_mu_ ); 4757ram_jobs_ .clear (); 4758ram_quit_ = false; 4759} 4760 4761int FileExpertSource ::tier_of (int64_t layer ,int64_t expert )const { 4762if (layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return 2 ; 4763const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 4764if (complement_ready_ && resident_blob (index )!= nullptr )return 0 ; 4765#if defined(__linux__ ) 4766uint64_t total = 0 ; 4767const uint64_t c = cached_bytes (layer ,expert ,total , false); 4768return total > 0 && c >=total ?1 :2 ; 4769#else 4770return 2 ; 4771#endif 4772} 4773 4774void FileExpertSource ::commit_copies () { 4775fs_hold_staged (true);// #2134: held until commit_flip has pointed `out` at its new place 4776if (exchange_storage_ .active ())return ;// STRATA_EXCHANGE_ROTATE: ownership moves in commit_flip, nothing to copy 4777for (const Exchange & x :staged_ ) { 4778const uint8_t * src = override_ .empty () ?nullptr :override_ [x .out ]; 4779const uint64_t at = complement_offsets_ [x .in ]; 4780if (src != nullptr && at != kNoComplement && at <=complement_bytes_ && x .bytes <=complement_bytes_ - at && 4781complement_host_ != nullptr ) 4782 std::memcpy ((uint8_t * )complement_host_ + (size_t )at ,src , (size_t )x .bytes ); 4783 } 4784} 4785 4786int64_t FileExpertSource ::commit_flip () { 4787int64_t n = 0 ; 4788fs_hold_staged (true);// (already held by commit_copies; idempotent) 4789for (const Exchange & x :staged_ ) { 4790const uint8_t * src = override_ [x .out ]; 4791if (exchange_storage_ .active ()) {// STRATA_EXCHANGE_ROTATE: the same ownership transfer as commit_exchanges 4792if (!exchange_storage_ .commit (x .in ,x .out , (size_t )x .q ,src , (size_t )x .bytes )) { 4793 std::fprintf (stderr ,"FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n" ); 4794 std::abort (); 4795 } 4796++ n ; 4797override_ [x .out ]= nullptr ; 4798continue ; 4799 } 4800const uint64_t at = complement_offsets_ [x .in ]; 4801// the same test as commit_copies: an exchange whose bytes were copied is the one that flips 4802if (src != nullptr && at != kNoComplement && at <=complement_bytes_ && x .bytes <=complement_bytes_ - at && 4803complement_host_ != nullptr && detail::exchange_cache_complement (complement_offsets_ ,x .in ,x .out )) 4804++ n ; 4805override_ [x .out ]= nullptr ; 4806 } 4807fs_hold_staged (false); 4808staged_ .clear (); 4809exchanges_ += n ; 4810return n ; 4811} 4812 4813const uint8_t * FileExpertSource ::resident_blob (int64_t layer ,int64_t expert )const { 4814if (!complement_ready_ || complement_host_ == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || 4815expert >=n_expert_ )return nullptr ; 4816const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 4817if (index >=complement_offsets_ .size ())return nullptr ; 4818return resident_blob (index );// through the rotation's ownership table when STRATA_EXCHANGE_ROTATE is on 4819} 4820 4821const uint8_t * FileExpertSource ::blob_stable (int64_t layer ,int64_t expert ) { 4822if (io_pf_ && role_ptr_ .empty ()&& direct_ .empty ()) { 4823if (complement_ready_ && layer >=0 && expert >=0 && layer < n_layers_ && expert < n_expert_ ) { 4824const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 4825if (resident_blob (index )!= nullptr || (!override_ .empty ()&& override_ [index ]!= nullptr ))return blob (layer ,expert ); 4826 } 4827const uint8_t * b = mapped_blob (layer ,expert ); 4828if (b != nullptr )file_read_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 4829return b ; 4830 } 4831return blob (layer ,expert ); 4832} 4833 4834int FileExpertSource ::blob_parts (int64_t layer ,int64_t expert ,BlobPart * out ) { 4835// the GGUF mapped in place only (three tensors per expert); the RAM copy, an exchange override, the unbuffered 4836// reads, a closed mapping and the I/O prefetch (STRATA_IO_PREFETCH: it preads the ranges the page cache lacks, which a copy out 4837// of the mapping would fault in one page at a time) keep going through blob(), which knows them 4838if (role_ptr_ .empty ()|| !direct_ .empty ()|| io_pf_ || unmapped_ || base_ == nullptr || layer < 0 || expert < 0 || 4839layer >=n_layers_ || expert >=n_expert_ ) 4840return 0 ; 4841const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 4842if (complement_ready_ && (resident_blob (index )!= nullptr || (!override_ .empty ()&& override_ [index ]!= nullptr )))return 0 ; 4843Span sp [3 ]; 4844const int ns = spans (layer ,expert ,sp ); 4845for (int i = 0 ;i < ns ;++ i )out [i ]= {sp [i ].p ,sp [i ].n ,sp [i ].at }; 4846if (ns > 0 ) { 4847file_read_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 4848++ reads_ ; 4849 } 4850return ns ; 4851} 4852 4853const uint8_t * FileExpertSource ::blob (int64_t layer ,int64_t expert ) { 4854if (base_ == nullptr || layer < 0 || expert < 0 || layer >=n_layers_ || expert >=n_expert_ )return nullptr ; 4855const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 4856const uint8_t * result = nullptr ; 4857bool from_files = true; 4858if (complement_ready_ ) { 4859result = resident_blob (index ); 4860if (result != nullptr ) { 4861ram_reads_ .fetch_add (1 , std::memory_order_relaxed ); 4862from_files = false; 4863 }else if (!override_ .empty ()&& override_ [index ]!= nullptr ) { 4864result = override_ [index ]; 4865from_files = false; 4866 } 4867 } 4868if (from_files ) { 4869if (io_pf_ && role_ptr_ .empty ()&& direct_ .empty ()) { 4870result = io_blob (layer ,expert );// staged when it had to be read, the mapping when cached 4871 }else if (staged ()) { 4872result = staged_blob (layer ,expert );// counts its bytes 4873 }else { 4874result = mapped_blob (layer ,expert ); 4875if (result != nullptr ) { 4876file_read_bytes_ .fetch_add (layer_blob_bytes_ [(size_t )layer ], std::memory_order_relaxed ); 4877#if defined(__linux__ ) 4878if (io_stats_ ) {// STRATA_IO_STATS=1: what the page cache held when the kernels were handed the blob 4879uint64_t total = 0 ; 4880const uint64_t c = cached_bytes (layer ,expert ,total ); 4881io_cached_ .fetch_add (c , std::memory_order_relaxed ); 4882io_uncached_ .fetch_add (total - c , std::memory_order_relaxed ); 4883 } 4884#endif 4885 } 4886 } 4887if (complement_ready_ && result != nullptr )file_reads_ .fetch_add (1 , std::memory_order_relaxed ); 4888 } 4889if (result != nullptr )reads_ .fetch_add (1 , std::memory_order_relaxed ); 4890return result ; 4891} 4892 4893bool FileExpertSource ::pinned (int64_t layer ,int64_t expert )const { 4894if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 || 4895layer >=n_layers_ || expert >=n_expert_ )return false; 4896const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 4897if (exchange_storage_ .active ())return exchange_storage_ .resident (index ).host != nullptr ; 4898// soft_commit_exchanges: a staged `out` is judged by the place it will take (`in`'s), as after the commit 4899const size_t at_index = !soft_in_ .empty ()&& soft_in_ [index ]!= SIZE_MAX ?soft_in_ [index ] :index ; 4900if (at_index >=complement_offsets_ .size ()|| complement_offsets_ [at_index ]== kNoComplement )return false; 4901// a partial pin (CS-T): only the registered prefix 4902return !complement_partial_ || 4903complement_offsets_ [at_index ]+ layer_blob_bytes_ [(size_t )layer ] <=complement_pin_limit_ ; 4904} 4905 4906const uint8_t * FileExpertSource ::device_alias (int64_t layer ,int64_t expert )const { 4907if (!pinned (layer ,expert )|| complement_device_ == nullptr )return nullptr ; 4908const size_t index = (size_t )layer * (size_t )n_expert_ + (size_t )expert ; 4909if (exchange_storage_ .active ())return exchange_storage_ .resident (index ).device ; 4910if (!soft_in_ .empty ()&& soft_in_ [index ]!= SIZE_MAX )// soft_commit_exchanges: out is read from its exchange buffer 4911return override_ .empty ()|| override_ [index ]== nullptr || xstage_dev_ == nullptr 4912 ?nullptr :xstage_dev_ + (size_t ) (override_ [index ]- xstage_ ); 4913return complement_device_ + (size_t )complement_offsets_ [index ]; 4914} 4915 4916bool FileExpertSource ::pcie_layer (int64_t layer )const { 4917if (complement_ready_ && complement_pinned_ && complement_device_ != nullptr ) 4918return layer >=0 && layer < n_layers_ ; 4919return device_alias (layer ,0 )!= nullptr ; 4920} 4921 4922// ================================ THE ADAPTER ================================ 4923 4924bool ExpertDispatch ::fetch_can (int64_t layer )const { 4925return fetch_admit > 0 && res_mut != nullptr && !usage .empty ()&& plan != nullptr && plan -> pcie_mode == 2 && 4926plan -> dst2 != nullptr && peer == nullptr && remote_count == 0 && fs == nullptr && pcie_num > 0 && 4927src != nullptr && src -> pcie_layer (layer ); 4928} 4929 4930void expert_pool_dispatch (void * user ,const float * x_f ,const int32_t * ids ,const float * weights ,int64_t n_embd , 4931int64_t k ,float * out ) { 4932 (void )weights ;// clause 2: `moe_combine` applies it on the device. Not an oversight. 4933ExpertDispatch & d = * (ExpertDispatch * )user ; 4934if (d .failed )return ;// a previous layer already failed; do not make it worse 4935 4936using namespace strata::kernels::cpu ; 4937// Clause 3: the blob's internal offsets are compile-time constants, so a mismatched geometry does not 4938// produce a wrong answer - it produces a walk off the end of the blob into the next expert's bytes, which 4939// is finite and plausible. Refuse, name the number, and let the driver report it. 4940if (n_embd != H ) { 4941d .failed = true; 4942d .fail = "the expert kernel is compiled for a 2560-wide activation" ; 4943d .fail_layer = d .layers ; 4944return ; 4945 } 4946if (expert_layout ().native ) { 4947// plan v0.3 P6: a native pack runs its experts in verify windows only (the driver guarantees it) 4948d .failed = true; 4949d .fail = "the single-token expert path does not take a native (IQ) pack" ; 4950d .fail_layer = d .layers ; 4951return ; 4952 } 4953if (k > (int64_t )d .jobs .size ())d .jobs .resize ((size_t )k ); 4954 4955d .src -> begin_layer (d .layers ,ids ,k ); 4956 4957// Clause 1: rebuilt from `x_f` on EVERY call. `x_f` is mapped pinned memory whose address never changes, 4958// so anything cached against it would be layer 0's activation reused 48 times. 4959act_quant_q8_1 (x_f ,H ,d .act ); 4960 4961// ---- R4.2c: THE POOL'S HALF OF THE SPLIT. **IT DOES NOT DECIDE ANYTHING - `Launch` ALREADY DID.** 4962// 4963// The decision has to be made on THIS layer's ids, and `Launch` is the only callback that runs before the 4964// pool while the ids are known (the doorbell publishes them when the ring fires). So `expert_hit_run` 4965// decides, and this consumes `d.is_hit`. The first version decided here instead, which meant `Launch` 4966// computed the PREVIOUS layer's experts into this layer's rows: C1 went from mean KL 9.69e-02 to 1.03e+00. 4967// 4968// `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a hit. 4969const bool graph_hits = d .host_res != nullptr ; 4970const bool use_hits = graph_hits || (d .hits_ready ()&& d .decided ); 4971int64_t njobs = 0 ; 4972 4973if (d .remote_count > 0 ) { 4974int32_t kind [32 ]; 4975if (k > 32 ) { 4976d .failed = true;d .fail = "remote experts: routing width exceeds 32" ;return ; 4977 } 4978for (int64_t i = 0 ;i < k ;++ i ) 4979kind [i ]= use_hits && ids [i ] >=0 && ids [i ]< d .n_expert && (graph_hits 4980 ?d .host_res [(size_t )d .layers * (size_t )d .n_expert + (size_t )ids [i ]] >=0 4981 :d .is_hit [(size_t )i ]!= 0 ) ?0 :-1 ; 4982static thread_local std::string remote_error ; 4983for (int r = 0 ;r < d .remote_count ;++ r ) 4984if (!d .remote [r ]-> begin (d .layers ,x_f ,ids ,1 ,k ,kind ,d .host_res ,remote_error )) { 4985d .failed = true;d .fail = remote_error .c_str ();d .fail_layer = d .layers ;return ; 4986 } 4987 } 4988 4989for (int64_t i = 0 ;i < k ;++ i ) { 4990const int64_t e = ids [i ]; 4991if (e < 0 || e >=d .n_expert ) { 4992d .failed = true; 4993d .fail = "a routed expert id is out of range" ; 4994d .fail_layer = d .layers ; 4995d .fail_expert = e ; 4996return ; 4997 } 4998const uint8_t * b = d .src -> blob (d .layers ,e ); 4999if (b == nullptr ) { 5000// The one failure the loop cannot see. Leaving `out` at its previous contents would feed the NEXT 5001// layer a stale expert vector, which `moe_combine` would weight and add - the token would still be 5002// finite and would still be wrong, 48 layers deep. 5003d .failed = true; 5004d .fail = "the expert source could not produce a blob" ; 5005d .fail_layer = d .layers ; 5006d .fail_expert = e ; 5007++ d .missing ; 5008return ; 5009 } 5010// A hit's row was zeroed by `Launch` and belongs to the GPU; the pool must not touch it. 5011if (use_hits && (graph_hits ?d .host_res [(size_t )d .layers * (size_t )d .n_expert + (size_t )e ] >=0 5012 :d .is_hit [(size_t )i ]!= 0 )) { 5013if (graph_hits )++ d .cache_hits ; 5014// The GPU owns this row and `hit_out` is zeroed, so the CPU's contribution is zero - but 5015// `y_miss` is a REUSED pinned buffer, so the row must be written, not merely skipped. 5016 std::memset (out + (size_t )i * (size_t )n_embd ,0 , (size_t )n_embd * sizeof (float )); 5017continue ; 5018 } 5019if (graph_hits )++ d .cache_refused ;// token graph: a miss (nothing is admitted during a token) 5020 5021bool remote_owns = false; 5022for (int r = 0 ;r < d .remote_count ;++ r )remote_owns |=d .remote [r ]-> owns (i ); 5023if (remote_owns ) { 5024 std::memset (out + (size_t )i * (size_t )n_embd ,0 , (size_t )n_embd * sizeof (float )); 5025continue ; 5026 } 5027 5028// `njobs` indexes the JOB ARRAY and `i` indexes the OUTPUT - they are the same only when nothing is a 5029// hit, and using one for the other is how a hit's row would get two experts summed into it. 5030ExpertJob & j = d .jobs [(size_t )njobs ++ ]; 5031j .blob = b ; 5032j .act = & d .act ;// SHARED across the batch: one conversion serves all ten experts 5033j .out = out + (size_t )i * (size_t )n_embd ; 5034j .weight = 1.0f ;// clause 2: a diagnostic field, NOT the router weight 5035j .slot = (int )i ; 5036 } 5037 5038// Plan v0.3 P4: rows of every expert across all threads (bitwise the same as `run`). 5039if (d .split_rows )d .pool -> run_split (d .jobs .data (), (int )njobs ); 5040else d .pool -> run (d .jobs .data (), (int )njobs ); 5041if (d .remote_count > 0 ) { 5042static thread_local std::string remote_error ; 5043for (int r = 0 ;r < d .remote_count ;++ r ) 5044if (!d .remote [r ]-> finish (out ,remote_error )) { 5045d .failed = true;d .fail = remote_error .c_str ();d .fail_layer = d .layers ;return ; 5046 } 5047 } 5048++ d .layers ; 5049d .experts += k ; 5050} 5051 5052namespace { 5053// the verify window's per-entry tables in `expert_pool_dispatch_multi` (`kind`, `distinct`, `first_of`) 5054// are fixed arrays of this many entries: a window's rows (kWindowMaxT) of the model's 10 routed experts must fit, and a 5055// larger k is refused at run time rather than written past them. 128 for the 8-row window (as it was), 256 for 16. 5056constexpr int64_t kMaxWindowEntries = strata::kernels::kWindowMaxT <=8 ?128 :256 ; 5057static_assert(strata::kernels::kWindowMaxT * 10 <=kMaxWindowEntries ,"a verify window's entries overflow the tables" ); 5058}// namespace 5059 5060namespace { 5061// STRATA_ROUTE_TAIL_SKIP: the rank from which a missed expert that every token of the window routes that low is skipped. An 5062// explicit environment value is read once; the serve start-up (generate.cpp) sets the CUDA default where it applies. 5063std::atomic < int > g_tail_skip_rank {-1 };// -1: not resolved yet 5064}// namespace 5065int tail_skip_rank () { 5066int r = g_tail_skip_rank .load (std::memory_order_relaxed ); 5067if (r < 0 ) { 5068const char * v = std::getenv ("STRATA_ROUTE_TAIL_SKIP" ); 5069r = v != nullptr ? std::atoi (v ) :0 ; 5070r = r > 0 && r < 10 ?r :0 ; 5071g_tail_skip_rank .store (r , std::memory_order_relaxed ); 5072 } 5073return r ; 5074} 5075void set_tail_skip_rank (int r ) {g_tail_skip_rank .store (r > 0 && r < 10 ?r :0 , std::memory_order_relaxed ); } 5076 5077static void lat_quant_q8_1 (const float * x ,int n ,uint8_t * o ) {// = quantize_q8_1_kernel, per 32: d, sum, qs 5078const int nb = n /32 ; 5079for (int b = 0 ;b < nb ;++ b ) { 5080const float * xb = x + b * 32 ; 5081uint8_t * ob = o + b * 36 ; 5082float amax = 0.0f ,sum = 0.0f ; 5083for (int j = 0 ;j < 32 ;++ j ) { 5084const float v = xb [j ]; 5085amax = fmaxf (amax ,fabsf (v )); 5086sum += v ; 5087 } 5088const float d32 = amax /127.0f ; 5089const float d = fabsf (d32 )> 65504.0f ?copysignf (65504.0f ,d32 ) :d32 ; 5090const uint16_t dh = strata::kernels::f16_from_f32 (d ); 5091const uint16_t sh = strata::kernels::f16_from_f32 (sum ); 5092ob [0 ]= (uint8_t )(dh & 0xFFu );ob [1 ]= (uint8_t )(dh >>8 ); 5093ob [2 ]= (uint8_t )(sh & 0xFFu );ob [3 ]= (uint8_t )(sh >>8 ); 5094int8_t * q = (int8_t * )(ob + 4 ); 5095// amax/sum stay scalar above (their order feeds the f16 d/sum - a SIMD reduction would 5096// reorder it). The qs loop is per element, no reduction: the AVX2 copy in kq_avx2.cpp. 5097// THE 32-float SNAPSHOT is the race fix (probe-proven 2026-11-04): lh has a writer that 5098// races this read - consuming it at a different moment changed the window's output (the 5099// day's whole "parity red" chain). The copy pins what the quant consumes, a few ns/block. 5100// STRATA_LH_WHO=1 double-reads to catch the writer in the act. 5101static const bool qs_simd_off = std::getenv ("STRATA_NO_QS_SIMD" )!= nullptr ; 5102static const bool lh_who = std::getenv ("STRATA_LH_WHO" )!= nullptr ; 5103float snap [32 ]; 5104 std::memcpy (snap ,xb ,32 * sizeof (float )); 5105if (lh_who ) {// read it again right away: a racing writer shows up as a delta 5106static std::atomic < int > lh_diffs {0 }; 5107for (int j = 0 ;j < 32 ;++ j ) 5108if (snap [j ]!= xb [j ]) { 5109if (lh_diffs .fetch_add (1 )< 8 ) 5110 std::fprintf (stderr ,"LHWHO b=%d j=%d: before %g after %g\n" ,b ,j ,snap [j ],xb [j ]); 5111break ; 5112 } 5113 } 5114if (amax != 0.0f && !qs_simd_off && strata::kernels::cpu::kq256_supported (8 )) 5115 strata::kernels::cpu::lat_quant_q8_1_qs_avx2 (snap ,& d ,q ); 5116else { 5117for (int j = 0 ;j < 32 ;++ j ) { 5118float v ; 5119if (amax == 0.0f )v = 0.0f ; 5120else v = roundf (xb [j ] /d ); 5121v = v > 127.0f ?127.0f : (v < -127.0f ?-127.0f :v ); 5122q [j ]= (int8_t )v ; 5123 } 5124 } 5125 } 5126} 5127 5128// ---- latent MoE: the CPU pool's expert arithmetic (edge0). The GPU computes the whole window's D stage 5129// and its result (the q8_1 image of xl, row t*G + g) is in mapped host memory - the pool never recomputes D. 5130// Per CPU-served entry (kind == -1): the A blob computes h = A[e] . xl[t,g] (I then ELL, the pool's native 5131// row phases over the GPU's own quantized xl rows), then contribution = U[g] . q8_1(h) as a mode-7 row dot 5132// spread over the workers, written into the entry's mapped row (out + i*H). 5133static FileExpertSource * latent_io_source (ExpertSource * src ) { 5134static const bool enabled = [] { 5135const char * v = std::getenv ("STRATA_LATENT_IO_OVERLAP" ); 5136return v != nullptr && std::atoi (v )!= 0 ; 5137 }(); 5138if (!enabled )return nullptr ; 5139auto * file = dynamic_cast < FileExpertSource *> (src ); 5140return file != nullptr && file -> unbuffered () ?file :nullptr ; 5141} 5142 5143static void latent_cpu_run (ExpertDispatch & d ,const float * x_f ,const int32_t * ids , 5144int64_t n_tok ,int64_t k ,const int32_t * kind ,float * out ) { 5145using namespace strata::kernels::cpu ; 5146const int64_t l = d .layers ; 5147const NativeFmt & f = expert_layout ().fmt [(size_t )l ]; 5148const int64_t ELL = d .lat_ELL ,H = d .lat_H ; 5149const int G = d .lat_G ,E = d .lat_E ; 5150const strata::core::LatentDense & dd = * d .lat_dense ; 5151const uint8_t * U = dd .u (l ); 5152const int32_t * labels = d .lat_labels + (size_t )l * (size_t )E ; 5153const size_t u_row = dd .u_row_bytes (); 5154const size_t xlq_row = (size_t ) (ELL /32 )* 36 ; 5155const double t_enter_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5156 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// PROBE-OTHER: entry 5157 5158// the CPU entries: j -> (entry index i, token, expert, group); the groups used 5159static thread_local std::vector < int64_t > ent_i ; 5160static thread_local std::vector < int > ent_t ,ent_e ,ent_g ; 5161ent_i .clear ();ent_t .clear ();ent_e .clear ();ent_g .clear (); 5162bool used [64 ]= {}; 5163for (int64_t i = 0 ;i < n_tok * k ;++ i ) { 5164if (kind [i ]!= -1 )continue ; 5165const int32_t e = ids [i ]; 5166if (e < 0 || e >=E ) {d .failed = true;d .fail = "a routed expert id is out of range" ;d .fail_layer = l ;d .fail_expert = e ;return ; } 5167const int g = labels [(size_t )e ]; 5168if (g < 0 || g >=G ) {d .failed = true;d .fail = "latent: a bad group label" ;d .fail_layer = l ;d .fail_expert = e ;return ; } 5169ent_i .push_back (i );ent_t .push_back ((int ) (i /k ));ent_e .push_back (e );ent_g .push_back (g ); 5170if (g < 64 )used [g ]= true; 5171 } 5172if (ent_t .empty ())return ; 5173static const bool s_pool_trace = std::getenv ("STRATA_POOL_TRACE" )!= nullptr ; 5174if (s_pool_trace ) std::fprintf (stderr ,"POOL-ENTRY l=%d\n" , (int )l ); 5175const float * xl = (const float * )d .lat_xlq ;// the D stage's f32 rows (mapped), row t*G + g 5176if (xl == nullptr ) {d .failed = true;d .fail = "latent CPU share: no D result for this window" ;d .fail_layer = l ;return ; } 5177double t_xlseq_ms = 0.0 ; 5178if (d .lat_xlseq != nullptr ) {// the D stage's doorbell: the rows of layer l are in when it reaches l+1 5179const uint32_t want = (uint32_t ) (l + 1 ); 5180if (s_pool_trace ) std::fprintf (stderr ,"POOL-DOORBELL l=%d want=%u got=%u\n" , (int )l ,want ,* (volatile const uint32_t * )d .lat_xlseq ); 5181const auto t0 = std::chrono::steady_clock::now (); 5182while (* (volatile const uint32_t * )d .lat_xlseq < want ) { 5183if (std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count ()> 20000.0 ) { 5184d .failed = true;d .fail = "latent CPU share: the D rows never arrived for this layer" ; 5185d .fail_layer = l ; 5186return ; 5187 } 5188 std::this_thread::yield (); 5189 } 5190 std::atomic_thread_fence (std::memory_order_seq_cst ); 5191t_xlseq_ms = std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); 5192if (s_pool_trace ) std::fprintf (stderr ,"POOL-QUANT l=%d\n" , (int )l ); 5193 } 5194 5195// ---- A: the blob experts on the pool's native row phases. The activation is quantized ON THE HOST from 5196// the D stage's f32 rows (native_quant_act -> the blobs' vec_dot_type, Q8_0 for NVFP4); the layer's 5197// Hadamard fold stays off - the D output is already in the blob's own basis (v1's verified fix). 5198const double t_ew_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5199 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// PROBE-OTHER: ew end 5200static thread_local std::vector < float > lh ; 5201static thread_local std::vector < uint8_t > act ;// one Q8_0 activation row per CPU entry 5202static thread_local std::vector < ExpertJobMulti > jobs ; 5203static thread_local std::vector < int64_t > job_experts ; 5204static thread_local std::vector < char > taken ; 5205FileExpertSource * const io = latent_io_source (d .src ); 5206struct FetchDrain { 5207FileExpertSource * src ; 5208 ~FetchDrain () {if (src != nullptr ) (void )src -> latent_fetch_wait (); } 5209 }fetch_drain {io }; 5210lh .assign ((size_t )ent_t .size ()* (size_t )ELL ,0.f ); 5211jobs .clear (); 5212job_experts .clear (); 5213taken .assign (ent_t .size (),0 ); 5214NativeFmt f_nr = f ;f_nr .had_gu = false;// no rotation: the D output is the blob's own basis 5215const size_t act_row = f .act_bytes ;// per-entry activation bytes (the gu vec_dot_type, Q8_0) 5216// DESIGN-4: the act rows arrive GPU-made (mapped, bit-exact - probe_std's zero diff; the D 5217// stage quantizes them before the doorbell, so xlseq covers them). The jobs point straight 5218// at the mapped rows - zero host compute, zero copy. STRATA_ACT_FALLBACK=1 keeps the old 5219// host quantization (the A/B arm); STRATA_ACT_CHECK memcmps GPU rows vs the host reference 5220// (zero-row guard included - the mod5 lesson). 5221static const bool act_fallback = std::getenv ("STRATA_ACT_FALLBACK" )!= nullptr ; 5222static const bool act_check = std::getenv ("STRATA_ACT_CHECK" )!= nullptr ; 5223const uint8_t * act0 = (const uint8_t * )d .lat_act0 ; 5224// DESIGN-4's GPU rows are ALWAYS Q8_0 (verify.cpp quantize_q8_0_rows), but this layer's 5225// blobs may dot against another activation format (Q3_K -> ggml-cpu's Q8_K, 292 B per 5226// 256 values): a non-Q8_0 layer must not consume them - the bytes would be misread and 5227// the row stride would bleed into the next row. Only a layer whose own act_row is the 5228// Q8_0 one takes the GPU-made rows; the rest fall back to the host quantizer. 5229const size_t act_q8_0_row = (size_t ) (ELL /32 )* 34 ; 5230const bool act_gpu = act0 != nullptr && !act_fallback && act_row == act_q8_0_row ; 5231act .assign ((size_t )ent_t .size ()* act_row ,0 ); 5232if (act_gpu ) { 5233for (size_t j = 0 ;j < ent_t .size ();++ j ) { 5234const uint8_t * src = act0 + ((size_t )ent_t [j ]* (size_t )G + (size_t )ent_g [j ])* act_row ; 5235if (act_check ) {// the GPU-vs-host probe, first diff only, zero-head guard 5236static std::atomic < int > act_diffs {0 }; 5237static thread_local std::vector < uint8_t > act_ref ; 5238act_ref .assign (act_row ,0 ); 5239native_quant_act (f_nr ,xl + ((size_t )ent_t [j ]* (size_t )G + (size_t )ent_g [j ])* (size_t )ELL , 5240act_ref .data ()); 5241const uint8_t * a = act_ref .data (); 5242if (a [0 ]== 0 && a [1 ]== 0 && a [2 ]== 0 && a [3 ]== 0 ) 5243if (act_diffs .fetch_add (1 )< 8 ) 5244 std::fprintf (stderr ,"ACTCHECK j=%zu: GPU ZERO HEAD\n" ,j ); 5245if (std::memcmp (a ,src ,act_row )!= 0 ) 5246for (size_t k = 0 ;k < act_row ;++ k ) 5247if (a [k ]!= src [k ]) { 5248if (act_diffs .fetch_add (1 )< 8 ) 5249 std::fprintf (stderr ,"ACTCHECK j=%zu byte %zu: host %02x vs gpu %02x\n" ,j ,k ,a [k ],src [k ]); 5250break ; 5251 } 5252 } 5253 std::memcpy (act .data ()+ j * act_row ,src ,act_row ); 5254 } 5255 }else { 5256auto * const tr = ggml_get_type_traits_cpu ((ggml_type )f_nr .gu_act ); 5257auto const ff = tr -> from_float ; 5258for (size_t j = 0 ;j < ent_t .size ();++ j ) { 5259const float * src = xl + ((size_t )ent_t [j ]* (size_t )G + (size_t )ent_g [j ])* (size_t )ELL ; 5260ff (src ,act .data ()+ j * act_row , (int64_t )ELL ); 5261 } 5262 } 5263const double t_quant_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5264 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGA: relative marker 5265int64_t t_blob_ns = 0 ; 5266for (size_t i0 = 0 ;i0 < ent_t .size ();++ i0 ) { 5267if (taken [i0 ])continue ; 5268const int e = ent_e [i0 ]; 5269ExpertJobMulti jb {}; 5270const auto tb0 = std::chrono::steady_clock::now (); 5271if (io == nullptr )jb .blob = d .src -> blob (l ,e ); 5272t_blob_ns += std::chrono::duration_cast < std::chrono::nanoseconds > (std::chrono::steady_clock::now ()- tb0 ).count (); 5273if (io == nullptr && jb .blob == nullptr ) {d .failed = true;d .fail = "the expert source could not produce a blob" ;d .fail_layer = l ;d .fail_expert = e ;++ d .missing ;return ; } 5274for (size_t i = i0 ;i < ent_t .size ()&& jb .nt < MAXT ;++ i ) { 5275if (taken [i ]|| ent_e [i ]!= e )continue ; 5276taken [i ]= 1 ; 5277jb .nact [jb .nt ]= act .data ()+ i * act_row ; 5278jb .out [jb .nt ]= lh .data ()+ i * (size_t )ELL ; 5279++ jb .nt ; 5280 } 5281jobs .push_back (jb ); 5282if (io != nullptr )job_experts .push_back (e ); 5283 } 5284if (std::getenv ("STRATA_DIAG_A" )!= nullptr ) { 5285static std::atomic < int64_t > dwin {0 },djobs {0 },dent {0 }; 5286int64_t ent_sum = 0 ; 5287for (const auto & jb :jobs )ent_sum += jb .nt ; 5288dwin .fetch_add (1 , std::memory_order_relaxed ); 5289djobs .fetch_add ((int64_t )jobs .size (), std::memory_order_relaxed ); 5290dent .fetch_add (ent_sum , std::memory_order_relaxed ); 5291if (dwin .load (std::memory_order_relaxed ) %48 == 0 ) 5292 std::fprintf (stderr ,"DIAGA win=%lld jobs=%.1f entries=%.1f\n" , 5293 (long long )dwin .load (), (double )djobs .load () /dwin .load (), 5294 (double )dent .load () /dwin .load ()); 5295 } 5296const double t_a0_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5297 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// PROBE-OTHER: jb end 5298if (io == nullptr || jobs .empty ()) { 5299d .pool -> run_split_multi_native (f ,jobs .data (), (int )jobs .size (),NativeArithmetic ::Default ); 5300 }else { 5301static const size_t batch = [] { 5302const char * v = std::getenv ("STRATA_LATENT_IO_BATCH" ); 5303return (size_t ) std::clamp (v != nullptr ? std::atoi (v ) :8 ,1 ,16 ); 5304 }(); 5305auto submit = [& ](size_t at ) { 5306return io -> latent_fetch_begin (l ,job_experts .data ()+ at , 5307 (int64_t ) std::min (batch ,jobs .size ()- at )); 5308 }; 5309bool submitted = submit (0 ); 5310for (size_t at = 0 ;at < jobs .size ();at += batch ) { 5311if (!submitted || !io -> latent_fetch_wait ()) { 5312d .failed = true;d .fail = "latent: the direct fetch batch failed" ;d .fail_layer = l ;return ; 5313 } 5314const size_t count = std::min (batch ,jobs .size ()- at ); 5315for (size_t j = at ;j < at + count ;++ j ) { 5316jobs [j ].blob = d .src -> blob (l ,job_experts [j ]); 5317if (jobs [j ].blob == nullptr ) { 5318d .failed = true;d .fail = "the expert source could not produce a blob" ; 5319d .fail_layer = l ;d .fail_expert = job_experts [j ];++ d .missing ;return ; 5320 } 5321 } 5322const size_t next = at + count ; 5323// blob() just refreshed current claims; <=16 next claims cannot reach claim_stage's 256-use eviction age. 5324if (next < jobs .size ())submitted = submit (next ); 5325d .pool -> run_split_multi_native (f ,jobs .data ()+ at , (int )count ,NativeArithmetic ::Default ); 5326 } 5327 } 5328const double t_a1_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5329 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGA: A wall 5330if (s_pool_trace ) std::fprintf (stderr ,"POOL-A-END l=%d\n" , (int )l ); 5331 5332// ---- U: contribution[j] = U[g] . q8_1(h_j): one matvec per used group over its entries (mode 7) 5333static thread_local std::vector < uint8_t > hq ; 5334static thread_local std::vector < const void *> flat_act ; 5335static thread_local std::vector < float *> flat_out ; 5336static thread_local std::vector < ExpertPool ::LatentMatvec > mvs ; 5337hq .resize (xlq_row * ent_t .size ()); 5338for (size_t j = 0 ;j < ent_t .size ();++ j )lat_quant_q8_1 (lh .data ()+ j * (size_t )ELL , (int )ELL ,hq .data ()+ j * xlq_row ); 5339if (s_pool_trace ) std::fprintf (stderr ,"POOL-HQ-END l=%d\n" , (int )l ); 5340// knife-0 (STRATA_LATENT_U_GPU=1): skip the CPU U matvec (mode 7); the GPU computes U from this hq. 5341static const bool u_gpu = [] {const char * v = std::getenv ("STRATA_LATENT_U_GPU" );return v != nullptr && std::atoi (v )!= 0 ; }(); 5342if (const char * hqd = std::getenv ("STRATA_HQ_DUMP" )) {// knife-0 debug: the hq rows this group computed 5343static std::atomic < int > hqn {0 }; 5344if (hqn .fetch_add (1 , std::memory_order_relaxed )< 2 ) { 5345FILE * f = std::fopen (hqd ,"ab" ); 5346if (f != nullptr ) { 5347 std::fwrite (hq .data (),1 ,hq .size (),f ); 5348 std::fclose (f ); 5349 } 5350 } 5351 } 5352if (u_gpu ) { 5353uint8_t * lhq = (uint8_t * )out ;// m_ymiss_ reinterpreted: Q8_1, routed order (xlq_row per entry) 5354 std::memset (lhq ,0 , (size_t )n_tok * (size_t )k * xlq_row );// skipped (kind=-2) rows -> zero hq -> zero U 5355for (size_t j = 0 ;j < ent_t .size ();++ j ) { 5356const int r = ent_i [j ]; 5357 std::memcpy (lhq + (size_t )r * xlq_row ,hq .data ()+ j * xlq_row ,xlq_row ); 5358 } 5359static const bool diag_hq = std::getenv ("STRATA_DIAG_HQ" )!= nullptr ;// the first windows' hq rows as copied 5360static std::atomic < int > diaghq_n {0 }; 5361if (diag_hq && diaghq_n .fetch_add (1 , std::memory_order_relaxed )< 5 && !ent_t .empty ()) { 5362const uint8_t * src = hq .data (); 5363const uint8_t * dst = lhq + (size_t )ent_i [0 ]* xlq_row ; 5364const int cmp = std::memcmp (src ,dst ,xlq_row ); 5365const uint16_t d = * (const uint16_t * )dst ,s = * (const uint16_t * ) (dst + 2 ); 5366const bool nan_d = (d & 0x7C00 )== 0x7C00 && (d & 0x3FF )!= 0 ; 5367const bool nan_s = (s & 0x7C00 )== 0x7C00 && (s & 0x3FF )!= 0 ; 5368 std::fprintf (stderr ,"DIAGHQ nent=%zu out=%p tb_off_bytes=%lld ent_i0=%d cmp=%d d=0x%04x(nan=%d) s=0x%04x(nan=%d) q0..3=%d,%d,%d,%d\n" , 5369ent_t .size (), (const void * )out , (long long ) (ent_i [0 ]* xlq_row ),ent_i [0 ],cmp , 5370d , (int )nan_d ,s , (int )nan_s , 5371 (int ) (int8_t )dst [4 ], (int ) (int8_t )dst [5 ], (int ) (int8_t )dst [6 ], (int ) (int8_t )dst [7 ]); 5372 std::fflush (stderr ); 5373 } 5374d .multi_entries += (int64_t )ent_t .size (); 5375return ; 5376 } 5377mvs .clear (); 5378flat_act .reserve (ent_t .size ()); 5379flat_out .reserve (ent_t .size ()); 5380int mv_base [64 ]; 5381for (int g = 0 ;g < G ;++ g ) { 5382mv_base [g ]= (int )flat_act .size (); 5383if (g >=64 || !used [g ])continue ; 5384for (size_t j = 0 ;j < ent_t .size ();++ j ) { 5385if (ent_g [j ]!= g )continue ; 5386flat_act .push_back (hq .data ()+ j * xlq_row ); 5387flat_out .push_back (out + (size_t )ent_i [j ]* (size_t )H ); 5388 } 5389 } 5390for (int g = 0 ;g < G ;++ g ) { 5391if (g >=64 || !used [g ])continue ; 5392const int i0 = mv_base [g ]; 5393const int i1 = g + 1 < G ?mv_base [g + 1 ] : (int )flat_act .size (); 5394if (i1 <=i0 )continue ; 5395ExpertPool ::LatentMatvec mv {}; 5396mv .w = U + (size_t )g * (size_t )H * u_row ; 5397mv .row_bytes = u_row ; 5398mv .nrows = (int )H ; 5399mv .ncols = (int )ELL ; 5400mv .nt = i1 - i0 ; 5401mv .act = flat_act .data ()+ i0 ; 5402mv .out = flat_out .data ()+ i0 ; 5403mvs .push_back (mv ); 5404 } 5405const double t_u1_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5406 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGA: U wall 5407static std::atomic < double > s_ur {0 }; 5408const auto ur0 = std::chrono::steady_clock::now (); 5409d .pool -> run_latent_rows (mvs .data (), (int )mvs .size ()); 5410s_ur .fetch_add ((double ) std::chrono::duration_cast < std::chrono::nanoseconds > (std::chrono::steady_clock::now ()- ur0 ).count () /1e6 , std::memory_order_relaxed ); 5411d .multi_entries += (int64_t )ent_t .size (); 5412if (std::getenv ("STRATA_DIAG_A" )!= nullptr ) { 5413static std::atomic < double > s_xlseq {0 },s_a {0 },s_u {0 },s_blob {0 }; 5414static std::atomic < int64_t > s_calls {0 }; 5415static std::atomic < double > s_ew {0 },s_jb {0 },s_am {0 };// PROBE-OTHER: the glue walls 5416s_ew .fetch_add (t_ew_ms - t_enter_ms , std::memory_order_relaxed ); 5417s_jb .fetch_add (t_a0_ms - t_quant_ms , std::memory_order_relaxed ); 5418s_am .fetch_add (t_quant_ms - t_ew_ms , std::memory_order_relaxed ); 5419s_xlseq .fetch_add (t_xlseq_ms , std::memory_order_relaxed ); 5420s_a .fetch_add (t_a1_ms - t_a0_ms , std::memory_order_relaxed ); 5421s_u .fetch_add (t_u1_ms - t_a1_ms , std::memory_order_relaxed ); 5422s_blob .fetch_add ((double )t_blob_ns /1e6 , std::memory_order_relaxed ); 5423if (s_calls .fetch_add (1 , std::memory_order_relaxed ) %48 == 0 ) 5424 std::fprintf (stderr ,"DIAGP ms/call: xlseq %.3f blob %.3f A %.3f U %.3f UR %.3f EW %.3f JB %.3f AM %.3f (n %lld)\n" , 5425s_xlseq .load () / (s_calls .load ()+ 1 ),s_blob .load () / (s_calls .load ()+ 1 ), 5426s_a .load () / (s_calls .load ()+ 1 ),s_u .load () / (s_calls .load ()+ 1 ), 5427s_ur .load () / (s_calls .load ()+ 1 ), 5428s_ew .load () / (s_calls .load ()+ 1 ),s_jb .load () / (s_calls .load ()+ 1 ), 5429s_am .load () / (s_calls .load ()+ 1 ), 5430 (long long ) (s_calls .load ()+ 1 )); 5431 } 5432} 5433 5434// One routed entry's report counters: -2 skipped, 0 VRAM, 1 PCIe, 2 another GPU, -1 CPU. 5435static void count_route_entry (ExpertDispatch & d ,int32_t kind ) { 5436if (kind == -2 ) {++ d .tail_skipped ;return ; } 5437if (kind < 0 ) {++ d .cache_refused ;return ; } 5438if (kind == 0 )++ d .cache_hits ; 5439else ++ d .offload_entries ;// #588: PCIe or another GPU 5440if (kind == 2 && d .peer != nullptr )++ d .peer_entries ; 5441} 5442 5443void expert_pool_dispatch_multi (ExpertDispatch & d ,const float * x_f ,const int32_t * ids ,int64_t n_tok ,int64_t k , 5444float * out , strata::kernels::cpu::NativeArithmetic arithmetic ) { 5445using namespace strata::kernels::cpu ; 5446if (d .failed )return ; 5447d .lat_xlq = strata::core::latent_xl_current ();// this window's D rows (null: not latent) 5448d .lat_xlseq = strata::core::latent_xlseq_current (); 5449d .lat_act0 = strata::core::latent_act0_current ();// DESIGN-4: the D rows as Q8_0, GPU-made 5450if (n_tok < 1 || n_tok > strata::kernels::kWindowMaxT ) { 5451d .failed = true; 5452d .fail = "a verify window has more tokens than the multi-token expert kernel takes" ; 5453d .fail_layer = d .layers ; 5454return ; 5455 } 5456if (d .lookahead != nullptr ) { 5457if (d .lookahead -> stats_on ()) { 5458if (d .layers == 0 )d .lookahead -> stats_window_start (); 5459d .lookahead -> stats_score (d .layers ,ids ,n_tok * k ,d .host_res ,d .pcie_num ); 5460 } 5461d .lookahead -> submit (d .layers ,x_f ,n_tok ,d .host_res );// CS-T: warm layer + 1 5462 } 5463if (k < 1 || n_tok * k > kMaxWindowEntries ) { 5464d .failed = true; 5465d .fail = "a verify window routes more entries than the expert pool's window tables hold" ; 5466d .fail_layer = d .layers ; 5467return ; 5468 } 5469if ((int64_t )d .act_multi .size ()< n_tok )d .act_multi .resize ((size_t ) strata::kernels::kWindowMaxT ); 5470const ExpertLayout & lay = expert_layout (); 5471const bool native = lay .native ; 5472if (native && d .nact_multi .size ()< (size_t ) strata::kernels::kWindowMaxT * kNativeActBytes ) 5473d .nact_multi .resize ((size_t ) strata::kernels::kWindowMaxT * kNativeActBytes ); 5474if (d .job_of .size ()!= (size_t )d .n_expert )d .job_of .assign ((size_t )d .n_expert , (int16_t )-1 ); 5475if (d .jobs_multi .size ()< (size_t ) (n_tok * k ))d .jobs_multi .resize ((size_t ) (strata::kernels::kWindowMaxT * k )); 5476static const bool ptrace = std::getenv ("STRATA_POOL_TRACE" )!= nullptr ; 5477auto pt = [& ](const char * what ,long long a = -1 ) { 5478if (ptrace ) { std::fprintf (stderr ,"pool trace: layer %lld %s %lld\n" , (long long )d .layers ,what ,a ); std::fflush (stderr ); } 5479 }; 5480const auto c0 = std::chrono::steady_clock::now (); 5481const FileExpertSource ::DecodeScope decode_scope ;// 149 STRATA_IO_PF_GATE: this thread reads for the decode 5482// 149-cold STRATA_COLD_OVERLAP: 0 off, 1 overlap, 2 measure only, 3 overlap + zero-copy, 4 zero-copy only. 5483// 0.2.0: unset, 4 for the GGUF read in place on Linux (zero-copy needs the page cache's residency query), else 0 5484static const int cold_env = [] { 5485const char * v = std::getenv ("STRATA_COLD_OVERLAP" ); 5486return v == nullptr || v [0 ]== '\0' ?-1 : std::clamp (std::atoi (v ),0 ,4 ); 5487 }(); 5488d .cold_mode = cold_env >=0 ?cold_env : (d .src != nullptr && d .src -> linux_file_defaults () ?4 :0 ); 5489pt ("begin" ); 5490const double t_b0_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5491 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGB2: before begin_layer 5492d .src -> begin_layer (d .layers ,ids ,n_tok * k ); 5493pt ("begun" ); 5494if (!d .usage .empty ()) 5495for (int64_t i = 0 ;i < n_tok * k ;++ i ) 5496if (ids [i ] >=0 && ids [i ]< d .n_expert )d .usage [(size_t )d .layers * (size_t )d .n_expert + (size_t )ids [i ]]+= 1.0f ; 5497// ---- plan v0.3 P6: the GPU's share, decided and published FIRST so the GPU starts while the CPU works. 5498// Distinct experts in routing order; resident ones and the last pcie_num/256 of the missed ones go to the GPU. 5499const int64_t n = n_tok * k ; 5500const double t_c0_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5501 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGB: dispatch entry 5502double t_d1_ms = 0 ,t_d2_ms = 0 ,t_k1_ms = 0 ,t_k2_ms = 0 ;// DIAGB2 stamps, assigned inside the plan block 5503static std::atomic < int64_t > s_pinned_ns {0 },s_blob_ns {0 },s_pinned_calls {0 }; 5504static std::atomic < int64_t > s_publish_ns {0 },s_fetch_ns {0 },s_pub_calls {0 }; 5505int32_t kind [kMaxWindowEntries ];// per entry: -1 CPU, 0 VRAM, 1 PCIe 5506if (d .plan != nullptr && n <=kMaxWindowEntries && n <=d .plan -> cap ) { 5507int64_t distinct [kMaxWindowEntries ],first_of [kMaxWindowEntries ]; 5508int nd = 0 ,nmiss = 0 ; 5509// a helper GPU (RemoteExperts) holding the expert computes it in its own VRAM once begin() claims the row: like 5510// the peer tier's, such an expert is no miss of this plan and never part of the PCIe share, which would read it 5511// over the primary's link instead (2x RX 6900 XT, IQ3_S, --remote-expert-opt with the probed share 0.39: ~4 5512// helper experts per layer-window moved to PCIe, 59 ms per window against 34 ms) 5513auto helper_holds = [& ](int32_t e ) { 5514for (int r = 0 ;r < d .remote_count ;++ r ) 5515if (d .remote [r ]-> holds (d .layers ,e ))return true; 5516return false; 5517 }; 5518for (int64_t i = 0 ;i < n ;++ i ) { 5519first_of [i ]= i ; 5520for (int64_t j = 0 ;j < i ;++ j ) 5521if (ids [j ]== ids [i ]) {first_of [i ]= first_of [j ];break ; } 5522if (first_of [i ]== i ) { 5523distinct [nd ++ ]= i ; 5524const int32_t e = ids [i ]; 5525if (e >=0 && e < d .n_expert && d .host_res [(size_t )d .layers * (size_t )d .n_expert + (size_t )e ]< 0 && 5526 !(d .peer != nullptr && d .peer -> has (d .layers ,e ))&& !helper_holds (e ))++ nmiss ; 5527 } 5528 } 5529t_d1_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5530 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGB2: distinct done 5531// STRATA_ROUTE_TAIL_SKIP=R (default 7 on CUDA serve, =0 off; changes the output): a missed expert that EVERY token of the window routes 5532// only at rank >= R (the smallest weights of the top-10) is neither copied nor computed; its contribution is 5533// zero, without renormalisation (the others keep the weight the router gave them). Less PCIe and CPU work. 5534const int tail_rank = tail_skip_rank (); 5535bool skip_d [kMaxWindowEntries ]; 5536for (int q = 0 ;q < nd ;++ q )skip_d [q ]= false; 5537// STRATA_HELPER_RESIDENT=1: the skip also runs beside helper GPUs, for the misses no helper holds 5538static const bool helper_skip = [] {const char * v = std::getenv ("STRATA_HELPER_RESIDENT" );return v != nullptr && std::atoi (v )!= 0 ; }(); 5539if (tail_rank > 0 && d .peer == nullptr && (d .remote_count == 0 || helper_skip )) { 5540int minr [kMaxWindowEntries ]; 5541for (int q = 0 ;q < nd ;++ q )minr [q ]= 99 ; 5542for (int64_t i = 0 ;i < n ;++ i ) { 5543int q = 0 ; 5544while (q < nd && distinct [q ]!= first_of [i ])++ q ; 5545if (q < nd )minr [q ]= std::min (minr [q ], (int ) (i %k )); 5546 } 5547for (int q = 0 ;q < nd ;++ q ) { 5548const int32_t e = ids [distinct [q ]]; 5549if (e < 0 || e >=d .n_expert || minr [q ]< tail_rank )continue ; 5550if (d .host_res [(size_t )d .layers * (size_t )d .n_expert + (size_t )e ] >=0 )continue ;// resident 5551if (helper_holds (e ))continue ;// a helper computes it 5552skip_d [q ]= true; 5553-- nmiss ; 5554++ d .tail_experts ; 5555 } 5556 } 5557// STRATA_ROUTE_DUMP=<file> (bench only, off by default): one text line per layer-window, "layer n_tok nd nmiss | e:rows:res ..." in routing 5558// order (res 1 = resident in the GPU cache, 0 = a miss the CPU computes unless the PCIe share takes it, 2 = tail-skipped), for replaying placement 5559// policies offline on the routing the engine really produced (round 0216 P3.1). 5560static std::FILE * const route_dump = [] {const char * f = std::getenv ("STRATA_ROUTE_DUMP" );return f != nullptr && f [0 ]!= '\0' ? std::fopen (f ,"a" ) :nullptr ; }(); 5561if (route_dump != nullptr ) { 5562 std::fprintf (route_dump ,"%lld %lld %d %d |" , (long long )d .layers , (long long )n_tok ,nd ,nmiss ); 5563for (int q = 0 ;q < nd ;++ q ) { 5564const int32_t e = ids [distinct [q ]]; 5565int rows = 0 ; 5566for (int64_t i = 0 ;i < n ;++ i )rows += first_of [i ]== distinct [q ]; 5567const int res = skip_d [q ] ?2 : (e >=0 && e < d .n_expert && d .host_res [(size_t )d .layers * (size_t )d .n_expert + (size_t )e ]>= 0 ) ?1 :0 ; 5568 std::fprintf (route_dump ," %d:%d:%d" , (int )e ,rows ,res ); 5569 } 5570 std::fputc (10 ,route_dump ); 5571 } 5572t_d2_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5573 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGB2: tail_skip done 5574// STRATA_PCIE_BALANCE (opt-in, #1548): the count comes from the measured CPU and GPU costs instead of the share 5575const bool pcie_ok = (d .pcie_num > 0 || d .pcie_model .on )&& d .src -> pcie_layer (d .layers ); 5576int m = pcie_ok ?d .pcie_model .pick (nmiss , (nmiss * d .pcie_num ) >>8 ) :0 ; 5577// STRATA_PCIE_MIN1 (opt-in): the share rounds to 0 for 1-2 misses per layer, so the PCIe lane idles on the typical 5578// decode step; with >= 2 misses give it at least one (the last in routing order). It only flies if its blob is 5579// pinned (the fetch below checks), else it stays a CPU miss exactly as before. Read once. 5580static const bool pcie_min1 = [] {const char * v = std::getenv ("STRATA_PCIE_MIN1" );return v && std::atoi (v )!= 0 ; }(); 5581if (pcie_min1 && pcie_ok && m < 1 && nmiss >=2 )m = 1 ; 5582int miss_rank = 0 ,groups = 0 ,entries = 0 ,fetches = 0 ; 5583GpuPlanSink & P = * d .plan ; 5584const uint8_t * dma_src [64 ]; 5585int64_t pcie_i0 [64 ]; 5586// STRATA_ADAPT_FETCH: the share is the layer's most-routed misses, and the ones the tier would swap in are copied 5587// into a slot as they are fetched (ExpertDispatch::fetch_admit) 5588const bool fetch_on = m > 0 && d .fetch_can (d .layers ); 5589const float * use = d .usage .empty () ?nullptr :d .usage .data ()+ (size_t )d .layers * (size_t )d .n_expert ; 5590bool pick [kMaxWindowEntries ]; 5591if (fetch_on ) { 5592int mq [kMaxWindowEntries ],nm = 0 ; 5593for (int q = 0 ;q < nd ;++ q ) { 5594pick [q ]= false; 5595const int32_t e = ids [distinct [q ]];// a tail-skipped miss is not fetched 5596// (an unpinned blob cannot be fetched: under STRATA_PIN_BY_NEED a PCIe layer is pinned in part) 5597if (!skip_d [q ]&& e >=0 && e < d .n_expert && d .host_res [(size_t )d .layers * (size_t )d .n_expert + (size_t )e ]< 0 && 5598d .src -> pinned (d .layers ,e )) 5599mq [nm ++ ]= q ; 5600 } 5601 std::stable_sort (mq ,mq + nm , [& ](int a ,int b ) {return use [ids [distinct [a ]]]> use [ids [distinct [b ]]]; }); 5602for (int j = 0 ;j < m && j < nm ;++ j )pick [mq [j ]]= true; 5603 } 5604for (int q = 0 ;q < nd ;++ q ) { 5605const int64_t i0 = distinct [q ]; 5606const int32_t e = ids [i0 ]; 5607int kd = -1 ; 5608unsigned long long ptr = 0 ; 5609if (skip_d [q ]) {// STRATA_ROUTE_TAIL_SKIP: neither copied nor computed 5610for (int64_t i = i0 ;i < n ;++ i ) 5611if (first_of [i ]== i0 )kind [i ]= -2 ; 5612continue ; 5613 } 5614if (e >=0 && e < d .n_expert ) { 5615const int32_t slot = d .host_res [(size_t )d .layers * (size_t )d .n_expert + (size_t )e ]; 5616if (slot >=0 ) { 5617kd = 0 ; 5618ptr = (unsigned long long ) (d .cache_base + (d .cache_slot_off ? (size_t )d .cache_slot_off [slot ] 5619 : (size_t )slot * (size_t )d .cache_blob )); 5620 }else if (d .peer != nullptr && d .peer -> has (d .layers ,e )) { 5621kd = 2 ;// multi-GPU: the second GPU computes it 5622 }else if (helper_holds (e )) { 5623// left to the helper: kind -1 until RemoteExperts::begin() claims the row (see above) 5624 }else if (d .fs != nullptr && d .fs -> take (d .layers ,e ,ptr )) { 5625kd = 0 ;// Foresight: a landed swap-space slot holds it - a GPU group like a hit 5626 }else { 5627if (d .fs != nullptr )d .fs -> note_miss (d .src ,d .layers ,e ); 5628if ((fetch_on ?pick [q ] :miss_rank >=nmiss - m )&& fetches < P .staging_cap && fetches < 64 ) { 5629const uint8_t * src ; 5630 {// DIAGB2: time pinned() and blob() separately (PCIe-share miss only) 5631const auto tp0 = std::chrono::steady_clock::now (); 5632const bool p = d .src -> pinned (d .layers ,e ); 5633const auto tp1 = std::chrono::steady_clock::now (); 5634src = p ?d .src -> blob (d .layers ,e ) :nullptr ; 5635const auto tp2 = std::chrono::steady_clock::now (); 5636s_pinned_ns .fetch_add ((int64_t ) std::chrono::duration_cast < std::chrono::nanoseconds > (tp1 - tp0 ).count (), std::memory_order_relaxed ); 5637s_blob_ns .fetch_add ((int64_t ) std::chrono::duration_cast < std::chrono::nanoseconds > (tp2 - tp1 ).count (), std::memory_order_relaxed ); 5638s_pinned_calls .fetch_add (1 , std::memory_order_relaxed ); 5639 } 5640if (src != nullptr ) { 5641kd = 1 ; 5642dma_src [fetches ]= src ; 5643pcie_i0 [fetches ]= i0 ; 5644++ fetches ; 5645 } 5646 } 5647++ miss_rank ; 5648 } 5649 } 5650for (int64_t i = i0 ;i < n ;++ i ) 5651if (first_of [i ]== i0 )kind [i ]= kd ; 5652if (kd != 0 )continue ;// the VRAM groups first; the PCIe groups below 5653P .ptr [groups ]= ptr ; 5654P .start [groups ]= entries ; 5655for (int64_t i = i0 ;i < n ;++ i ) 5656if (first_of [i ]== i0 ) { 5657P .dst [entries ]= (int32_t )i ; 5658P .tok [entries ]= (int32_t ) (i /k ); 5659++ entries ; 5660 } 5661++ groups ; 5662 } 5663t_k1_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5664 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGB2: kind loop done 5665P .start [groups ]= entries ; 5666const uint64_t bb = lay .blob_bytes (d .layers ); 5667for (int q = 0 ;q < fetches ;++ q ) {// the PCIe groups: staging slot q, entries after the VRAM ones 5668const int64_t i0 = pcie_i0 [q ]; 5669P .ptr2 [q ]= P .pcie_mode != 0 ? (unsigned long long )d .src -> device_alias (d .layers ,ids [i0 ]) 5670 :P .staging + (unsigned long long )q * (unsigned long long )bb ; 5671P .start2 [q ]= entries ; 5672for (int64_t i = i0 ;i < n ;++ i ) 5673if (first_of [i ]== i0 ) { 5674P .dst [entries ]= (int32_t )i ; 5675P .tok [entries ]= (int32_t ) (i /k ); 5676++ entries ; 5677 } 5678++ d .pcie_experts ; 5679 } 5680if (d .fetch_admit > 0 && P .dst2 != nullptr ) 5681for (int q = 0 ;q < fetches ;++ q )P .dst2 [q ]= 0 ;// staging 5682if (fetch_on && fetches > 0 && (size_t )d .layers < d .fetch_avail .size ())d .fetch_avail [(size_t )d .layers ]= 1 ; 5683if (fetch_on && fetches > 0 ) { 5684// the fetched experts routed enough, most-routed first, each against the next least-routed resident expert 5685// of the layer that the window does not route (its slot is read by nothing until the next window) 5686const size_t lb = (size_t )d .layers * (size_t )d .n_expert ; 5687if (d .fetch_mark .size ()!= (size_t )d .n_expert )d .fetch_mark .assign ((size_t )d .n_expert ,0 ); 5688for (int64_t i = 0 ;i < n ;++ i ) 5689if (ids [i ] >=0 && ids [i ]< d .n_expert )d .fetch_mark [(size_t )ids [i ]]= 1 ; 5690int cq [64 ],nc = 0 ; 5691for (int q = 0 ;q < fetches ;++ q ) { 5692const int32_t e = ids [pcie_i0 [q ]]; 5693if (use [e ] >=d .fetch_min && (d .in_flight .empty ()|| d .in_flight [lb + (size_t )e ]== 0 ))cq [nc ++ ]= q ; 5694 } 5695 std::stable_sort (cq ,cq + nc , [& ](int a ,int b ) {return use [ids [pcie_i0 [a ]]]> use [ids [pcie_i0 [b ]]]; }); 5696int32_t vic [64 ]; 5697int nv = 0 ; 5698for (int32_t e = 0 ;e < (int32_t )d .n_expert && nc > 0 ;++ e ) { 5699if (d .res_mut [lb + (size_t )e ]< 0 || d .fetch_mark [(size_t )e ]!= 0 )continue ; 5700if (nv < nc )vic [nv ++ ]= e ; 5701else if (use [e ]< use [vic [nv - 1 ]])vic [nv - 1 ]= e ; 5702else continue ; 5703for (int j = nv - 1 ;j > 0 && use [vic [j ]]< use [vic [j - 1 ]];-- j ) std::swap (vic [j ],vic [j - 1 ]); 5704 } 5705for (int j = 0 ;j < nc && j < nv ;++ j ) { 5706const int q = cq [j ]; 5707const int32_t e = ids [pcie_i0 [q ]],v = vic [j ]; 5708if (use [e ]< use [v ]+ d .fetch_margin )break ; 5709const int32_t slot = d .res_mut [lb + (size_t )v ]; 5710P .dst2 [q ]= (unsigned long long ) (d .cache_base + (d .cache_slot_off ? (size_t )d .cache_slot_off [slot ] 5711 : (size_t )slot * (size_t )d .cache_blob )); 5712d .res_mut [lb + (size_t )v ]= -1 ;// kNotResident 5713d .res_mut [lb + (size_t )e ]= slot ; 5714++ d .fetch_admitted ; 5715d .res_dirty = true; 5716d .res_dirty_idx .push_back ((int32_t ) (lb + (size_t )v )); 5717d .res_dirty_idx .push_back ((int32_t ) (lb + (size_t )e )); 5718if (d .fetch_log_on )d .fetch_log .emplace_back ((int64_t ) (lb + (size_t )e ),slot ); 5719 } 5720for (int64_t i = 0 ;i < n ;++ i ) 5721if (ids [i ] >=0 && ids [i ]< d .n_expert )d .fetch_mark [(size_t )ids [i ]]= 0 ; 5722 } 5723P .start2 [fetches ]= entries ; 5724P .counts [0 ]= groups ; 5725P .counts [1 ]= entries ; 5726P .counts [2 ]= fetches ; 5727 std::atomic_thread_fence (std::memory_order_seq_cst ); 5728pt ("publish" ,fetches ); 5729const auto pp0 = std::chrono::steady_clock::now (); 5730if (P .publish )P .publish (P .ctx ); 5731const auto pp1 = std::chrono::steady_clock::now (); 5732pt ("fetch" ,fetches ); 5733if (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 5734const auto pp2 = std::chrono::steady_clock::now (); 5735s_publish_ns .fetch_add ((int64_t ) std::chrono::duration_cast < std::chrono::nanoseconds > (pp1 - pp0 ).count (), std::memory_order_relaxed ); 5736s_fetch_ns .fetch_add ((int64_t ) std::chrono::duration_cast < std::chrono::nanoseconds > (pp2 - pp1 ).count (), std::memory_order_relaxed ); 5737s_pub_calls .fetch_add (1 , std::memory_order_relaxed ); 5738t_k2_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5739 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGB2: publish+fetch done 5740 }else { 5741for (int64_t i = 0 ;i < n ;++ i ) { 5742const int32_t e = ids [i ]; 5743kind [i ]= (e >=0 && e < d .n_expert && d .host_res != nullptr && 5744d .host_res [(size_t )d .layers * (size_t )d .n_expert + (size_t )e ]>= 0 ) ?0 5745 : (e >=0 && e < d .n_expert && d .peer != nullptr && d .peer -> has (d .layers ,e )) ?2 :-1 ; 5746 } 5747 } 5748if (d .peer != nullptr ) {// multi-GPU: start the second GPU's share before the CPU's own work 5749 std::string perr ; 5750if (!d .peer -> launch (d .layers ,x_f ,ids ,n_tok ,k ,kind ,perr ,out )) { 5751 std::fprintf (stderr ,"strata: %s (layer %lld)\n" ,perr .c_str (), (long long )d .layers ); 5752d .failed = true; 5753d .fail = "the peer GPU's experts could not be launched" ; 5754d .fail_layer = d .layers ; 5755return ; 5756 } 5757 } 5758if (d .remote_count > 0 ) { 5759static thread_local std::string remote_error ; 5760for (int r = 0 ;r < d .remote_count ;++ r ) { 5761if (!d .remote [r ]-> begin (d .layers ,x_f ,ids ,n_tok ,k ,kind ,d .host_res ,remote_error )) { 5762d .failed = true;d .fail = remote_error .c_str ();d .fail_layer = d .layers ;return ; 5763 } 5764for (int64_t i = 0 ;i < n ;++ i )if (d .remote [r ]-> owns (i ))kind [i ]= 2 ; 5765 } 5766 } 5767static const bool dec_batch = [] {const char * v = std::getenv ("STRATA_DEC_BATCH" );return v == nullptr || std::atoi (v )!= 0 ; }(); 5768// the GPU's copy_rows_from_mapped zeroes the rows it computed itself (dec_batch); STRATA_VERIFY_DEVICE_PLAN's 5769// copy_or_zero_from_mapped copies every row, so there the host still zeroes them 5770static const bool device_plan = [] {const char * v = std::getenv ("STRATA_VERIFY_DEVICE_PLAN" );return v != nullptr && std::atoi (v )!= 0 ; }(); 5771const bool gpu_zeroes_hits = (d .plan != nullptr && n <=kMaxWindowEntries && n <=d .plan -> cap && dec_batch && !device_plan ); 5772bool any_cpu = false; 5773for (int64_t i = 0 ;i < n ;++ i ) 5774if (kind [i ]== -1 ) {any_cpu = true;break ; }// -2: skipped (STRATA_ROUTE_TAIL_SKIP), no work 5775if (d .dres_check != nullptr && any_cpu ) {// STRATA_ADAPT_CHECKRES 5776bool published = false; 5777for (int64_t i = 0 ;i < n && !published ;++ i ) 5778published = ids [i ]< 0 || ids [i ] >=d .n_expert || 5779d .dres_check [(size_t )d .layers * (size_t )d .n_expert + (size_t )ids [i ]]< 0 ; 5780if (!published )++ d .stale_x ; 5781 } 5782const double t_kb_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5783 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGB: K wall ends 5784if (d .latent && any_cpu ) {// latent MoE: the CPU share runs the A-blob experts on the host (D -> A -> U) 5785for (int64_t i = 0 ;i < n ;++ i )// counted before the CPU share, which may fail 5786if (ids [i ] >=0 && ids [i ]< d .n_expert )count_route_entry (d ,kind [i ]); 5787static thread_local std::vector < int64_t > lmiss ; 5788static thread_local std::vector < uint8_t > lmiss_mark ;// one pass, no std::find scan 5789lmiss .clear (); 5790if (lmiss_mark .size ()< (size_t )d .n_expert )lmiss_mark .assign ((size_t )d .n_expert ,0 ); 5791for (int64_t i = 0 ;i < n ;++ i ) 5792if (kind [i ]== -1 ) { 5793const int32_t e = ids [i ]; 5794if (e < 0 || e >=d .n_expert || lmiss_mark [(size_t )e ])continue ; 5795lmiss_mark [(size_t )e ]= 1 ; 5796lmiss .push_back (e ); 5797 } 5798if (!lmiss .empty ()&& latent_io_source (d .src )== nullptr ) 5799d .src -> prefetch (d .layers ,lmiss .data (), (int64_t )lmiss .size ()); 5800for (const int64_t e :lmiss )lmiss_mark [(size_t )e ]= 0 ;// the scratch resets for the next call 5801for (int64_t i = 0 ;i < n ;++ i )// STRATA_ROUTE_TAIL_SKIP: a skipped entry's row is zero (the merge copies it) 5802if (kind [i ]== -2 ) std::memset (out + (size_t )i * (size_t )d .lat_H ,0 , (size_t )d .lat_H * sizeof (float )); 5803const auto l0 = std::chrono::steady_clock::now (); 5804const double t_bb_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5805 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ;// DIAGB: B wall ends 5806latent_cpu_run (d ,x_f ,ids ,n_tok ,k ,kind ,out ); 5807const double t_run_ms = std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- l0 ).count (); 5808d .ms_run += t_run_ms ; 5809 {// DIAGB2: fine dispatch-bridge walls (ms/call cumulative mean). RUN = full latent_cpu_run wall. 5810static std::atomic < double > s_beg {0 },s_dist {0 },s_tailw0 {0 },s_kind {0 },s_pcie {0 },s_glue {0 },s_bwall {0 },s_run {0 },s_tailw {0 }; 5811static std::atomic < int64_t > s_bn {0 }; 5812const double t_tb_ms = (double ) std::chrono::duration_cast < std::chrono::nanoseconds > ( 5813 std::chrono::steady_clock::now ().time_since_epoch ()).count () /1e6 ; 5814s_beg .fetch_add (t_c0_ms - t_b0_ms , std::memory_order_relaxed );// begin_layer + usage 5815s_dist .fetch_add (t_d1_ms - t_c0_ms , std::memory_order_relaxed );// distinct + nmiss 5816s_tailw0 .fetch_add (t_d2_ms - t_d1_ms , std::memory_order_relaxed );// tail_skip 5817s_kind .fetch_add (t_k1_ms - t_d2_ms , std::memory_order_relaxed );// kind loop (incl pinned/blob) 5818s_pcie .fetch_add (t_k2_ms - t_k1_ms , std::memory_order_relaxed );// PCIe group fill + publish + fetch 5819s_glue .fetch_add (t_kb_ms - t_k2_ms , std::memory_order_relaxed );// peer/remote/any_cpu/dres_check glue 5820s_bwall .fetch_add (t_bb_ms - t_kb_ms , std::memory_order_relaxed );// lmiss + prefetch + memset(-2) 5821s_run .fetch_add (t_run_ms , std::memory_order_relaxed );// latent_cpu_run full wall 5822s_tailw .fetch_add (t_tb_ms - t_bb_ms - t_run_ms , std::memory_order_relaxed );// tail bookkeeping 5823const int64_t bn = s_bn .fetch_add (1 , std::memory_order_relaxed ); 5824if (std::getenv ("STRATA_DIAG_A" )!= nullptr && bn %48 == 0 ) 5825 std::fprintf (stderr , 5826"DIAGB2 ms/call: beg %.4f dist %.4f tail %.4f kind %.4f pcie %.4f glue %.4f B %.4f RUN %.4f tailw %.4f | pub %.4f fetch %.4f pinned %.4f blob %.4f | pub_c %.2f pin_c %.2f (n %lld)\n" , 5827s_beg .load () / (double ) (bn + 1 ),s_dist .load () / (double ) (bn + 1 ), 5828s_tailw0 .load () / (double ) (bn + 1 ),s_kind .load () / (double ) (bn + 1 ), 5829s_pcie .load () / (double ) (bn + 1 ),s_glue .load () / (double ) (bn + 1 ), 5830s_bwall .load () / (double ) (bn + 1 ),s_run .load () / (double ) (bn + 1 ), 5831s_tailw .load () / (double ) (bn + 1 ), 5832 (double )s_publish_ns .load () /1e6 / (double ) (bn + 1 ), 5833 (double )s_fetch_ns .load () /1e6 / (double ) (bn + 1 ), 5834 (double )s_pinned_ns .load () /1e6 / (double ) (bn + 1 ), 5835 (double )s_blob_ns .load () /1e6 / (double ) (bn + 1 ), 5836 (double )s_pub_calls .load () / (double ) (bn + 1 ), 5837 (double )s_pinned_calls .load () / (double ) (bn + 1 ), 5838 (long long ) (bn + 1 )); 5839 } 5840if (d .plan != nullptr )d .plan -> cpu_jobs = (int )lmiss .size (); 5841d .multi_misses += (int64_t )lmiss .size (); 5842for (int64_t i = 0 ;i < n ;++ i ) { 5843const int64_t e = ids [i ]; 5844if (e >=0 && e < d .n_expert )d .job_of [(size_t )e ]= -1 ; 5845 } 5846++ d .layers ; 5847d .experts += n_tok * k ; 5848return ; 5849 } 5850const auto c1 = std::chrono::steady_clock::now (); 5851if (any_cpu ) { 5852// #578 --remote-expert-opt: a token whose experts all run on a GPU (CUDA0 or a helper) needs no CPU activation 5853const bool ep = d .remote_count > 0 && d .remote [0 ]-> optimized_decode (); 5854for (int64_t t = 0 ;t < n_tok ;++ t ) { 5855if (ep && std::all_of (kind + t * k ,kind + (t + 1 )* k , [](int32_t v ) {return v >=0 ; }))continue ; 5856if (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 5857act_quant_any (x_f + (size_t )t * H ,H ,d .act_multi [(size_t )t ]); 5858else if (native ) 5859native_quant_act (lay .fmt [(size_t )d .layers ],x_f + (size_t )t * H ,d .nact_multi .data ()+ (size_t )t * kNativeActBytes ); 5860else 5861act_quant_q8_1 (x_f + (size_t )t * H ,H ,d .act_multi [(size_t )t ]); 5862 } 5863 } 5864const auto c2 = std::chrono::steady_clock::now (); 5865// 149-cold STRATA_COLD_OVERLAP (d.cold_mode): which of the CPU's experts still have a blob to read. Mode 1 reads 5866// them in the background and computes the ready ones first, then each read one as it lands; every expert keeps 5867// its own token rows (the pool splits rows, never a row's sum), and the weighted sum over a token's experts is 5868// the GPU's, after the dispatch - so the result is the same bits in any batch order. The stage buffers stay 5869// claimed (busy, then young) until the dispatch has joined its reads and run every batch. 5870static thread_local std::vector < int64_t > miss ; 5871static thread_local std::vector < uint8_t > mstate ;// per miss: 0 ready, 1 being read, 2 landed, 3 computed 5872miss .clear (); 5873int64_t npend = 0 ; 5874double cold_r_ms = 0 ; 5875if (any_cpu ) {// CS-T: the experts the CPU computes, fetched together (the GGUF in place reads them on several threads) 5876for (int64_t i = 0 ;i < n_tok * k ;++ i ) 5877if (kind [i ]== -1 && ids [i ] >=0 && ids [i ]< d .n_expert && 5878 std::find (miss .begin (),miss .end (), (int64_t )ids [i ])== miss .end ()) 5879miss .push_back (ids [i ]); 5880if (d .cold_mode == 0 ) { 5881d .src -> prefetch (d .layers ,miss .data (), (int64_t )miss .size ()); 5882 }else { 5883mstate .assign (miss .size (),0 ); 5884const auto r0 = std::chrono::steady_clock::now (); 5885npend = d .src -> prefetch_begin (d .layers ,miss .data (), (int64_t )miss .size (),mstate .data ()); 5886if (npend > 0 && d .cold_mode == 2 ) {// measure: every read first, as mode 0 does 5887d .src -> prefetch_end (); 5888for (uint8_t & s :mstate )if (s == 1 )s = 2 ; 5889cold_r_ms = std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- r0 ).count (); 5890d .ms_cold_wait += cold_r_ms ; 5891 } 5892 } 5893 } 5894// the CPU's experts this batch takes: all (mode 0, or no read), else by their state (want 0: the ready ones, 5895// want 2: those that landed since the last batch) 5896auto take = [& ](int64_t e ,uint8_t want ) { 5897if (npend == 0 )return true; 5898for (size_t q = 0 ;q < miss .size ();++ q ) 5899if (miss [q ]== e )return mstate [q ]== want ; 5900return want == 0 ; 5901 }; 5902int njobs = 0 ,njobs_all = 0 ; 5903bool first_pass = true; 5904uint8_t want = 0 ; 5905double run_ms_extra = 0 ,cr_ms = 0 ; 5906for (;;) { 5907for (int64_t t = 0 ;t < n_tok ;++ t ) 5908for (int64_t j = 0 ;j < k ;++ j ) { 5909const int64_t i = t * k + j ; 5910const int64_t e = ids [i ]; 5911float * row = out + (size_t )i * H ; 5912if (!first_pass && (e < 0 || e >= d .n_expert || kind [i ]!= -1 || !take (e ,want ))) 5913continue ;// a later batch: only the CPU entries of the experts that just landed 5914if (first_pass && kind [i ]== -1 && e >=0 && e < d .n_expert && !take (e ,0 ))continue ;// being read: a later batch 5915if (e < 0 || e >=d .n_expert ) { 5916d .failed = true; 5917d .fail = "a routed expert id is out of range" ; 5918d .fail_layer = d .layers ; 5919d .fail_expert = e ; 5920return ; 5921 } 5922count_route_entry (d ,kind [i ]); 5923if (kind [i ]== -2 ) {// STRATA_ROUTE_TAIL_SKIP: a skipped tail expert contributes zero 5924 std::memset (row ,0 , (size_t )H * sizeof (float )); 5925continue ; 5926 } 5927if (kind [i ] >=0 ) {// CUDA0, PCIe, or a remote/peer result staged into this row below 5928// multi-GPU: a direct peer launch is writing this row right now - zeroing it would race it; 5929// dec_batch: copy_rows_from_mapped_kernel already zeroes kind 0/1 rows on the GPU 5930if (!((kind [i ]== 2 && d .peer != nullptr && d .peer -> launched_direct ())|| 5931 (gpu_zeroes_hits && (kind [i ]== 0 || kind [i ]== 1 )))) 5932 std::memset (row ,0 , (size_t )H * sizeof (float )); 5933continue ; 5934 } 5935int16_t & jo = d .job_of [(size_t )e ]; 5936if (jo < 0 ) { 5937const uint8_t * zp [3 ]= {nullptr ,nullptr ,nullptr }; 5938const bool zc = d .cold_mode >=3 && native && d .src -> zc_roles (d .layers ,e ,zp ); 5939const uint8_t * b = zc ?zp [0 ] :d .src -> blob (d .layers ,e ); 5940if (b == nullptr ) { 5941d .failed = true; 5942d .fail = "the expert source could not produce a blob" ; 5943d .fail_layer = d .layers ; 5944d .fail_expert = e ; 5945++ d .missing ; 5946return ; 5947 } 5948jo = (int16_t )njobs ++ ; 5949ExpertJobMulti & nj = d .jobs_multi [(size_t )jo ]; 5950nj .blob = b ; 5951nj .nt = 0 ; 5952nj .fmt = nullptr ; 5953if (zc ) {// 149-cold mode 3: the gate rows are the blob; up and down at their distance in the mapping 5954if (d .zc_fmt .size ()< d .jobs_multi .size ())d .zc_fmt .resize (d .jobs_multi .size ()); 5955 strata::kernels::cpu::NativeFmt & f = d .zc_fmt [(size_t )jo ]; 5956f = lay .fmt [(size_t )d .layers ]; 5957f .up_off = (size_t ) ((uintptr_t )zp [1 ]- (uintptr_t )zp [0 ]);// modular: the tensors' order 5958f .down_off = (size_t ) ((uintptr_t )zp [2 ]- (uintptr_t )zp [0 ]);// in the file does not matter 5959nj .fmt = & f ; 5960++ d .cold_zc ; 5961 } 5962 } 5963if (d .jobs_multi [(size_t )jo ].nt == MAXT ) { 5964// a window of 9..16 rows routes more than MAXT tokens to this expert: the kernels and the pool's scratch 5965// take MAXT tokens a job, so the rest are a further job over the same blob (each token's rows are its own, 5966// so the split changes no value; the blob is read once more) 5967const int16_t prev = jo ; 5968jo = (int16_t )njobs ++ ; 5969ExpertJobMulti & nj = d .jobs_multi [(size_t )jo ]; 5970nj .blob = d .jobs_multi [(size_t )prev ].blob ; 5971nj .fmt = d .jobs_multi [(size_t )prev ].fmt ; 5972nj .nt = 0 ; 5973 } 5974ExpertJobMulti & jb = d .jobs_multi [(size_t )jo ]; 5975jb .act [jb .nt ]= & d .act_multi [(size_t )t ]; 5976jb .nact [jb .nt ]= native ?d .nact_multi .data ()+ (size_t )t * kNativeActBytes :nullptr ; 5977jb .out [jb .nt ]= row ; 5978++ jb .nt ; 5979++ d .multi_entries ; 5980 } 5981if (npend == 0 )break ; 5982// 149-cold: run this batch now (the ready experts, then each landed group), then wait for the next landing 5983 { 5984const auto b0 = std::chrono::steady_clock::now (); 5985if (njobs > 0 ) { 5986if (native )d .pool -> run_split_multi_native (lay .fmt [(size_t )d .layers ],d .jobs_multi .data (),njobs ,arithmetic ); 5987else d .pool -> run_split_multi (d .jobs_multi .data (),njobs ); 5988++ d .cold_batches ; 5989 } 5990const auto b1 = std::chrono::steady_clock::now (); 5991const double bm = std::chrono::duration < double , std::milli > (b1 - b0 ).count (); 5992run_ms_extra += bm ; 5993if (first_pass ) {d .ms_cold_cr += bm ;cr_ms = bm ; } 5994else d .ms_cold_cc += bm ; 5995if (first_pass )d .cold_ready += njobs ; 5996// the computed ones' job slots are free again (an expert is in one batch only) 5997for (int jx = 0 ;jx < njobs ;++ jx )d .jobs_multi [(size_t )jx ].nt = 0 ; 5998for (int64_t i = 0 ;i < n_tok * k ;++ i ) 5999if (ids [i ] >=0 && ids [i ]< d .n_expert )d .job_of [(size_t )ids [i ]]= -1 ; 6000if (!first_pass )for (uint8_t & s :mstate )if (s == 2 )s = 3 ; 6001njobs_all += njobs ; 6002njobs = 0 ; 6003first_pass = false; 6004want = 2 ; 6005bool left = false; 6006for (uint8_t s :mstate )left = left || s == 1 || s == 2 ; 6007if (!left )break ; 6008if (std::none_of (mstate .begin (),mstate .end (), [](uint8_t s ) {return s == 2 ; })) { 6009const auto w0 = std::chrono::steady_clock::now (); 6010 (void )d .src -> wait_landed (d .layers ,miss .data (), (int64_t )miss .size (),mstate .data ()); 6011d .ms_cold_wait += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- w0 ).count (); 6012 } 6013 } 6014 } 6015if (npend > 0 ) { 6016d .src -> prefetch_end (); 6017const FileExpertSource * fs = dynamic_cast < const FileExpertSource *> (d .src ); 6018const double r_ms = d .cold_mode == 2 ?cold_r_ms : (fs != nullptr ?fs -> async_fill_us () /1e3 :0.0 ); 6019++ d .cold_layers ; 6020d .cold_pending += npend ; 6021d .ms_cold_r += r_ms ; 6022d .ms_cold_hide += std::min (r_ms ,cr_ms );// what an overlap can hide of this layer's reads at most 6023njobs = njobs_all ; 6024d .ms_run += run_ms_extra ;// the batches ran inside the job loop: the pool's time stays the pool's 6025d .ms_jobs -= run_ms_extra ; 6026 } 6027const auto c3 = std::chrono::steady_clock::now (); 6028if (d .plan != nullptr )d .plan -> cpu_jobs = njobs ; 6029pt ("run" ,njobs ); 6030if (njobs > 0 && npend == 0 ) { 6031if (native )d .pool -> run_split_multi_native (lay .fmt [(size_t )d .layers ],d .jobs_multi .data (),njobs ,arithmetic ); 6032else d .pool -> run_split_multi (d .jobs_multi .data (),njobs ); 6033 } 6034if (d .remote_count > 0 ) { 6035static thread_local std::string remote_error ; 6036for (int r = 0 ;r < d .remote_count ;++ r ) 6037if (!d .remote [r ]-> finish (out ,remote_error )) { 6038d .failed = true;d .fail = remote_error .c_str ();d .fail_layer = d .layers ;return ; 6039 } 6040 } 6041if (d .peer != nullptr ) {// multi-GPU: the second GPU's rows, into the same mapped rows 6042 std::string perr ; 6043if (!d .peer -> finish (out ,perr )) { 6044 std::fprintf (stderr ,"strata: %s (layer %lld)\n" ,perr .c_str (), (long long )d .layers ); 6045d .failed = true; 6046d .fail = "the peer GPU's experts failed" ; 6047d .fail_layer = d .layers ; 6048return ; 6049 } 6050 } 6051const auto c4 = std::chrono::steady_clock::now (); 6052pt ("ran" ); 6053auto ms = [](auto a ,auto b ) {return std::chrono::duration < double , std::milli > (b - a ).count (); }; 6054d .ms_plan += ms (c0 ,c1 ); 6055d .ms_actq += ms (c1 ,c2 ); 6056d .ms_jobs += ms (c2 ,c3 ); 6057d .ms_run += ms (c3 ,c4 ); 6058for (int64_t i = 0 ;i < n_tok * k ;++ i ) { 6059const int64_t e = ids [i ]; 6060if (e >=0 && e < d .n_expert )d .job_of [(size_t )e ]= -1 ; 6061 } 6062d .multi_misses += njobs ; 6063++ d .layers ; 6064d .experts += n_tok * k ; 6065} 6066 6067void expert_hit_run (void * user ,void * stream ,HitPhase phase ,const int32_t * ids ,int64_t k ) { 6068ExpertDispatch & d = * (ExpertDispatch * )user ; 6069if (d .failed )return ; 6070cudaStream_t cs = (cudaStream_t )stream ; 6071 6072if (phase == HitPhase ::Launch ) { 6073d .decided = false; 6074d .hit_pending = false; 6075if (!d .hits_ready ()|| ids == nullptr || k <=0 )return ; 6076if ((int64_t )d .is_hit .size ()< k )d .is_hit .resize ((size_t )k ); 6077// STRATA_EXPERT_NIBBLE=1: this split computes a resident expert with the GGUF-block kernels and admits + fills 6078// a missed one with its GGUF blob - neither may meet a layer whose slots hold 4-bit codes (a native pack's 6079// experts run in the verify windows, so this is the backstop, never the path) 6080#if STRATA_EXPERT_NIBBLE_BUILT // compiled out of every other build: nothing is added to the hit split there 6081if (strata::core::nibble::layer (d .layers ).on ) 6082 strata::core::nibble::fatal (d .layers ,"the expert source's hit split (expert_hit_run)" , 6083"it computes resident experts as GGUF blocks and fills slots with GGUF blobs" ); 6084#endif 6085 6086// ================================ THE DECISION, ONCE, ON THIS LAYER'S IDS ================================ 6087// 6088// Every routed expert is asked of the cache. Resident -> the GPU computes it. Not resident -> it is 6089// admitted and filled if there is room (which makes it a hit on THIS call, because the fill and the 6090// kernel are on one stream in that order), and otherwise it stays a miss for the CPU. 6091d .n_hits = 0 ; 6092for (int64_t i = 0 ;i < k ;++ i ) { 6093const int64_t e = ids [i ]; 6094d .is_hit [(size_t )i ]= 0 ; 6095if (e < 0 || e >=d .n_expert )continue ;// out of range: the pool refuses it, with a message 6096int32_t slot = d .cache -> slot_of (d .layers ,e ); 6097if (slot == kNotResident ) { 6098const int32_t cand = d .cache -> admit (d .layers ,e ); 6099if (cand == kNotResident ) { 6100++ d .cache_refused ; 6101continue ; 6102 } 6103// `blob` is asked ONLY for an expert about to be filled, so the source's read counter stays a 6104// count of distinct experts moved rather than of looks. 6105const uint8_t * b = d .src -> blob (d .layers ,e ); 6106 std::string ferr ; 6107if (b == nullptr || !d .cache -> fill_slot (cand ,b ,cs ,ferr , (int64_t ) strata::kernels::cpu::expert_layout ().blob_bytes (d .layers ))) { 6108d .failed = true; 6109d .fail = "the expert cache could not fill a slot" ; 6110d .fail_layer = d .layers ; 6111d .fail_expert = e ; 6112return ; 6113 } 6114d .src -> note_async_read (b ,cs );// #1237: a page-locked stage buffer is not recycled under the queued copy 6115++ d .cache_admitted ; 6116slot = cand ; 6117 }else { 6118++ d .cache_hits ; 6119 } 6120d .is_hit [(size_t )i ]= 1 ; 6121d .h_slot [(size_t )d .n_hits ]= slot ; 6122d .h_dst [(size_t )d .n_hits ]= (int32_t )i ; 6123++ d .n_hits ; 6124 } 6125d .decided = true; 6126if (d .n_hits <=0 )return ;// nothing resident yet: no GPU work, and nothing for `Combine` to add 6127 6128const size_t list_bytes = (size_t )d .n_hits * sizeof (int32_t ); 6129// `hit_out` is ZEROED rather than overwritten: the kernel writes only the rows this layer's hits own, 6130// so a row that was a hit last layer and a miss this one would still hold last layer's expert and 6131// `add_inplace` would sum it in. Finite, plausible, wrong. 6132if (cudaMemsetAsync (d .hit_out ,0 , (size_t )d .parts_elems * sizeof (float ),cs )!= cudaSuccess || 6133cudaMemcpyAsync (d .d_slot ,d .h_slot .data (),list_bytes ,cudaMemcpyHostToDevice ,cs )!= cudaSuccess || 6134cudaMemcpyAsync (d .d_dst ,d .h_dst .data (),list_bytes ,cudaMemcpyHostToDevice ,cs )!= cudaSuccess ) { 6135d .hit_fail = "the hit list could not be staged" ; 6136d .failed = true; 6137d .fail = d .hit_fail ; 6138return ; 6139 } 6140// The activation is quantized HERE rather than reused from `s.moe.x_q8_0`, which `post[l-1]` wrote from 6141// the PREVIOUS layer's `mixed`. `pre[l]` has since overwritten `mixed`, so that buffer is a layer stale 6142// - and a stale activation produces a perfectly finite expert for the wrong input. 6143// **R4.2h: THE SCALED QUANTIZER, SO A HIT REPRODUCES A MISS.** The CPU pool quantizes this same 6144// activation with `act_quant_q8_1` and multiplies by the fp32 `ActQ::scale`; `quantize_q8_0` writes 6145// an fp16 `d` instead, and `bench/micro/act_quant_parity.cu` measured **80 of 80 chunks differing by 6146// up to 4.761e-04 relative**. `quantize_q8_0_scaled` adopts the CPU's rule and scale, and the kernel 6147// takes the fp32 array. Falling back to the old path would silently reintroduce the divergence, so 6148// the scales are required here rather than optional. 6149if (d .x_q8_0_hit_scale == nullptr ) { 6150d .failed = true; 6151d .fail = "the hit path has no fp32 activation scales (R4.2h)" ; 6152return ; 6153 } 6154 strata::kernels::quantize_q8_0_scaled (d .mixed ,d .x_q8_0_hit ,d .x_q8_0_hit_scale , strata::kernels::cpu::H , 6155cs ); 6156if (d .hit_cpu_order ) 6157 strata::kernels::moe_hit_grouped_s2_cpu_order (d .cache_base ,d .d_slot ,d .d_dst ,d .n_hits , 6158d .cache_blob ,d .x_q8_0_hit ,d .hit_scratch ,d .hit_out ,cs ,d .x_q8_0_hit_scale ); 6159else 6160 strata::kernels::moe_hit_grouped_s2 (d .cache_base ,d .d_slot ,d .d_dst ,d .n_hits ,d .cache_blob , 6161d .x_q8_0_hit ,d .hit_scratch ,d .hit_out ,cs ,d .x_q8_0_hit_scale ); 6162d .hit_pending = true; 6163if (d .hit_done != nullptr )cudaEventRecord ((cudaEvent_t )d .hit_done ,cs ); 6164// The A/B arm: ONE driver entry here, and nothing else changes. If the work was waiting for the host 6165// to enter the driver, this is what lets it start while the pool runs. 6166if (d .hit_poke && d .hit_done != nullptr ) (void )cudaEventQuery ((cudaEvent_t )d .hit_done ); 6167return ; 6168 } 6169 6170// Combine: `parts += hit_out`, stream-ordered after the misses were copied into `parts`. 6171if (!d .hit_pending )return ; 6172d .hit_pending = false; 6173// Did the GPU get the hit work done while the CPU was in the pool? This query is itself a driver entry, 6174// so it is the LAST chance to observe a late start: a NOT-READY here means the work had not finished by the 6175// time the pool returned, and with no poke in front of it that can only be because it began after. 6176if (d .hit_done != nullptr ) { 6177if (cudaEventQuery ((cudaEvent_t )d .hit_done )== cudaSuccess )++ d .hit_ready ; 6178else ++ d .hit_late ; 6179 } 6180 strata::kernels::add_inplace (d .parts_out ,d .hit_out ,d .parts_elems ,cs ); 6181} 6182 6183// ================================ THE RESIDENT ARENA (R2.1) ================================ 6184 6185namespace { 6186 6187void hash_u64 (uint64_t & h ,uint64_t v ) { 6188h = fnv1a64 ((const uint8_t * )& v ,sizeof v ,h ); 6189} 6190 6191void hash_text (uint64_t & h ,const std::string & s ) { 6192h = fnv1a64 ((const uint8_t * )s .data (), (uint64_t )s .size (),h ); 6193} 6194 6195bool hash_small_file (const std::filesystem::path & path ,uint64_t & h , std::string & err ) { 6196hash_text (h ,path .filename ().string ()); 6197 std::ifstream f (path , std::ios::binary ); 6198if (!f ) { 6199hash_u64 (h ,0 ); 6200return true; 6201 } 6202hash_u64 (h ,1 ); 6203 std::vector < uint8_t > buf (64u <<10 ); 6204for (;;) { 6205f .read ((char * )buf .data (), (std::streamsize )buf .size ()); 6206const std::streamsize n = f .gcount (); 6207if (n > 0 )h = fnv1a64 (buf .data (), (uint64_t )n ,h ); 6208if (f .eof ())break ; 6209if (!f ) { 6210err = "ArenaExpertSource: cannot hash pack metadata " + path .string (); 6211return false; 6212 } 6213 } 6214return true; 6215} 6216 6217bool hash_sampled_file (const std::filesystem::path & path ,uint64_t & h , std::string & err ) { 6218 std::ifstream f (path , std::ios::binary | std::ios::ate ); 6219if (!f ) { 6220err = "ArenaExpertSource: cannot sample pack source " + path .string (); 6221return false; 6222 } 6223const std::streamoff end = f .tellg (); 6224if (end < 0 ) { 6225err = "ArenaExpertSource: cannot size pack source " + path .string (); 6226return false; 6227 } 6228const uint64_t bytes = (uint64_t )end ; 6229hash_text (h ,path .filename ().string ()); 6230hash_u64 (h ,bytes ); 6231constexpr uint64_t sample = 64u <<10 ; 6232const uint64_t starts [3 ]= {0 ,bytes /2 ,bytes > sample ?bytes - sample :0 }; 6233 std::vector < uint8_t > buf ((size_t ) std::min < uint64_t > (sample ,bytes )); 6234for (uint64_t off :starts ) { 6235if (buf .empty ())break ; 6236const uint64_t at = std::min < uint64_t > (off ,bytes - (uint64_t )buf .size ()); 6237f .clear (); 6238f .seekg ((std::streamoff )at ); 6239f .read ((char * )buf .data (), (std::streamsize )buf .size ()); 6240if ((size_t )f .gcount ()!= buf .size ()) { 6241err = "ArenaExpertSource: short read while hashing pack source " + path .string (); 6242return false; 6243 } 6244hash_u64 (h ,at ); 6245h = fnv1a64 (buf .data (), (uint64_t )buf .size (),h ); 6246 } 6247return true; 6248} 6249 6250bool shared_arena_pack_hash (const std::string & pack_dir ,const std::string & experts_path , 6251const std::string & gguf ,const strata::kernels::cpu::ExpertLayout & lay , 6252uint64_t & out , std::string & err ) { 6253uint64_t h = 1469598103934665603ull ; 6254hash_text (h ,"strata-shared-expert-arena-pack-v1" ); 6255hash_u64 (h , (uint64_t )lay .n_layers ); 6256hash_u64 (h , (uint64_t )lay .n_expert ); 6257hash_u64 (h ,lay .total ); 6258hash_u64 (h ,lay .max_blob ); 6259hash_u64 (h ,lay .native ?1 :0 ); 6260 6261const std::filesystem::path pack (pack_dir ); 6262for (const char * name : {"manifest.json" ,"index.txt" ,"native_experts.txt" }) { 6263if (!hash_small_file (pack /name ,h ,err ))return false; 6264 } 6265 6266if (std::filesystem::exists (experts_path )) { 6267if (!hash_sampled_file (experts_path ,h ,err ))return false; 6268 }else if (!gguf .empty ()) { 6269// Native packs may read experts straight from one or more GGUF shards. Sample every distinct source 6270// file named by native_experts.txt; this keeps the fingerprint cheap while still tying it to the model 6271// bytes rather than only to an equal-size layout. 6272const std::filesystem::path first (gguf ); 6273 std::vector < std::filesystem::path > sources {first }; 6274for (const std::string & name :lay .gguf_file ) { 6275if (name .empty ())continue ; 6276const std::filesystem::path p = first .parent_path () /name ; 6277if (std::find (sources .begin (),sources .end (),p )== sources .end ())sources .push_back (p ); 6278 } 6279for (const auto & p :sources ) { 6280if (!hash_sampled_file (p ,h ,err ))return false; 6281 } 6282 } 6283 6284out = h == 0 ?1 :h ; 6285return true; 6286} 6287 6288}// namespace 6289 6290namespace { 6291/// The GGUF file that holds role `r` (0 gate, 1 up, 2 down) of layer `l`: a name beside the --native shard 6292/// (native_experts.txt v3 per layer, v4 per role), or the --native shard itself. 6293std::string expert_gguf_file (const std::string & gguf ,const strata::kernels::cpu::ExpertLayout & lay ,int64_t l ,int r ) { 6294const size_t i = (size_t ) (3 * l + r ); 6295if (lay .gguf_file .size () <=i || lay .gguf_file [i ].empty ())return gguf ; 6296const size_t cut = gguf .find_last_of ("/\\" ); 6297return (cut == std::string::npos ? std::string () :gguf .substr (0 ,cut + 1 ))+ lay .gguf_file [i ]; 6298} 6299}// namespace 6300 6301void ExpertSource ::record_inputs (const std::string & pack_experts ,const std::string & gguf , 6302const strata::kernels::cpu::ExpertLayout & lay ,bool from_gguf ) { 6303static const char * roles [3 ]= {"gate" ,"up" ,"down" }; 6304inputs_ .clear (); 6305if (!from_gguf ) {inputs_ .push_back ({"pack experts.bin" ,pack_experts });return ; } 6306// the same resolution open_gguf / load_experts_gguf use: every (layer, role) tensor and the file it is read from 6307for (int64_t l = 0 ;l < lay .n_layers ;++ l ) 6308for (int r = 0 ;r < 3 ;++ r ) 6309inputs_ .push_back ({"expert blk." + std::to_string (l )+ ".ffn_" + roles [r ],expert_gguf_file (gguf ,lay ,l ,r )}); 6310} 6311 6312bool check_experts_gguf (const std::string & gguf ,const strata::kernels::cpu::ExpertLayout & lay , std::string & err ) { 6313static const char * roles [3 ]= {"gate" ,"up" ,"down" }; 6314if (lay .gguf_off .size ()!= (size_t ) (3 * lay .n_layers )) { 6315err = "native_experts.txt has no GGUF offsets (a pack older than v2): repack it with tools/iq_pack.py" ; 6316return false; 6317 } 6318try { 6319 std::map < std::string , std::unique_ptr < strata::GgufFile >> files ; 6320for (int64_t l = 0 ;l < lay .n_layers ;++ l ) { 6321const auto & fm = lay .fmt [(size_t )l ]; 6322const uint64_t blob = lay .bytes [(size_t )l ]; 6323const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,blob - fm .down_off }; 6324for (int r = 0 ;r < 3 ;++ r ) { 6325const std::string path = expert_gguf_file (gguf ,lay ,l ,r ); 6326auto & f = files [path ]; 6327if (!f )f = std::make_unique < strata::GgufFile > (path ); 6328const std::string name = "blk." + std::to_string (l )+ ".ffn_" + roles [r ]+ "_exps.weight" ; 6329const strata::TensorInfo * t = f -> find (name ); 6330const uint64_t want_type = (uint64_t ) (r < 2 ?fm .gu_type :fm .d_type ); 6331// GGUF order: dim 0 is the row (the input), dim 1 the rows, dim 2 the experts 6332const uint64_t cols = (uint64_t ) (r < 2 ?fm .n_embd :fm .n_ff ); 6333const uint64_t rows = (uint64_t ) (r < 2 ?fm .n_ff :fm .n_embd ); 6334const uint64_t bytes = per [r ]* (uint64_t )lay .n_expert ; 6335const uint64_t payload = f -> file_size ()- f -> data_start (); 6336 std::string why ; 6337if (t == nullptr )why = "is not in it" ; 6338else if (t -> type != want_type ) 6339why = std::string ("is " )+ t -> type_name ()+ ", the pack says type " + std::to_string (want_type ); 6340else if (t -> shape .size ()!= 3 || t -> shape [0 ]!= cols || t -> shape [1 ]!= rows || 6341t -> shape [2 ]!= (uint64_t )lay .n_expert ) 6342why = "is not [" + std::to_string (cols )+ ", " + std::to_string (rows )+ ", " + 6343 std::to_string (lay .n_expert )+ "]" ; 6344else if (strata::tensor_payload_bytes (* t )!= bytes ) 6345why = "is not " + std::to_string (per [r ])+ " B per expert" ; 6346else if (f -> data_start ()+ t -> offset != lay .gguf_off [(size_t ) (3 * l + r )]) 6347why = "starts at byte " + std::to_string (f -> data_start ()+ t -> offset )+ ", the pack says " + 6348 std::to_string (lay .gguf_off [(size_t ) (3 * l + r )]); 6349else if (t -> offset > payload || bytes > payload - t -> offset ) 6350why = "runs past the end of the file (a truncated shard?)" ; 6351if (!why .empty ()) { 6352err = "the pack's native_experts.txt does not match the model: " + name + " in " + path + " " + 6353why + " - repack with tools/iq_pack.py from this model's shards" ; 6354return false; 6355 } 6356 } 6357 } 6358return true; 6359 }catch (const std::exception & e ) { 6360err = std::string ("native experts from the GGUF: " )+ e .what (); 6361return false; 6362 } 6363} 6364 6365// Plan v0.3 P6: the arena from the model's GGUF shards. Each layer's gate, up and down tensors hold the 512 6366// experts one after another; they are read in chunks and each expert's slice lands at its place in the blob 6367// [gate rows | up rows | down rows] - the layout tools/iq_pack.py would have written to experts.bin. Each role 6368// is read from its own file (native_experts.txt v4: a shard boundary can fall inside a layer; per role as in 6369// #255, gopinath87607). The caller checks the spans first (check_experts_gguf). 6370// `unbuffered` (Windows, experts_unbuffered): each chunk's 4 KiB-aligned window is read with FILE_FLAG_NO_BUFFERING into 6371// an aligned buffer and scattered into the blobs - no copy through the file cache when the drive is read anyway. 6372LoadStats load_experts_gguf (const std::string & gguf ,uint8_t * dst ,const strata::kernels::cpu::ExpertLayout & lay , 6373int threads ,bool unbuffered ,const std::atomic < int >* ready ,const PadMap * pad ) { 6374// where blob (l, e) goes in `dst`: packed (experts.bin) or the padded layout of pin by need 6375auto dst_blob = [& lay ,pad ](int64_t l ,int64_t e )-> uint64_t { 6376return pad != nullptr ?pad -> blob_off (l ,e ) :lay .blob_offset (l ,e ); 6377 }; 6378// `ready`: layer l is written only once *ready > l + 1 (a PinnedArena registering its slices meanwhile; the next 6379// slice too, since its registration starts on the page that may hold this layer's tail) 6380auto wait_ready = [ready ](int64_t l ) { 6381if (ready != nullptr ) 6382while (ready -> load (std::memory_order_acquire ) <=l + 1 ) std::this_thread::yield (); 6383 }; 6384LoadStats st ; 6385st .layers = (uint64_t )lay .n_layers ; 6386const auto t0 = std::chrono::steady_clock::now (); 6387 std::atomic < int64_t > next {0 }; 6388 std::atomic < bool > bad {false}; 6389#if defined(_WIN32 ) 6390if (unbuffered ) { 6391uint64_t max_chunk = 0 ; 6392for (int64_t l = 0 ;l < lay .n_layers ;++ l ) { 6393const auto & fm = lay .fmt [(size_t )l ]; 6394max_chunk = std::max < uint64_t > (max_chunk , std::max < uint64_t > (fm .up_off ,lay .bytes [(size_t )l ]- fm .down_off )* 16 ); 6395 } 6396 std::mutex err_mu ; 6397 std::string err ; 6398auto worker = [& ]() { 6399constexpr uint64_t kSector = 4096 ; 6400const uint64_t cap = (max_chunk + 2 * kSector + kSector - 1 ) /kSector * kSector ; 6401uint8_t * buf = (uint8_t * )VirtualAlloc (nullptr , (size_t )cap ,MEM_COMMIT |MEM_RESERVE ,PAGE_READWRITE ); 6402HANDLE h = INVALID_HANDLE_VALUE ; 6403 std::string open_name ; 6404auto fail = [& ](const std::string & what ) { 6405 std::lock_guard < std::mutex > g (err_mu ); 6406if (err .empty ())err = what ; 6407bad = true; 6408 }; 6409if (buf == nullptr )fail ("cannot allocate a read buffer" ); 6410for (;;) { 6411const int64_t l = next .fetch_add (1 ); 6412if (l >=lay .n_layers || bad )break ; 6413wait_ready (l ); 6414const auto & fm = lay .fmt [(size_t )l ]; 6415const uint64_t blob = lay .bytes [(size_t )l ]; 6416const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,blob - fm .down_off }; 6417const uint64_t at [3 ]= {0 ,fm .up_off ,fm .down_off }; 6418for (int r = 0 ;r < 3 && !bad ;++ r ) { 6419// the handle is kept while consecutive roles share a file (every layer of a v3 pack) 6420const std::string name = expert_gguf_file (gguf ,lay ,l ,r ); 6421if (name != open_name ) { 6422if (h != INVALID_HANDLE_VALUE )CloseHandle (h ); 6423const int wide = MultiByteToWideChar (CP_UTF8 ,0 ,name .c_str (),-1 ,nullptr ,0 ); 6424 std::vector < wchar_t > w ((size_t ) std::max (wide ,1 ),L'\0' ); 6425if (wide > 0 )MultiByteToWideChar (CP_UTF8 ,0 ,name .c_str (),-1 ,w .data (),wide ); 6426h = CreateFileW (w .data (),GENERIC_READ ,FILE_SHARE_READ ,nullptr ,OPEN_EXISTING , 6427FILE_FLAG_NO_BUFFERING |FILE_FLAG_SEQUENTIAL_SCAN ,nullptr ); 6428if (h == INVALID_HANDLE_VALUE ) { 6429fail ("cannot open " + name + " (error " + std::to_string ((unsigned long long )GetLastError ())+ ")" ); 6430break ; 6431 } 6432open_name = name ; 6433 } 6434const uint64_t src = lay .gguf_off [(size_t ) (3 * l + r )]; 6435const uint64_t total = per [r ]* (uint64_t )lay .n_expert ; 6436const uint64_t chunk = per [r ]* 16 ;// 16 experts per read 6437for (uint64_t done = 0 ;done < total ;done += chunk ) { 6438const uint64_t n = std::min < uint64_t > (chunk ,total - done ); 6439const uint64_t a0 = (src + done ) /kSector * kSector ; 6440const uint64_t a1 = (src + done + n + kSector - 1 ) /kSector * kSector ; 6441OVERLAPPED ov {}; 6442ov .Offset = (DWORD )a0 ; 6443ov .OffsetHigh = (DWORD ) (a0 >>32 ); 6444DWORD got = 0 ; 6445// the window may run past the end of the file: only the tensor's own bytes have to arrive 6446if (!ReadFile (h ,buf , (DWORD ) (a1 - a0 ),& got ,& ov )|| (uint64_t )got < src + done - a0 + n ) { 6447fail ("short unbuffered read of layer " + std::to_string (l )+ " in " + name + " (error " + 6448 std::to_string ((unsigned long long )GetLastError ())+ ")" ); 6449break ; 6450 } 6451const uint8_t * q = buf + (src + done - a0 ); 6452for (uint64_t k = 0 ;k < n /per [r ];++ k ) { 6453const uint64_t e = done /per [r ]+ k ; 6454 std::memcpy (dst + dst_blob (l , (int64_t )e )+ at [r ],q + k * per [r ], (size_t )per [r ]); 6455 } 6456 } 6457 } 6458 } 6459if (h != INVALID_HANDLE_VALUE )CloseHandle (h ); 6460if (buf != nullptr )VirtualFree (buf ,0 ,MEM_RELEASE ); 6461 }; 6462 std::vector < std::thread > pool ; 6463for (int i = 1 ;i < threads ;++ i )pool .emplace_back (worker ); 6464worker (); 6465for (auto & t :pool )t .join (); 6466if (bad ) { 6467st .seconds = -1.0 ; 6468st .ok = false; 6469st .error = err .empty () ?"unreadable shard while reading the experts from the GGUF" :err ; 6470return st ; 6471 } 6472st .bytes = lay .total ; 6473st .seconds = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 6474return st ; 6475 } 6476#else 6477 (void )unbuffered ; 6478#endif 6479auto worker = [& ]() { 6480// #230: `fread` on a `FILE*`, as load_experts_ranges (#89): MSVC's `std::ifstream::read` splits a request 6481// into 4095-byte freads, which took this path to 0.02 GiB/s on a Windows install without experts.bin. 6482// The guard closes the handle on every return. 6483struct Closer { 6484FILE * f = nullptr ; 6485 ~Closer () {if (f != nullptr ) std::fclose (f ); } 6486 }file ; 6487 std::string open_name ; 6488 std::vector < uint8_t > buf ; 6489for (;;) { 6490const int64_t l = next .fetch_add (1 ); 6491if (l >=lay .n_layers || bad )break ; 6492wait_ready (l ); 6493const auto & fm = lay .fmt [(size_t )l ]; 6494const uint64_t blob = lay .bytes [(size_t )l ]; 6495const uint64_t per [3 ]= {fm .up_off ,fm .up_off ,blob - fm .down_off }; 6496const uint64_t at [3 ]= {0 ,fm .up_off ,fm .down_off }; 6497for (int r = 0 ;r < 3 ;++ r ) { 6498// the handle is kept while consecutive roles share a file (every layer of a v3 pack) 6499const std::string name = expert_gguf_file (gguf ,lay ,l ,r ); 6500if (name != open_name ) { 6501if (file .f != nullptr ) std::fclose (file .f ); 6502file .f = std::fopen (name .c_str (),"rb" ); 6503if (file .f == nullptr ) {bad = true;return ; } 6504open_name = name ; 6505 } 6506FILE * const f = file .f ; 6507const uint64_t src = lay .gguf_off [(size_t ) (3 * l + r )]; 6508const uint64_t total = per [r ]* (uint64_t )lay .n_expert ; 6509const uint64_t chunk = per [r ]* 16 ;// 16 experts per read 6510buf .resize ((size_t )chunk ); 6511for (uint64_t done = 0 ;done < total ;done += chunk ) { 6512const uint64_t n = std::min < uint64_t > (chunk ,total - done ); 6513// 64-bit seek: a shard is tens of GB 6514if (STRATA_FSEEK64 (f ,src + done )!= 0 ) {bad = true;return ; } 6515if (std::fread (buf .data (),1 , (size_t )n ,f )!= (size_t )n ) {bad = true;return ; } 6516for (uint64_t k = 0 ;k < n /per [r ];++ k ) { 6517const uint64_t e = done /per [r ]+ k ; 6518 std::memcpy (dst + dst_blob (l , (int64_t )e )+ at [r ],buf .data ()+ k * per [r ], (size_t )per [r ]); 6519 } 6520 } 6521 } 6522 } 6523 }; 6524 std::vector < std::thread > pool ; 6525for (int i = 1 ;i < threads ;++ i )pool .emplace_back (worker ); 6526worker (); 6527for (auto & t :pool )t .join (); 6528if (bad ) { 6529st .seconds = -1.0 ; 6530st .ok = false; 6531st .error = "short read or unreadable shard while reading the experts from the GGUF" ; 6532return st ; 6533 } 6534st .bytes = lay .total ; 6535st .seconds = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t0 ).count (); 6536return st ; 6537} 6538 6539ArenaExpertSource ::~ArenaExpertSource () {close (); } 6540 6541bool ArenaExpertSource ::open (const std::string & pack_dir ,int64_t n_layers ,int64_t n_expert ,int threads , 6542 std::string & err ,uint64_t max_pinned_bytes , 6543const std::string & shared_arena_file ) { 6544close (); 6545const std::string path = pack_dir + "/experts.bin" ; 6546// plan v0.3 P6: the layout (canonical, or a native pack's per-layer blobs) was loaded by the driver 6547const strata::kernels::cpu::ExpertLayout & lay = strata::kernels::cpu::expert_layout (); 6548if (lay .n_layers != n_layers || lay .n_expert != n_expert ) { 6549err = "ArenaExpertSource: the expert layout was loaded for a different geometry" ; 6550return false; 6551 } 6552const int64_t blob = (int64_t )lay .max_blob ; 6553const uint64_t want = lay .total ; 6554 6555// plan v0.3 P6: no experts.bin in a native pack -> the experts come straight from the GGUF 6556const bool from_gguf = !std::ifstream (path , std::ios::binary )&& lay .native && !lay .gguf_off .empty ()&& !gguf_ .empty (); 6557// SIZE CHECK BEFORE THE ALLOCATION, not after. A wrong pack should name the two numbers rather than spend 6558// 34 GB and a minute of loading first. 6559if (from_gguf ) { 6560// every (file, offset) of native_experts.txt must be the tensor it claims, of the pack's type and 6561// dimensions and inside its file - before the allocation, so a pack of another model or a truncated 6562// shard is a message rather than an arena of plausible wrong experts 6563if (!check_experts_gguf (gguf_ ,lay ,err )) {err = "ArenaExpertSource: " + err ;return false; } 6564 }else { 6565 std::ifstream f (path , std::ios::binary | std::ios::ate ); 6566if (!f ) {err = "ArenaExpertSource: cannot open " + path ;return false; } 6567const uint64_t got = (uint64_t )f .tellg (); 6568if (got != want && got != want + (uint64_t )blob ) {// + one blob: STRATA_ARENA_MMAP's padded file 6569char buf [400 ]; 6570 std::snprintf (buf ,sizeof buf , 6571"ArenaExpertSource: %s is %llu B but %lld layers x %lld experts (blobs up to %lld B) " 6572"make %llu B - this is not the pack this geometry came from" , 6573path .c_str (), (unsigned long long )got , (long long )n_layers , (long long )n_expert , 6574 (long long )blob , (unsigned long long )want ); 6575err = buf ; 6576return false; 6577 } 6578 } 6579 6580// STRATA_ARENA_MMAP=1 (a small-RAM machine whose GPUs hold most experts): the arena is the pack's experts.bin 6581// mapped READ-ONLY - not locked, not pinned. The page cache keeps what the CPU pool and the prompt path 6582// actually read (the experts no VRAM cache holds) and gives back the rest under memory pressure; a page 6583// dropped is re-read from the file, so a result never depends on what is resident. The GPUs then get no 6584// mapped alias: run with --pcie-frac 0. The first start writes experts.bin (arena layout, padded by one blob 6585// so a whole-slot copy may start at any expert), later ones map it. 6586#if defined(_WIN32 ) 6587static const bool arena_mmap = false;// POSIX mmap/madvise: Linux only for now 6588#else 6589static const bool arena_mmap = [] {const char * v = std::getenv ("STRATA_ARENA_MMAP" );return v && v [0 ]== '1' ; }(); 6590if (arena_mmap ) { 6591const uint64_t file_bytes = want + (uint64_t )blob ; 6592uint64_t have = 0 ; 6593 { 6594 std::ifstream f (path , std::ios::binary | std::ios::ate ); 6595if (f )have = (uint64_t )f .tellg (); 6596 } 6597if (have == file_bytes ) { 6598const int fd = ::open (path .c_str (),O_RDONLY ); 6599void * v = fd >=0 ?mmap (nullptr , (size_t )file_bytes ,PROT_READ ,MAP_SHARED ,fd ,0 ) :MAP_FAILED ; 6600if (fd >=0 ) ::close (fd ); 6601if (v == MAP_FAILED ) {err = "ArenaExpertSource: mmap of " + path + " failed" ;return false; } 6602map_ = v ; 6603map_bytes_ = file_bytes ; 6604base_ = (const uint8_t * )v ; 6605pinned_bytes_ = 0 ; 6606dev_slice_ .clear (); 6607slice_bytes_ = 0 ; 6608ranges_ = false; 6609blobs_ = n_layers * n_expert ; 6610n_expert_ = n_expert ; 6611reads_ = 0 ; 6612note_ = "mapped read-only from " + path + " (STRATA_ARENA_MMAP: not locked, not pinned)" ; 6613gib_per_s_ = 0.0 ; 6614load_seconds_ = load_read_s_ = load_copy_s_ = 0.0 ; 6615record_inputs (path ,gguf_ ,lay ,from_gguf );// session files: the mapped experts.bin is a model input 6616return true; 6617 } 6618 } 6619#endif 6620 6621// #633: THE RAM BEFORE THE ALLOCATION. On Linux the arena is an anonymous mapping that succeeds whatever the host 6622// has; its pages are committed as the load writes them, so a container whose memory limit is below the arena was 6623// killed by the OOM killer part-way through the load, without a message. A hard cgroup limit below it is 6624// certain to end that way: refused, with the numbers. Less RAM available than the arena (another program, an 6625// engine still exiting) is only a warning - the OS may make room - per the recommend-not-force rule. 6626ram_warning_ .clear (); 6627ram_short_ = false; 6628// (a shared arena, --shared-expert-arena, may already be in RAM for another engine: not checked) 6629if (detail::HostMemory hm ;shared_arena_file .empty ()&& detail::host_available_memory (hm )) { 6630// --ram-keep-gib W: the arena is chosen only if W GiB stay free after it, so its need here is the arena plus W 6631const uint64_t need = arena_need_with_keep (want + (uint64_t )blob ,ram_keep_bytes ); 6632// under a hard limit the arena also needs the headroom (the engine's own memory comes on top of it, and the arena is never given back) 6633const uint64_t limit_need = arena_hard_limit_need (want + (uint64_t )blob ,ram_keep_bytes ,hard_limit_headroom_bytes ,fall_back_when_ram_short ); 6634const double gib = 1073741824.0 ; 6635char buf [512 ]; 6636char keep_note [96 ]= "" ; 6637if (ram_keep_bytes > 0 ) 6638 std::snprintf (keep_note ,sizeof keep_note ,", with the %.2f GiB --ram-keep-gib asks to leave free" , (double )ram_keep_bytes /gib ); 6639if (arena_ram_verdict (limit_need , ~uint64_t {0 },hm .cgroup_limit ,fall_back_when_ram_short )!= ArenaRamVerdict ::Load ) { 6640if (fall_back_when_ram_short ) {// #4846: the caller reads the experts from the file instead of refusing 6641 std::snprintf (buf ,sizeof buf ,"it needs %.2f GiB (with the %.2f GiB the engine's own memory and the RAM to keep take on top of it) and this process's memory limit is %.2f GiB" , 6642 (double )limit_need /gib , (double ) (limit_need - (want + (uint64_t )blob )) /gib , (double )hm .cgroup_limit /gib ); 6643err = buf ; 6644ram_short_ = true; 6645return false; 6646 } 6647 std::snprintf (buf ,sizeof buf , 6648"ArenaExpertSource: the expert arena needs %.2f GiB of RAM but this process's memory limit " 6649"(cgroup memory.max / memory.limit_in_bytes) is %.2f GiB: it would be killed while loading. " 6650"Raise the container's limit, or run with less RAM: --mmap-experts with " 6651"--resident-budget-gib N keeps only the hottest experts in RAM" , 6652 (double )need /gib , (double )hm .cgroup_limit /gib ); 6653err = buf ; 6654return false; 6655 } 6656if (hm .available < need ) { 6657// #4051: the shortfall is often an engine that was still exiting (the code's own example), a few seconds 6658// from giving its RAM back: wait for it, not for ever, and say so. STRATA_ARENA_RAM_WAIT_S changes the 6659// seconds (0 loads at once, as before this wait). Still short after it (and after the give-back below): the caller's 6660// --mmap-experts fallback (#4846) when it asked for one, otherwise the load goes on and only warns. 6661double wait_s = 20.0 ; 6662if (const char * w = std::getenv ("STRATA_ARENA_RAM_WAIT_S" );w != nullptr && w [0 ]!= '\0' ) { 6663char * end = nullptr ; 6664const double v = std::strtod (w ,& end ); 6665if (end != w && * end == '\0' && v >=0.0 && v <=3600.0 )wait_s = v ; 6666 } 6667double waited = 0.0 ; 6668uint64_t avail = hm .available ; 6669if (wait_s > 0.0 ) { 6670const bool came = detail::wait_for_ram ( 6671need ,wait_s ,0.25 ,5.0 , 6672 [](uint64_t & a ) { detail::HostMemory h ;if (!detail::host_available_memory (h ))return false;a = h .available ;return true; }, 6673 [](double s ) { std::this_thread::sleep_for (std::chrono::duration < double > (s )); }, 6674 [& ](double w ,uint64_t a ) { 6675 std::fprintf (stderr ,"strata generate: the expert arena needs %.2f GiB of RAM%s and %.2f GiB is " 6676"available; waiting up to %.0f s for it (another engine still exiting?) - " 6677"%.0f s so far (STRATA_ARENA_RAM_WAIT_S changes this)\n" , 6678 (double )need /gib ,keep_note , (double )a /gib ,wait_s ,w ); 6679 }, 6680waited ,avail ); 6681if (came ) 6682 std::fprintf (stderr ,"strata generate: %.2f GiB of RAM is available now (after %.1f s): loading the " 6683"expert arena\n" , (double )avail /gib ,waited ); 6684hm .available = avail ; 6685 } 6686if (hm .available < need && give_back_ram ) { 6687// #4846: the shortfall survived the wait. A lock the engine took by itself (the PLE table's residency lock) is 6688// given back before the registration starts: its pages stay cached, the OS may take them for the arena. 6689const uint64_t freed = give_back_ram (); 6690if (freed > 0 ) { 6691 detail::HostMemory h2 ; 6692if (detail::host_available_memory (h2 )) { 6693 std::fprintf (stderr ,"strata generate: the expert arena needs %.2f GiB of RAM and %.2f GiB was available: " 6694"gave back %.2f GiB of locked RAM, %.2f GiB is available now\n" , 6695 (double )need /gib , (double )hm .available /gib , (double )freed /gib , (double )h2 .available /gib ); 6696hm .available = h2 .available ; 6697 } 6698 } 6699 } 6700const ArenaRamVerdict verdict = arena_ram_verdict (need ,hm .available , ~uint64_t {0 },fall_back_when_ram_short ); 6701#if defined(__linux__ ) 6702// #5327: the refusal reads every shortfall as one the kernel can only serve by taking another program's 6703// memory (#4051's host: an engine that was still exiting, anonymous RAM - the stall the refusal is for). 6704// On a bare Linux host the usual false alarm is a reserved hugetlb pool: MemAvailable does not count free 6705// huge pages, and a launcher may reserve the pool for exactly this arena (the arena maps MAP_HUGETLB 6706// first), so the reserve itself takes MemAvailable below the need while the pool holds all of it. That 6707// is the case 0.1.54/0.1.55 loaded anyway ("expert arena read through the file cache") at full decode 6708// speed: credit the pool when it holds the whole arena (and free pages + droppable file pages, which the 6709// kernel evicts as the arena reads - only a small margin beyond MemAvailable's own count) and load, 6710// LOUDLY (a service setup never sees stderr). STRATA_ARENA_FILE_CACHE=0 6711// refuses as since 0.1.56. Not under a cgroup limit (the host's cache is not the container's to drop) 6712// and not on Windows: the proceed path was never trusted there ("buffered (not Windows)", the mapped 6713// view's trim needs the headroom the refusal keeps). 6714const bool file_cache_off = [] {const char * v = std::getenv ("STRATA_ARENA_FILE_CACHE" );return v != nullptr && v [0 ]== '0' ; }(); 6715bool file_cache_arena = false; 6716uint64_t memfree_b = 0 ,droppable_b = 0 ,huge_free_b = 0 ; 6717if (verdict == ArenaRamVerdict ::FallBack && hm .cgroup_limit == ~uint64_t {0 }&& !file_cache_off ) { 6718if (std::ifstream info ("/proc/meminfo" );info ) { 6719const std::string text ((std::istreambuf_iterator < char > (info )), std::istreambuf_iterator < char > ()); 6720if (meminfo_free_and_droppable (text ,memfree_b ,droppable_b ,& huge_free_b )) { 6721// the pool serves the arena only if the MAP_HUGETLB try is made (STRATA_NO_LARGEPAGES skips it) and 6722// the pool holds the whole mapping, which is the padded arena plus the spare blob, not `want + blob` 6723uint64_t map_bytes = want + (uint64_t )blob ; 6724if (pin_by_need_ && !pin_pairs_ .empty ()&& !arena_mmap && shared_arena_file .empty ()) { 6725uint64_t at = 0 ; 6726for (int64_t l = 0 ;l < n_layers ;++ l ) 6727at += ((lay .blob_bytes (l )+ 4095 )& ~(uint64_t )4095 )* (uint64_t )n_expert ; 6728map_bytes = at + (uint64_t )blob ; 6729 } 6730if (std::getenv ("STRATA_NO_LARGEPAGES" )!= nullptr || huge_free_b < map_bytes )huge_free_b = 0 ; 6731file_cache_arena = arena_shortfall_served_by_file_cache (need ,memfree_b ,droppable_b ,huge_free_b ); 6732 } 6733 } 6734 } 6735if (file_cache_arena ) { 6736 std::snprintf (buf ,sizeof buf , 6737"the experts need %.2f GiB of RAM and %.2f GiB is free, but free memory, file cache and reserved huge " 6738"pages can hold them, so they load anyway (same answers). STRATA_ARENA_FILE_CACHE=0 reads them from " 6739"the file instead." , 6740 (double )need /gib , (double )hm .available /gib ); 6741ram_warning_ = buf ;// the caller says it on stderr before the load's numbers 6742if (notices_on_stdout ) {// --serve only: a service setup never sees stderr (#5327); a plain run keeps its token stream clean 6743 std::printf ("strata generate: WARNING: %s\n" ,buf ); 6744 std::fflush (stdout ); 6745 } 6746 }else 6747#endif 6748if (verdict == ArenaRamVerdict ::FallBack ) { 6749// #4846 (owner 11-01): still short after the wait and the give-back. Registering anyway can stall the whole host in 6750// reclaim until it is power-cycled: nothing is allocated, the caller takes the --mmap-experts source for this run. 6751 std::snprintf (buf ,sizeof buf , 6752"it needs %.2f GiB%s and %.2f GiB is available (%.2f GiB short%s)" , 6753 (double )need /gib ,keep_note , (double )hm .available /gib , (double ) (need - hm .available ) /gib , 6754waited > 0.0 ?", after waiting" :"" ); 6755err = buf ; 6756ram_short_ = true; 6757return false; 6758 } 6759if (hm .available < need && ram_warning_ .empty ()) { 6760 std::snprintf (buf ,sizeof buf , 6761"the expert arena needs %.2f GiB of RAM but %.2f GiB is available (%.2f GiB short%s): the " 6762"load may swap or be stopped by the OS%s. Close other programs, or run with less RAM: " 6763"--mmap-experts with --resident-budget-gib N" , 6764 (double )need /gib , (double )hm .available /gib , (double ) (need - hm .available ) /gib , 6765waited > 0.0 ?", after waiting" :"" , 6766hm .available < need /2 ?" - with this little room the whole machine can stall in " 6767"memory reclaim until it is restarted (#4051); on Linux a " 6768"systemd MemoryHigh= below the RAM keeps one program from " 6769"taking all of it" :"" ); 6770ram_warning_ = buf ; 6771 } 6772 } 6773 } 6774 6775uint64_t pack_hash = 0 ; 6776if (!shared_arena_file .empty ()&& 6777 !shared_arena_pack_hash (pack_dir ,path ,gguf_ ,lay ,pack_hash ,err ))return false; 6778 6779// one layer per registration slice, so no expert straddles two registrations. The arena is one blob 6780// longer than the file: a copy of a whole VRAM slot (the largest blob) may then start at any expert. 6781 std::vector < uint64_t > bounds ,loff ,lbytes ; 6782for (int64_t l = 0 ;l < n_layers ;++ l ) { 6783bounds .push_back (lay .layer_offset (l )); 6784loff .push_back (lay .layer_offset (l )); 6785lbytes .push_back (lay .blob_bytes (l )* (uint64_t )n_expert ); 6786 } 6787bounds .push_back (want ); 6788// Pin by need: the arena gets a page-aligned blob STRIDE (blob rounded up to 4 KiB, ~+0.15 %), so every blob starts 6789// on a page and any set of blobs can be registered exactly (a canonical blob is 337.5 pages: packed, an isolated 6790// blob could never be registered without its neighbours' bytes). Not with the mapped arena file (STRATA_ARENA_MMAP 6791// writes experts.bin from the arena). The file offsets (loff) stay packed; only the destination moves. 6792padded_ = false; 6793pad_ = PadMap {}; 6794if (pin_by_need_ && !pin_pairs_ .empty ()&& !arena_mmap && shared_arena_file .empty ()) {// (a shared arena file has one layout for every process: the packed one) 6795padded_ = true; 6796uint64_t at = 0 ; 6797for (int64_t l = 0 ;l < n_layers ;++ l ) { 6798const uint64_t b = lay .blob_bytes (l ),s = (b + 4095 )& ~(uint64_t )4095 ; 6799pad_ .dst_off .push_back (at ); 6800pad_ .blob .push_back (b ); 6801pad_ .stride .push_back (s ); 6802at += s * (uint64_t )n_expert ; 6803 } 6804pad_ .total = at ; 6805 } 6806const uint64_t arena_bytes = padded_ ?pad_ .total :want ;// the spare blob below comes on top, as before 6807// Pin by need: the pairs set_pin_priority gave, as byte ranges in priority order. Neighbours (adjacent blobs) merge 6808// into one range that takes the best rank of its members, so the hottest experts are registered first and the 6809// number of cudaHostRegister calls stays far below the number of pairs. 6810 std::vector < std::pair < uint64_t ,uint64_t >> need_ranges ; 6811const bool by_need = padded_ ; 6812if (by_need ) { 6813// every blob starts on a page and owns its whole stride (pad included), so a run of adjacent blobs is one exact 6814// range: [first start, last start + stride). The best rank of a run's members is its priority. 6815struct Ext {uint64_t off ,len ;size_t rank ;int tier ; }; 6816 std::vector < Ext > ex ; 6817ex .reserve (pin_pairs_ .size ()); 6818 std::vector < uint8_t > seen ((size_t ) (n_layers * n_expert ),0 ); 6819for (size_t i = 0 ;i < pin_pairs_ .size ();++ i ) { 6820const int64_t l = pin_pairs_ [i ].first ,e = pin_pairs_ [i ].second ; 6821if (l < 0 || l >=n_layers || e < 0 || e >=n_expert || seen [(size_t ) (l * n_expert + e )])continue ; 6822seen [(size_t ) (l * n_expert + e )]= 1 ; 6823ex .push_back ({arena_off (l ,e ),pad_ .stride [(size_t )l ],i ,i < pin_first_ ?0 :1 }); 6824 } 6825 std::sort (ex .begin (),ex .end (), [](const Ext & a ,const Ext & b ) {return a .off < b .off ; }); 6826 std::vector < Ext > merged ; 6827for (const Ext & x :ex ) { 6828if (!merged .empty ()&& merged .back ().off + merged .back ().len == x .off && merged .back ().tier == x .tier ) { 6829merged .back ().len += x .len ; 6830merged .back ().rank = std::min (merged .back ().rank ,x .rank ); 6831 }else { 6832merged .push_back (x ); 6833 } 6834 } 6835 std::stable_sort (merged .begin (),merged .end (), [](const Ext & a ,const Ext & b ) {return a .rank < b .rank ; }); 6836for (const Ext & x :merged )need_ranges .emplace_back (x .off ,x .len ); 6837 } 6838// #285: on Windows the per-layer registration runs on a thread ahead of the readers, which wait for their 6839// layer's slice (the whole arena registered before the load cost ~2.5 s at 33 GiB of 4 KB pages, not hidden). 6840// Only where the whole arena would be registered: no cap (STRATA_ARENA_PIN_GIB, multi-GPU), no shared arena. 6841// Linux keeps the whole-arena pin (#253). OPT-IN (STRATA_DEFERRED_REGISTER=1): on the RTX 5070 / Windows the 6842// arena registered per layer before it is filled decoded ~10% slower than the old order (whole-arena try, sliced 6843// fallback after the load) with identical output; the start-time gain does not pay for that. 6844#ifdef _WIN32 6845const char * defer_env = std::getenv ("STRATA_DEFERRED_REGISTER" ); 6846const bool deferred = !by_need && max_pinned_bytes == 0 && arena_pin_cap_gib ()== -1 && shared_arena_file .empty ()&& 6847 (defer_env != nullptr && defer_env [0 ]!= 0 && defer_env [0 ]!= '0' ); 6848#else 6849const bool deferred = false; 6850#endif 6851PinnedArena * a = by_need ?new PinnedArena (arena_bytes + (uint64_t )blob ,PinnedArena ::ByNeed {},need_ranges , 6852max_pinned_bytes ,shared_arena_file ,pack_hash ) 6853 :deferred ?new PinnedArena (want + (uint64_t )blob ,bounds ,PinnedArena ::Deferred {}) 6854 :new PinnedArena (want + (uint64_t )blob ,bounds ,max_pinned_bytes , 6855shared_arena_file ,pack_hash ); 6856if (!a -> valid ()) { 6857const std::string why = a -> note ; 6858delete a ; 6859err = "ArenaExpertSource: the arena could not be reserved (" + 6860 std::to_string (want + (uint64_t )blob )+ " B)" + 6861 (why .empty () ? std::string {} :": " + why ); 6862return false; 6863 } 6864// #285: unbuffered when the drive is read anyway and the file cache could not keep the experts for the next 6865// start either (a 64 GB PC); otherwise the buffered readers, which a warm restart serves from the cache 6866 std::vector < std::string > files ; 6867if (from_gguf ) { 6868for (int64_t l = 0 ;l < n_layers ;++ l ) 6869for (int r = 0 ;r < 3 ;++ r ) { 6870const std::string f = expert_gguf_file (gguf_ ,lay ,l ,r ); 6871if (std::find (files .begin (),files .end (),f )== files .end ())files .push_back (f ); 6872 } 6873 }else { 6874files .push_back (path ); 6875 } 6876 std::string why ; 6877const bool unbuffered = experts_unbuffered (files ,want + (uint64_t )blob ,why ); 6878const int readers = unbuffered ? std::max (threads ,16 ) :threads ;// 16 keep a PCIe 5 drive's queue full 6879LoadStats st ; 6880// A shared arena (--shared-expert-arena, the replicas): ONE engine reads the experts into it, the others wait and skip the 6881// read. The state word in the file's header says who: 0 nobody, a pid loading, ~0 filled. An engine that finds a 6882// pid that is gone takes the load over (the previous one died mid-read: the arena is read again from the start), so a 6883// dead loader never leaves the others waiting, and an engine that waits too long loads it itself. 6884constexpr uint64_t kArenaFilled = ~uint64_t {0 }; 6885 std::atomic < uint64_t >* arena_state = padded_ ?nullptr :a -> shared_state ; 6886bool arena_leader = false,arena_skip = false; 6887if (arena_state != nullptr ) { 6888const uint64_t me = arena_this_pid (); 6889const auto t_begin = std::chrono::steady_clock::now (); 6890bool said = false; 6891for (;;) { 6892uint64_t cur = arena_state -> load (std::memory_order_acquire ); 6893if (cur == kArenaFilled ) {arena_skip = true;break ; } 6894if (cur == 0 || cur == me ) { 6895if (arena_state -> compare_exchange_strong (cur ,me , std::memory_order_acq_rel )) {arena_leader = true;break ; } 6896continue ; 6897 } 6898const bool alive = arena_pid_alive (cur ); 6899if (!alive ) { 6900if (arena_state -> compare_exchange_strong (cur ,me , std::memory_order_acq_rel )) { 6901 std::fprintf (stderr ,"strata generate: shared expert arena: engine %llu died while reading it; reading it again\n" , 6902 (unsigned long long )cur ); 6903arena_leader = true; 6904break ; 6905 } 6906continue ; 6907 } 6908if (std::chrono::steady_clock::now ()- t_begin > std::chrono::minutes (45 ))break ;// (loads it on its own) 6909if (!said ) { 6910said = true; 6911 std::fprintf (stderr ,"strata generate: shared expert arena: engine %llu is reading the experts; waiting for it " 6912"instead of reading them again\n" , (unsigned long long )cur ); 6913 } 6914 std::this_thread::sleep_for (std::chrono::milliseconds (200 )); 6915 } 6916 } 6917 std::atomic < int > ready {0 }; 6918 std::thread reg ; 6919if (deferred ) { 6920int dev = 0 ; 6921cudaGetDevice (& dev ); 6922reg = std::thread ([a ,& ready ,dev ] { 6923cudaSetDevice (dev ); 6924a -> register_slices (ready ); 6925 }); 6926 } 6927const std::atomic < int >* rp = deferred ?& ready :nullptr ; 6928if (arena_skip ) { 6929st .ok = true; 6930st .bytes = want ; 6931st .seconds = 0.0 ; 6932 std::fprintf (stderr ,"strata generate: shared expert arena: already filled by another engine; the read is skipped\n" ); 6933 }else if (from_gguf ) { 6934st = load_experts_gguf (gguf_ ,a -> data (),lay ,readers ,unbuffered ,rp ,padded_ ?& pad_ :nullptr ); 6935 }else { 6936if (unbuffered && !padded_ )st = load_experts_direct (path ,a -> data (),loff ,lbytes ,readers ,/*chunk=*/ 8u <<20 ,rp ); 6937if (!unbuffered || padded_ || (!st .ok && st .error .empty ()))// unaligned ranges / the padded layout: the buffered reader 6938st = load_experts_ranges (path ,a -> data (),loff ,lbytes ,threads ,/*chunk=*/ 8u <<20 ,rp ,padded_ ?& pad_ :nullptr , 6939/*drop_behind=*/ strata::core::page_cache_drop::enabled ());// integrated gfx11 under Linux 6940 } 6941if (reg .joinable ())reg .join (); 6942 std::fprintf (stderr ,"strata generate: expert arena read %s (%s)\n" ,unbuffered ?"unbuffered" :"through the file cache" , 6943why .c_str ()); 6944if (!st .ok ) { 6945if (arena_leader )arena_state -> store (0 , std::memory_order_release );// (somebody else may try) 6946delete a ; 6947err = "ArenaExpertSource: the expert load was refused: " + (st .error .empty () ? std::string ("unknown" ) :st .error ); 6948return false; 6949 } 6950if (st .bytes != want ) { 6951if (arena_leader )arena_state -> store (0 , std::memory_order_release ); 6952delete a ; 6953err = "ArenaExpertSource: the load read " + std::to_string (st .bytes )+ " B of " + std::to_string (want ); 6954return false; 6955 } 6956if (arena_leader )arena_state -> store (kArenaFilled , std::memory_order_release );// the others may use (and skip reading) it 6957if (std::getenv ("STRATA_VERIFY_ARENA" )!= nullptr ) {// tests: the loaded arena's checksum, any loader 6958 std::fprintf (stderr ,"strata generate: expert arena checksum %016llx (%.2f GiB)\n" , 6959 (unsigned long long )fnv1a64 (a -> data (),want ), (double )want / (1ull <<30 )); 6960 } 6961// the first start: write experts.bin for the mapped starts after this one - only when the drive has room for it 6962// and 2 GiB more (a full drive fails other writes too); otherwise this start says so and runs pinned as before 6963 std::error_code space_ec ; 6964const uint64_t free_disk = arena_mmap && from_gguf ? (uint64_t ) std::filesystem::space ( 6965 std::filesystem::path (path ).parent_path (),space_ec ).available :0 ; 6966const bool room = !space_ec && free_disk >=want + (uint64_t )blob + (2ull <<30 ); 6967if (arena_mmap && from_gguf && !room ) 6968 std::fprintf (stderr ,"strata generate: STRATA_ARENA_MMAP: NOT writing %s - %.1f GiB free on that drive, it needs " 6969"%.1f GiB plus 2 GiB to spare; this start keeps the arena in RAM\n" ,path .c_str (), 6970 (double )free_disk /1073741824.0 , (double ) (want + (uint64_t )blob ) /1073741824.0 ); 6971if (arena_mmap && from_gguf && room ) { 6972const std::string tmp = path + ".tmp" ; 6973 std::FILE * f = std::fopen (tmp .c_str (),"wb" ); 6974bool ok = f != nullptr && std::fwrite (a -> data (),1 , (size_t )want ,f )== (size_t )want ; 6975if (ok ) { 6976 std::vector < uint8_t > pad ((size_t )blob ,0 ); 6977ok = std::fwrite (pad .data (),1 ,pad .size (),f )== pad .size (); 6978 } 6979if (f )ok = std::fclose (f )== 0 && ok ; 6980if (ok )ok = std::rename (tmp .c_str (),path .c_str ())== 0 ; 6981if (!ok ) std::remove (tmp .c_str ()); 6982 std::fprintf (stderr ,"strata generate: STRATA_ARENA_MMAP: %s %s (the next start maps it)\n" , 6983ok ?"wrote" :"could NOT write" ,path .c_str ()); 6984 } 6985arena_ = a ; 6986base_ = a -> data (); 6987pinned_bytes_ = a -> registered_bytes ; 6988// plan v0.3 P6: device aliases of the mapped registration, for the PCIe share of the misses 6989dev_slice_ .clear (); 6990slice_bytes_ = a -> slice_bytes ; 6991pin_start_ .clear ();pin_end_ .clear ();pin_dev_ .clear ();layer_pcie_ .clear (); 6992ranges_ = false; 6993if (a -> by_need ) { 6994// device alias of each registered range's start (device_alias adds the blob's distance from it); one 6995// refusal drops the whole table: no PCIe share rather than a wrong pointer 6996ranges_ = true; 6997for (const auto & r :a -> pin_ranges ) { 6998void * d = nullptr ; 6999if (cudaHostGetDevicePointer (& d , (void * ) (base_ + r .first ),0 )!= cudaSuccess ) { 7000 (void )cudaGetLastError (); 7001ranges_ = false; 7002break ; 7003 } 7004pin_start_ .push_back (r .first ); 7005pin_end_ .push_back (r .first + r .second ); 7006pin_dev_ .push_back ((const uint8_t * )d ); 7007 } 7008if (!ranges_ ) { 7009pin_start_ .clear ();pin_end_ .clear ();pin_dev_ .clear (); 7010pinned_bytes_ = 0 ; 7011 }else { 7012layer_pcie_ .assign ((size_t )n_layers ,0 ); 7013n_expert_ = n_expert ;// pinned() reads it; the common tail below sets the same value 7014for (int64_t l = 0 ;l < n_layers ;++ l ) 7015for (int64_t e = 0 ;e < n_expert && !layer_pcie_ [(size_t )l ];++ e ) 7016layer_pcie_ [(size_t )l ]= pinned (l ,e ) ?1 :0 ; 7017 } 7018 }else if (a -> registered_bytes > 0 ) { 7019 std::vector < uint64_t > starts = a -> slice_bytes > 0 ?a -> slice_starts : std::vector < uint64_t > {0 }; 7020for (uint64_t off :starts ) { 7021void * d = nullptr ; 7022if (cudaHostGetDevicePointer (& d , (void * ) (base_ + off ),0 )!= cudaSuccess ) { 7023 (void )cudaGetLastError (); 7024dev_slice_ .clear (); 7025break ; 7026 } 7027dev_slice_ .push_back ((const uint8_t * )d ); 7028 } 7029 } 7030blobs_ = n_layers * n_expert ; 7031n_expert_ = n_expert ; 7032reads_ = 0 ; 7033note_ = a -> note ; 7034gib_per_s_ = st .gib_per_second (); 7035load_seconds_ = st .seconds ; 7036load_read_s_ = st .read_seconds ; 7037load_copy_s_ = st .copy_seconds ; 7038record_inputs (path ,gguf_ ,lay ,from_gguf ); 7039return true; 7040} 7041 7042void ArenaExpertSource ::close () { 7043#if !defined(_WIN32 ) 7044if (map_ != nullptr )munmap (map_ , (size_t )map_bytes_ ); 7045#endif 7046map_ = nullptr ; 7047map_bytes_ = 0 ; 7048inputs_ .clear (); 7049if (arena_ != nullptr ) { 7050delete (PinnedArena * )arena_ ; 7051arena_ = nullptr ; 7052 } 7053base_ = nullptr ; 7054blobs_ = 0 ; 7055n_expert_ = 0 ; 7056} 7057 7058void ArenaExpertSource ::prefetch (int64_t layer ,int64_t expert ) { 7059#if defined(_WIN32 ) 7060 (void )layer ; (void )expert ; 7061#else 7062if (map_ == nullptr || layer < 0 || expert < 0 || expert >=n_expert_ )return ; 7063const auto & lay = strata::kernels::cpu::expert_layout (); 7064const uint64_t off = lay .blob_offset (layer ,expert )& ~(uint64_t )4095 ; 7065const uint64_t end = lay .blob_offset (layer ,expert )+ lay .blob_bytes (layer ); 7066madvise ((uint8_t * )map_ + off , (size_t ) (end - off ),MADV_WILLNEED ); 7067#endif 7068} 7069 7070// Only the pages wholly inside the blob: a page shared with a neighbour the CPU may still read stays. MADV_DONTNEED 7071// unmaps them from this process; they stay in the page cache as clean, unmapped pages - the first the kernel takes 7072// back under pressure, and a minor fault away when the CPU needs the expert again (an adaptive swap evicts it). 7073// Dropping them from the cache too (POSIX_FADV_DONTNEED) made every eviction a re-read from the disk: ~200 major 7074// faults a second in decode, +8 ms a window. The memory the arena used to hold was never the cache itself but 7075// ROCclr's pin-in-place locks on it (see main) - locked pages are the ones the kernel cannot take back. 7076uint64_t ArenaExpertSource ::release (int64_t layer ,int64_t expert ) { 7077#if defined(_WIN32 ) 7078 (void )layer ; (void )expert ; 7079return 0 ; 7080#else 7081if (map_ == nullptr || layer < 0 || expert < 0 || expert >=n_expert_ )return 0 ; 7082const auto & lay = strata::kernels::cpu::expert_layout (); 7083const uint64_t off = (lay .blob_offset (layer ,expert )+ 4095 )& ~(uint64_t )4095 ; 7084const uint64_t end = (lay .blob_offset (layer ,expert )+ lay .blob_bytes (layer ))& ~(uint64_t )4095 ; 7085if (end <=off )return 0 ; 7086if (madvise ((uint8_t * )map_ + off , (size_t ) (end - off ),MADV_DONTNEED )!= 0 )return 0 ; 7087return end - off ; 7088#endif 7089} 7090 7091int64_t ArenaExpertSource ::pin_range_of (uint64_t off ,uint64_t len )const { 7092// last range starting at or before the blob; it must also end after it (a blob is inside ONE range: merged 7093// neighbours are contiguous, and a blob split by a trimmed page is reported unpinned - the safe answer) 7094const auto it = std::upper_bound (pin_start_ .begin (),pin_start_ .end (),off ); 7095if (it == pin_start_ .begin ())return -1 ; 7096const size_t i = (size_t ) (it - pin_start_ .begin ())- 1 ; 7097return off + len <=pin_end_ [i ] ? (int64_t )i :-1 ; 7098} 7099 7100uint64_t ArenaExpertSource ::arena_off (int64_t layer ,int64_t expert )const { 7101return padded_ ?pad_ .blob_off (layer ,expert ) : strata::kernels::cpu::expert_layout ().blob_offset (layer ,expert ); 7102} 7103 7104bool ArenaExpertSource ::pcie_layer (int64_t layer )const { 7105if (!ranges_ )return device_alias (layer ,0 )!= nullptr ;// the prefix rule (ExpertSource's default) 7106return layer >=0 && (size_t )layer < layer_pcie_ .size ()&& layer_pcie_ [(size_t )layer ]!= 0 ; 7107} 7108 7109bool ArenaExpertSource ::pinned (int64_t layer ,int64_t expert )const { 7110if (base_ == nullptr || layer < 0 || expert < 0 || expert >=n_expert_ )return false; 7111const auto & lay = strata::kernels::cpu::expert_layout (); 7112if (ranges_ )return pin_range_of (arena_off (layer ,expert ),lay .blob_bytes (layer )) >=0 ;// the whole blob inside ONE registered range 7113return lay .blob_offset (layer ,expert )+ lay .blob_bytes (layer ) <=pinned_bytes_ ; 7114} 7115 7116const uint8_t * ArenaExpertSource ::device_alias (int64_t layer ,int64_t expert )const { 7117if (ranges_ ) {// pin by need: the range's device base + the blob's offset inside it 7118if (base_ == nullptr || layer < 0 || expert < 0 || expert >=n_expert_ )return nullptr ; 7119const auto & rl = strata::kernels::cpu::expert_layout (); 7120const uint64_t off = arena_off (layer ,expert ); 7121const int64_t i = pin_range_of (off ,rl .blob_bytes (layer )); 7122return i < 0 ?nullptr :pin_dev_ [(size_t )i ]+ (off - pin_start_ [(size_t )i ]); 7123 } 7124if (dev_slice_ .empty ()|| !pinned (layer ,expert ))return nullptr ; 7125const auto & lay = strata::kernels::cpu::expert_layout (); 7126if (slice_bytes_ == 0 )return dev_slice_ [0 ]+ lay .blob_offset (layer ,expert ); 7127// one registration slice per layer 7128if ((size_t )layer >=dev_slice_ .size ())return nullptr ; 7129return dev_slice_ [(size_t )layer ]+ (uint64_t )expert * lay .blob_bytes (layer ); 7130} 7131 7132const uint8_t * ArenaExpertSource ::blob (int64_t layer ,int64_t expert ) { 7133if (base_ == nullptr )return nullptr ; 7134if (layer < 0 || expert < 0 || expert >=n_expert_ )return nullptr ; 7135const int64_t idx = layer * n_expert_ + expert ; 7136if (idx < 0 || idx >=blobs_ )return nullptr ; 7137reads_ .fetch_add (1 , std::memory_order_relaxed ); 7138// Pointer arithmetic into resident memory. No fault, no copy, no mapping - which is the entire point of 7139// this class over `FileExpertSource`. 7140return base_ + arena_off (layer ,expert ); 7141} 7142 7143const uint8_t * ArenaExpertSource ::blob_at (int64_t layer ,int64_t expert )const { 7144if (base_ == nullptr || layer < 0 || expert < 0 || expert >=n_expert_ )return nullptr ; 7145const int64_t idx = layer * n_expert_ + expert ; 7146if (idx < 0 || idx >=blobs_ )return nullptr ; 7147return base_ + arena_off (layer ,expert );// (the padded layout of pin by need too) 7148} 7149 7150}// namespace strata::core 7151 7152// ---- Foresight swap space (see include/strata/core/foresight_swap.hpp) ------------------------------------------ 7153namespace strata::core { 7154 7155bool ForesightSwap ::init (int slots_per_layer ,int64_t layers ,int64_t experts ,const std::vector < int >& card_of_layer , 7156const std::vector < int >& devices , std::string & err ) { 7157slots = slots_per_layer ; 7158n_layers = layers ; 7159n_expert = experts ; 7160const size_t ns = (size_t ) (layers * slots ); 7161slot .reset (new Slot [ns ]); 7162where .assign ((size_t ) (layers * experts ),-1 ); 7163miss_cnt .assign ((size_t ) (layers * experts ),0 ); 7164miss_at .assign ((size_t ) (layers * experts ),0 ); 7165layer_card = card_of_layer ; 7166layer_dev .resize ((size_t )layers ); 7167card_dev = devices ; 7168card_stream .assign (devices .size (),nullptr ); 7169card_mem .assign (devices .size (),nullptr ); 7170card_round .assign (devices .size (), ~0ull ); 7171card_used .assign (devices .size (),0 ); 7172const auto & lay = strata::kernels::cpu::expert_layout (); 7173for (size_t c = 0 ;c < devices .size ();++ c ) { 7174uint64_t bytes = 0 ; 7175for (int64_t l = 0 ;l < layers ;++ l ) 7176if (card_of_layer [(size_t )l ]== (int )c )bytes += (uint64_t )slots * (uint64_t )lay .blob_bytes (l ); 7177if (bytes == 0 )continue ; 7178const OnDevice on (devices [c ]); 7179cudaStream_t s = nullptr ; 7180if (cudaMalloc (& card_mem [c ],bytes )!= cudaSuccess || 7181cudaStreamCreateWithFlags (& s ,cudaStreamNonBlocking )!= cudaSuccess ) { 7182cudaGetLastError (); 7183err = "cannot allocate " + std::to_string (bytes >>20 )+ " MiB on CUDA" + std::to_string (devices [c ])+ 7184" (raise --vram-reserve-mib by about that much)" ; 7185return false; 7186 } 7187card_stream [c ]= s ; 7188uint64_t off = 0 ; 7189for (int64_t l = 0 ;l < layers ;++ l ) { 7190if (card_of_layer [(size_t )l ]!= (int )c )continue ; 7191layer_dev [(size_t )l ]= devices [c ]; 7192const uint64_t bb = (uint64_t )lay .blob_bytes (l ); 7193for (int s2 = 0 ;s2 < slots ;++ s2 ) { 7194Slot & sl = slot [(size_t ) (l * slots + s2 )]; 7195sl .dptr = (unsigned long long ) ((uint8_t * )card_mem [c ]+ off ); 7196sl .bytes = bb ; 7197cudaEvent_t ev = nullptr ; 7198if (cudaEventCreateWithFlags (& ev ,cudaEventDisableTiming )!= cudaSuccess ) { 7199cudaGetLastError (); 7200err = "cannot create the copy events" ; 7201return false; 7202 } 7203sl .ev = ev ; 7204off += bb ; 7205 } 7206 } 7207 } 7208filler_ = std::thread ([this ] {fill_loop (); }); 7209return true; 7210} 7211 7212ForesightSwap ::~ForesightSwap () { 7213 { 7214 std::lock_guard < std::mutex > lk (mu_ ); 7215stop_ = true; 7216 } 7217cv_ .notify_all (); 7218if (filler_ .joinable ())filler_ .join (); 7219for (size_t c = 0 ;c < card_dev .size ();++ c ) { 7220const OnDevice on (card_dev [c ]); 7221if (card_stream [c ])cudaStreamSynchronize ((cudaStream_t )card_stream [c ]); 7222if (card_mem [c ])cudaFree (card_mem [c ]); 7223if (card_stream [c ])cudaStreamDestroy ((cudaStream_t )card_stream [c ]); 7224 } 7225if (slot ) 7226for (int64_t i = 0 ;i < n_layers * slots ;++ i ) 7227if (slot [(size_t )i ].ev )cudaEventDestroy ((cudaEvent_t )slot [(size_t )i ].ev ); 7228} 7229 7230void ForesightSwap ::fill_loop () { 7231 strata::platform::name_this_thread ("strata-fill" ); 7232int cur_dev = -1 ; 7233for (;;) { 7234int64_t idx ; 7235 { 7236 std::unique_lock < std::mutex > lk (mu_ ); 7237cv_ .wait (lk , [& ] {return stop_ || !queue_ .empty (); }); 7238if (stop_ )return ; 7239idx = queue_ .front (); 7240queue_ .pop_front (); 7241 } 7242Slot & sl = slot [(size_t )idx ]; 7243const int64_t l = idx /slots ; 7244const int dev = layer_dev [(size_t )l ]; 7245if (dev != cur_dev ) {cudaSetDevice (dev );cur_dev = dev ; } 7246cudaStream_t s = (cudaStream_t )card_stream [(size_t )layer_card [(size_t )l ]]; 7247if (cudaMemcpyAsync ((void * )sl .dptr ,sl .src ,sl .bytes ,cudaMemcpyHostToDevice ,s )!= cudaSuccess || 7248cudaEventRecord ((cudaEvent_t )sl .ev ,s )!= cudaSuccess ) { 7249cudaGetLastError (); 7250if (!failed .exchange (true)) std::fprintf (stderr ,"strata serve: foresight swap: a copy failed - swap space off\n" ); 7251continue ;// never marked issued: the slot is never used 7252 } 7253sl .issued .store (true, std::memory_order_release ); 7254 } 7255} 7256 7257bool ForesightSwap ::take (int64_t layer ,int32_t expert ,unsigned long long & ptr ) { 7258 std::lock_guard < std::mutex > smu_lk (smu_ ); 7259const int s = where [(size_t ) (layer * n_expert + expert )]; 7260if (s < 0 )return false; 7261Slot & sl = slot [(size_t ) (layer * slots + s )]; 7262if (!sl .ready ) { 7263if (!sl .loading || !sl .issued .load (std::memory_order_acquire )) {++ pending ;return false; } 7264const cudaError_t q = cudaEventQuery ((cudaEvent_t )sl .ev ); 7265if (q != cudaSuccess ) { 7266if (q != cudaErrorNotReady )cudaGetLastError (); 7267++ pending ; 7268return false; 7269 } 7270sl .ready = true; 7271sl .loading = false; 7272if (verify ) {// test mode: the bytes the GPU will read must be the expert's own 7273 std::vector < uint8_t > back ((size_t )sl .bytes ); 7274const OnDevice on (layer_dev [(size_t )layer ]); 7275const bool same = cudaMemcpy (back .data (), (const void * )sl .dptr , (size_t )sl .bytes ,cudaMemcpyDeviceToHost )== 7276cudaSuccess && std::memcmp (back .data (),sl .src , (size_t )sl .bytes )== 0 ; 7277if (same )++ verify_ok ; 7278else { 7279cudaGetLastError (); 7280++ verify_bad ; 7281sl .ready = false;// never serve it 7282where [(size_t ) (layer * n_expert + expert )]= -1 ; 7283sl .expert = -1 ; 7284return false; 7285 } 7286 } 7287 } 7288sl .last_ref = completed .load (std::memory_order_acquire ); 7289ptr = sl .dptr ; 7290++ hits ; 7291return true; 7292} 7293 7294void ForesightSwap ::hold (int64_t layer ,int32_t expert ) { 7295if (layer < 0 || layer >=n_layers || expert < 0 || expert >=n_expert )return ; 7296 std::lock_guard < std::mutex > smu_lk (smu_ ); 7297const size_t key = (size_t ) (layer * n_expert + expert ); 7298const int s = where [key ]; 7299where [key ]= kHeld ; 7300if (s < 0 )return ; 7301Slot & sl = slot [(size_t ) (layer * slots + s )]; 7302sl .expert = kDropped ;// `loading` and `last_ref` stay: a copy in flight and a window that read it are waited for 7303sl .ready = false; 7304++ dropped ; 7305} 7306 7307void ForesightSwap ::unhold (int64_t layer ,int32_t expert ) { 7308if (layer < 0 || layer >=n_layers || expert < 0 || expert >=n_expert )return ; 7309 std::lock_guard < std::mutex > smu_lk (smu_ ); 7310int16_t & w = where [(size_t ) (layer * n_expert + expert )]; 7311if (w == kHeld )w = -1 ; 7312} 7313 7314void ForesightSwap ::note_miss (ExpertSource * src ,int64_t layer ,int32_t expert ) { 7315 std::lock_guard < std::mutex > smu_lk (smu_ ); 7316request_locked (src ,layer ,expert , false); 7317} 7318 7319void ForesightSwap ::predict (ExpertSource * src ,int64_t layer ,int32_t expert ) { 7320if (layer < 0 || layer >=n_layers || expert < 0 || expert >=n_expert )return ; 7321 std::lock_guard < std::mutex > smu_lk (smu_ ); 7322request_locked (src ,layer ,expert , true); 7323} 7324 7325void ForesightSwap ::request_locked (ExpertSource * src ,int64_t layer ,int32_t expert ,bool predicted_copy ) { 7326if (failed .load (std::memory_order_relaxed ))return ; 7327const size_t key = (size_t ) (layer * n_expert + expert ); 7328if (where [key ]!= -1 )return ;// already on its way, or held by an exchange (#2134) 7329const uint64_t now = completed .load (std::memory_order_acquire ); 7330if (admit > 1 && !predicted_copy ) { 7331if (now > miss_at [key ]+ 4 )miss_cnt [key ]= 0 ; 7332miss_at [key ]= now ; 7333if (miss_cnt [key ]< 255 )++ miss_cnt [key ]; 7334if (miss_cnt [key ]< admit )return ; 7335 } 7336const int c = layer_card [(size_t )layer ]; 7337if (card_round [(size_t )c ]!= now ) {card_round [(size_t )c ]= now ;card_used [(size_t )c ]= 0 ; } 7338if (card_used [(size_t )c ] >=budget ) {++ over_budget ;return ; } 7339if (src == nullptr || !src -> pinned (layer ,expert ))return ;// async copies need the pinned arena 7340const uint8_t * b = src -> blob (layer ,expert ); 7341if (b == nullptr )return ; 7342int best = -1 ; 7343uint64_t best_ref = ~0ull ; 7344for (int s = 0 ;s < slots ;++ s ) {// an empty slot, else the one used longest ago that no window can still read 7345Slot & sl = slot [(size_t ) (layer * slots + s )]; 7346if (sl .loading ) {// copied in but never asked for since: landed long ago -> an ordinary candidate 7347if (sl .last_ref + (uint64_t )depth > now || !sl .issued .load (std::memory_order_acquire ))continue ; 7348const cudaError_t q = cudaEventQuery ((cudaEvent_t )sl .ev ); 7349if (q != cudaSuccess ) {if (q != cudaErrorNotReady )cudaGetLastError ();continue ; } 7350sl .loading = false; 7351sl .ready = true; 7352 } 7353if (sl .expert == -1 ) {best = s ;break ; }// never used (a dropped slot, kDropped, waits like a used one) 7354if (sl .last_ref + (uint64_t )depth > now )continue ; 7355if (sl .last_ref < best_ref ) {best_ref = sl .last_ref ;best = s ; } 7356 } 7357if (best < 0 ) {++ busy ;return ; } 7358Slot & sl = slot [(size_t ) (layer * slots + best )]; 7359if (sl .expert >=0 )where [(size_t ) (layer * n_expert + sl .expert )]= -1 ; 7360sl .expert = expert ; 7361sl .ready = false; 7362sl .loading = true; 7363sl .issued .store (false, std::memory_order_relaxed ); 7364sl .src = b ; 7365sl .last_ref = now ; 7366where [key ]= (int16_t )best ; 7367++ card_used [(size_t )c ]; 7368++ copies ; 7369if (predicted_copy )++ predicted ; 7370 { 7371 std::lock_guard < std::mutex > lk (mu_ ); 7372queue_ .push_back (layer * slots + best ); 7373 } 7374cv_ .notify_one (); 7375} 7376 7377std::string ForesightSwap ::report ()const { 7378 std::lock_guard < std::mutex > smu_lk (const_cast < std::mutex &> (smu_ )); 7379char buf [320 ]; 7380 std::snprintf (buf ,sizeof buf ,"foresight swap: %llu experts served from the swap space, %llu copies (%llu from the " 7381"router look-ahead), %llu not landed yet, %llu no free slot, %llu over budget%s" , 7382 (unsigned long long )hits , (unsigned long long )copies , (unsigned long long )predicted , 7383 (unsigned long long )pending , (unsigned long long )busy , (unsigned long long )over_budget ,verify ?"" :"" ); 7384 std::string r = buf ; 7385if (dropped > 0 )r += ", " + std::to_string (dropped )+ " dropped by exchanges" ; 7386if (verify )r += ", verified " + std::to_string (verify_ok )+ " ok / " + std::to_string (verify_bad )+ " BAD" ; 7387return r ; 7388} 7389 7390ForesightSwap * foresight_swap_from_env (int64_t layers ,int64_t experts ,const std::vector < int >& card_of_layer , 7391const std::vector < int >& devices ) { 7392const char * v = std::getenv ("STRATA_FS_SLOTS" ); 7393const int slots = v ? std::atoi (v ) :0 ; 7394if (slots <=0 )return nullptr ; 7395if (const char * dp = std::getenv ("STRATA_VERIFY_DEVICE_PLAN" );dp && std::atoi (dp )!= 0 ) { 7396 std::fprintf (stderr ,"strata serve: foresight swap: off beside STRATA_VERIFY_DEVICE_PLAN (the device would plan " 7397"resident layers without the host)\n" ); 7398return nullptr ; 7399 } 7400auto * f = new ForesightSwap (); 7401auto env_int = [](const char * name ,int def ,int lo ) {const char * e = std::getenv (name );const int x = e ? std::atoi (e ) :def ;return x < lo ?lo :x ; }; 7402f -> budget = env_int ("STRATA_FS_BUDGET" ,32 ,1 ); 7403f -> admit = env_int ("STRATA_FS_ADMIT" ,1 ,1 ); 7404f -> depth = env_int ("STRATA_FS_DEPTH" ,4 ,2 ); 7405f -> verify = env_int ("STRATA_FS_VERIFY" ,0 ,0 )!= 0 ; 7406 std::string err ; 7407if (!f -> init (std::min (slots ,64 ),layers ,experts ,card_of_layer ,devices ,err )) { 7408 std::fprintf (stderr ,"strata serve: foresight swap: %s - swap space off\n" ,err .c_str ()); 7409delete f ; 7410return nullptr ; 7411 } 7412 std::fprintf (stderr ,"strata serve: foresight swap: %d slots per layer on %zu card(s), up to %d copies per card and " 7413"window, admit after %d miss(es), reuse after %d windows\n" , 7414f -> slots ,devices .size (),f -> budget ,f -> admit ,f -> depth ); 7415return f ; 7416} 7417 7418}// namespace strata::core