okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7f46672a4
main
1// metal/src/engine/stream.cpp - see stream.h. 2#include "geo.h" 3#include "stream.h" 4 5#include "ref_quant.h" 6#include "arena_budget.h" 7 8#include <sys/sysctl.h> 9 10#include <fcntl.h> 11#include <sys/mman.h> 12#include <sys/stat.h> 13#include <unistd.h> 14 15#include <algorithm> 16#include <chrono> 17#include <cstdio> 18#include <cstdlib> 19#include <cstring> 20#include <map> 21 22namespace strata::metal_engine { 23 24namespace { 25constexpr int NL = strata_metal::geo::NL ,NE = 512 ;// layers of the compiled shape (engine/geo.h); NE: the row stride of the per-layer maps (the largest expert count) 26constexpr uint64_t PAGE = 16384 ; 27double now_ms () {return std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ().time_since_epoch ()).count (); } 28int env_int (const char * n ,int d ) { 29const char * e = std::getenv (n ); 30return e && * e ? std::atoi (e ) :d ; 31} 32}// namespace 33 34bool ExpertStream ::wanted (const gguf::File & f ,const mtl::Context & cx ) { 35const char * e = std::getenv ("STRATA_METAL_STREAM" ); 36if (e && std::string (e )== "1" )return true; 37if (e && std::string (e )== "0" )return false; 38// auto: stream when the mapped weights (experts and dense) and ~12 GiB beside them (the prompt buffers, KV, the 39// draft layer, macOS) do not fit the resident footprint cap: the GPU working set, or on a big Mac the RAM less the 40// 30% macOS and its file cache keep (arena_budget.h: footprint_cap). M5 Max (115.4 GB working set, 96.2 GB cap): 41// GSQ packs, IQ3_S and UD-Q4_K_XL stay resident, UD-Q5/Q6_K_XL stream; M4 32 GB (26.8 GB): every pack streams. 42uint64_t all = 0 ; 43for (const auto & kv :f .tensors ) 44if (kv .first != "per_layer_token_embd.weight" )all += kv .second .bytes ; 45uint64_t phys = 0 ; 46size_t len = sizeof phys ; 47sysctlbyname ("hw.memsize" ,& phys ,& len ,nullptr ,0 ); 48return !resident_fits ((double )phys , (double )cx .recommended_working_set (), (double )all ,12.0 * (1ull <<30 )); 49} 50 51ExpertStream ::~ExpertStream () { 52 { 53 std::lock_guard < std::mutex > g (mu_ ); 54stop_ = true; 55 } 56cv_ .notify_all (); 57for (auto & t :io_ )t .join (); 58if (fd_ >=0 ) ::close (fd_ ); 59} 60 61bool ExpertStream ::open (const gguf::File & f , std::string & err ) { 62fd_ = ::open (f .path .c_str (),O_RDONLY ); 63if (fd_ < 0 ) {err = "metal stream: cannot open " + f .path ;return false; } 64fcntl (fd_ ,F_NOCACHE ,1 ); 65fcntl (fd_ ,F_RDAHEAD ,0 ); 66lay_ .resize (NL ); 67if (const gguf::Tensor * g0 = f .find ("blk.0.ffn_gate_exps.weight" );g0 && g0 -> shape .size () >=3 && g0 -> shape [2 ]> 0 && g0 -> shape [2 ] <=NE ) 68ne_ = (int )g0 -> shape [2 ]; 69for (int l = 0 ;l < NL ;++ l ) { 70const std::string b = "blk." + std::to_string (l )+ "." ; 71const gguf::Tensor * g = f .find (b + "ffn_gate_exps.weight" ); 72const gguf::Tensor * u = f .find (b + "ffn_up_exps.weight" ); 73const gguf::Tensor * d = f .find (b + "ffn_down_exps.weight" ); 74if (!g || !u || !d ) {err = "metal stream: layer " + std::to_string (l )+ " has no routed experts" ;return false; } 75lay_ [(size_t )l ]= {g -> offset ,g -> bytes /ne_ ,u -> offset ,u -> bytes /ne_ ,d -> offset ,d -> bytes /ne_ ,-1 }; 76 } 77// the expert-contiguous copy beside the GGUF, when it is this GGUF's (sizes in its header) and its first and 78// last experts match the GGUF's bytes 79if (env_int ("STRATA_METAL_CONTIG" ,1 )!= 0 ) { 80const std::string cp = f .path + ".experts" ; 81const int cfd = ::open (cp .c_str (),O_RDONLY ); 82bool ok = cfd >=0 ; 83 std::vector < uint64_t > off (NL ); 84if (ok ) { 85uint8_t h [64 ]; 86 std::vector < uint64_t > t ((size_t )NL * 4 ); 87struct stat st {}; 88 ::fstat (fd_ ,& st ); 89ok = ::pread (cfd ,h ,64 ,0 )== 64 && std::memcmp (h ,"STRX" ,4 )== 0 && 90 ::pread (cfd ,t .data (),t .size ()* 8 ,64 )== (ssize_t ) (t .size ()* 8 ); 91uint32_t ver = 0 ,nl = 0 ,ne = 0 ; 92uint64_t src = 0 ; 93 std::memcpy (& ver ,h + 4 ,4 ); std::memcpy (& nl ,h + 8 ,4 ); std::memcpy (& ne ,h + 12 ,4 ); std::memcpy (& src ,h + 16 ,8 ); 94ok = ok && ver == 1 && nl == (uint32_t )NL && ne == (uint32_t )ne_ && src == (uint64_t )st .st_size ; 95for (int l = 0 ;ok && l < NL ;++ l ) { 96const Lay & x = lay_ [(size_t )l ]; 97ok = t [(size_t )l * 4 + 1 ]== x .gs && t [(size_t )l * 4 + 2 ]== x .us && t [(size_t )l * 4 + 3 ]== x .ds ; 98off [(size_t )l ]= t [(size_t )l * 4 ]; 99 } 100if (ok ) {// spot check: layer 0's first and layer 47's last expert, every slice 101for (const int l : {0 ,NL - 1 }) { 102const Lay & x = lay_ [(size_t )l ]; 103const int e = l == 0 ?0 :ne_ - 1 ; 104 std::vector < uint8_t > a (x .gs + x .us + x .ds ),b (a .size ()); 105ok = ok && ::pread (cfd ,a .data (),a .size (), (off_t ) (off [(size_t )l ]+ (uint64_t )e * a .size ()))== (ssize_t )a .size ()&& 106 ::pread (fd_ ,b .data (),x .gs , (off_t ) (x .g + (uint64_t )e * x .gs ))== (ssize_t )x .gs && 107 ::pread (fd_ ,b .data ()+ x .gs ,x .us , (off_t ) (x .u + (uint64_t )e * x .us ))== (ssize_t )x .us && 108 ::pread (fd_ ,b .data ()+ x .gs + x .us ,x .ds , (off_t ) (x .d + (uint64_t )e * x .ds ))== (ssize_t )x .ds && 109a == b ; 110 } 111 } 112 } 113if (ok ) { 114fcntl (cfd ,F_NOCACHE ,1 ); 115fcntl (cfd ,F_RDAHEAD ,0 ); 116cfd_ = cfd ; 117coff_ = off ; 118 std::fprintf (stderr ,"strata metal stream: experts read from %s (one request per expert)\n" ,cp .c_str ()); 119 }else if (cfd >=0 ) { 120 ::close (cfd ); 121 std::fprintf (stderr ,"strata metal stream: %s is not this GGUF's (sizes or bytes differ): the GGUF is read\n" , 122cp .c_str ()); 123 } 124 } 125// size classes: one LRU pool per class. The layers' slot sizes (9 in the IQ3_XXS mix) are merged into a few 126// classes, each as big as its largest member, so that no member wastes more than STRATA_METAL_CLASS_WASTE (default 127// 0.15) of its slot: every class must hold a whole layer's experts for a prompt chunk, so fewer classes = less 128// memory tied up in those minimums. 129 { 130const char * ew = std::getenv ("STRATA_METAL_CLASS_WASTE" ); 131const double waste = ew ? std::atof (ew ) :0.15 ; 132 std::vector < uint64_t > pages_of (NL ); 133 std::vector < uint64_t > sizes ; 134for (int l = 0 ;l < NL ;++ l ) { 135const Lay & x = lay_ [(size_t )l ]; 136pages_of [(size_t )l ]= (x .gs + x .us + x .ds + PAGE - 1 ) /PAGE ; 137sizes .push_back (pages_of [(size_t )l ]); 138 } 139 std::sort (sizes .begin (),sizes .end ()); 140sizes .erase (std::unique (sizes .begin (),sizes .end ()),sizes .end ()); 141 std::vector < uint64_t > tops ;// each class's slot pages, largest first 142for (auto it = sizes .rbegin ();it != sizes .rend ();++ it ) 143if (tops .empty ()|| (double )* it < (1.0 - waste )* (double )tops .back ())tops .push_back (* it ); 144for (uint64_t t :tops ) {Cls c ;c .pages = t ;cls_ .push_back (c ); } 145for (int l = 0 ;l < NL ;++ l ) { 146int best = 0 ;// the smallest class that holds the layer's slot 147for (int c = 0 ;c < (int )cls_ .size ();++ c ) 148if (cls_ [(size_t )c ].pages >=pages_of [(size_t )l ])best = c ; 149lay_ [(size_t )l ].cls = best ; 150 } 151 } 152nio_ = std::max (1 ,env_int ("STRATA_METAL_IO_THREADS" ,6 )); 153split_ = std::max (1 , std::min (8 ,env_int ("STRATA_METAL_READ_SPLIT" ,1 ))); 154// The read-ahead's depth and where its experts wait in the LRU, measured on the M4 (notes-mac-ssd.md, 3 interleaved 155// pairs each): Q2_0 (1.38 MB experts) top 10 at the LRU front 12.2 tok/s vs top 6 at the tail 11.3; the IQ3_XXS 156// mix (1.75 MB, the SSD is the limit) top 6 at the tail 8.06 vs top 10 at the front 7.43. 157uint64_t eb = 0 ; 158for (const auto & x :lay_ )eb += x .gs + x .us + x .ds ; 159const bool big = (double )eb /NL > 1.5e6 ; 160pre_k_ = env_int ("STRATA_METAL_PREFETCH" ,big ?6 :10 ); 161pre_k2_ = env_int ("STRATA_METAL_PREFETCH2" ,0 ); 162prefetch_ = pre_k_ > 0 ; 163pre_mru_ = env_int ("STRATA_METAL_PREFETCH_MRU" ,big ?0 :1 )!= 0 ; 164// timing only (WRONG answers): every missing expert is pointed at slot 0, nothing is read 165fake_ = env_int ("STRATA_METAL_STREAM_FAKE" ,0 )!= 0 ; 166return true; 167} 168 169bool ExpertStream ::read (void * dst ,uint64_t len ,uint64_t off )const { 170uint8_t * p = (uint8_t * )dst ; 171while (len > 0 ) { 172const ssize_t r = ::pread (fd_ ,p , (size_t ) std::min < uint64_t > (len ,64ull <<20 ), (off_t )off ); 173if (r <=0 )return false; 174p += r ; 175off += (uint64_t )r ; 176len -= (uint64_t )r ; 177 } 178return true; 179} 180 181bool ExpertStream ::load_dense (gguf::File & f , mtl::Context & cx ,const std::vector < std::string >& skip , mtl::Buffer & out , 182 std::string & err ) { 183const double t0 = now_ms (); 184 std::vector < gguf::Tensor *> ts ; 185uint64_t tot = 0 ; 186for (auto & kv :f .tensors ) { 187 gguf::Tensor & t = kv .second ; 188if (t .name .find ("_exps" )!= std::string::npos )continue ; 189// the n-gram table is read by the host from the SSD, a few rows at a time (src/ngram/ple_reader.cpp). It is its own shard in 190// the ISTA / Unsloth files; in agentionai's Gyro files it is the first 28.8 GB of the one file, and must not be read in here 191if (t .name == "per_layer_token_embd.weight" )continue ; 192if (std::find (skip .begin (),skip .end (),t .name )!= skip .end ()) {t .offset = 0 ;continue ; } 193ts .push_back (& t ); 194tot += (t .bytes + 255 ) /256 * 256 ; 195 } 196out = cx .alloc ((tot + PAGE - 1 ) /PAGE * PAGE ); 197 std::vector < uint64_t > src (ts .size ()),dst (ts .size ()); 198uint64_t o = 0 ; 199for (size_t i = 0 ;i < ts .size ();++ i ) { 200src [i ]= ts [i ]-> offset ; 201dst [i ]= o ; 202o += (ts [i ]-> bytes + 255 ) /256 * 256 ; 203 } 204 std::atomic < size_t > next {0 }; 205 std::atomic < bool > ok {true}; 206 std::vector < std::thread > th ; 207for (int k = 0 ;k < 4 ;++ k ) 208th .emplace_back ([& ] { 209for (;;) { 210const size_t i = next ++ ; 211if (i >=ts .size ())break ; 212if (!read (out .as < uint8_t > ()+ dst [i ],ts [i ]-> bytes ,src [i ]))ok = false; 213 } 214 }); 215for (auto & x :th )x .join (); 216if (!ok ) {err = "metal stream: reading the dense tensors failed" ;return false; } 217for (size_t i = 0 ;i < ts .size ();++ i )ts [i ]-> offset = dst [i ]; 218 std::fprintf (stderr ,"strata metal stream: %zu dense tensors read into memory (%.2f GB, %.1f s; %zu left out)\n" ,ts .size (), 219tot /1e9 , (now_ms ()- t0 ) /1e3 ,skip .size ()); 220return true; 221} 222 223int ExpertStream ::cls_of (int s )const {// the class ranges are contiguous 224int ci = 0 ; 225while (!(s >=cls_ [(size_t )ci ].base && s < cls_ [(size_t )ci ].base + cls_ [(size_t )ci ].n ))++ ci ; 226return ci ; 227} 228 229void ExpertStream ::lru_unlink (int s ) { 230Slot & x = slots_ [(size_t )s ]; 231Cls & k = cls_ [(size_t )cls_of (s )]; 232if (x .prev >=0 )slots_ [(size_t )x .prev ].next = x .next ;else k .head = x .next ; 233if (x .next >=0 )slots_ [(size_t )x .next ].prev = x .prev ;else k .tail = x .prev ; 234x .prev = x .next = -1 ; 235} 236 237void ExpertStream ::lru_back (int s ) { 238lru_unlink (s ); 239Cls & k = cls_ [(size_t )cls_of (s )]; 240Slot & x = slots_ [(size_t )s ]; 241x .prev = k .tail ; 242x .next = -1 ; 243if (k .tail >=0 )slots_ [(size_t )k .tail ].next = s ; 244k .tail = s ; 245if (k .head < 0 )k .head = s ; 246} 247 248void ExpertStream ::lru_front (int s ) { 249lru_unlink (s ); 250Cls & k = cls_ [(size_t )cls_of (s )]; 251Slot & x = slots_ [(size_t )s ]; 252x .next = k .head ; 253x .prev = -1 ; 254if (k .head >=0 )slots_ [(size_t )k .head ].prev = s ; 255k .head = s ; 256if (k .tail < 0 )k .tail = s ; 257} 258 259int ExpertStream ::victim (int ci ) { 260Cls & k = cls_ [(size_t )ci ]; 261for (int s = k .tail ;s >=0 ;s = slots_ [(size_t )s ].prev ) 262if (slots_ [(size_t )s ].state .load ()== 0 && slots_ [(size_t )s ].pin != stamp_ ) { 263Slot & x = slots_ [(size_t )s ]; 264if (x .layer >=0 ) { 265const int key = x .layer * NE + x .e ; 266where_ [(size_t )key ]= -1 ; 267smap_ .as < uint32_t > ()[key ]= 0xFFFFFFFFu ; 268 } 269x .layer = x .e = -1 ; 270return s ; 271 } 272return -1 ; 273} 274 275// One piece of an expert: slice part / split_ (gate, up, down), piece part % split_ of it. The pieces of one expert 276// go to several I/O threads, so a single miss is read with several requests in flight (its latency, not only the 277// SSD's throughput, is what a layer waits for). 278void ExpertStream ::read_part (int s ,int l ,int e ,int part ) { 279const Lay & x = lay_ [(size_t )l ]; 280if (cfd_ >=0 ) {// the contiguous copy: the whole expert, piece part of split_ (the slot keeps gate | up | down) 281const uint64_t len = x .gs + x .us + x .ds ,src = coff_ [(size_t )l ]+ (uint64_t )e * len ; 282const uint64_t a = len * (uint64_t )part / (uint64_t )split_ /4096 * 4096 ; 283const uint64_t b = part + 1 == split_ ?len :len * (uint64_t ) (part + 1 ) / (uint64_t )split_ /4096 * 4096 ; 284uint8_t * p = host_ [(size_t )s ]+ a ; 285uint64_t n = b - a ,o = src + a ; 286while (n > 0 ) { 287const ssize_t r = ::pread (cfd_ ,p , (size_t )n , (off_t )o ); 288if (r <=0 ) { 289 std::fprintf (stderr ,"strata metal stream: reading expert %d of layer %d failed\n" ,e ,l ); 290 std::exit (6 ); 291 } 292p += r ;o += (uint64_t )r ;n -= (uint64_t )r ; 293 } 294bytes_read_ += b - a ; 295return ; 296 } 297const int k = part /split_ ,p = part %split_ ; 298const uint64_t len = k == 0 ?x .gs : (k == 1 ?x .us :x .ds ); 299const uint64_t src = (k == 0 ?x .g : (k == 1 ?x .u :x .d ))+ (uint64_t )e * len ; 300const uint64_t dst = k == 0 ?0 : (k == 1 ?x .gs :x .gs + x .us ); 301const uint64_t a = len * (uint64_t )p / (uint64_t )split_ /4096 * 4096 ; 302const uint64_t b = p + 1 == split_ ?len :len * (uint64_t ) (p + 1 ) / (uint64_t )split_ /4096 * 4096 ; 303if (b > a && !read (host_ [(size_t )s ]+ dst + a ,b - a ,src + a )) { 304 std::fprintf (stderr ,"strata metal stream: reading expert %d of layer %d failed\n" ,e ,l ); 305 std::exit (6 ); 306 } 307bytes_read_ += b - a ; 308} 309 310void ExpertStream ::io_main () { 311for (;;) { 312Job j ; 313 { 314 std::unique_lock < std::mutex > g (mu_ ); 315cv_ .wait (g , [& ] {return stop_ || !urgent_q_ .empty ()|| !pre_q_ .empty (); }); 316if (stop_ )return ; 317if (!urgent_q_ .empty ()) {j = urgent_q_ .front ();urgent_q_ .pop_front (); } 318else {j = pre_q_ .front ();pre_q_ .pop_front (); } 319slots_ [(size_t )j .slot ].state = 2 ; 320 } 321read_part (j .slot ,j .layer ,j .e ,j .part ); 322bool done = false; 323 { 324 std::lock_guard < std::mutex > g (mu_ ); 325Slot & x = slots_ [(size_t )j .slot ]; 326if (-- x .left == 0 ) { 327smap_ .as < uint32_t > ()[j .layer * NE + j .e ]= code_ [(size_t )j .slot ]; 328x .state = 0 ; 329-- outstanding_ ; 330++ reads_ ; 331done = true; 332 } 333 } 334if (done )done_cv_ .notify_all (); 335 } 336} 337 338void ExpertStream ::submit (int s ,int l ,int e ,bool urgent ) { 339Slot & x = slots_ [(size_t )s ]; 340x .layer = (int16_t )l ; 341x .e = (int16_t )e ; 342x .state = 1 ; 343x .pre = !urgent ; 344const int parts = cfd_ >=0 ?split_ :3 * split_ ; 345x .left = parts ; 346++ outstanding_ ; 347where_ [(size_t ) (l * NE + e )]= s ; 348for (int p = 0 ;p < parts ;++ p ) (urgent ?urgent_q_ :pre_q_ ).push_back ({s ,l ,e ,p }); 349} 350 351// a queued read-ahead nobody wants: its pieces dropped, the slot freed (only before any piece has started) 352void ExpertStream ::cancel_slot (int s ) { 353Slot & x = slots_ [(size_t )s ]; 354for (auto it = pre_q_ .begin ();it != pre_q_ .end ();)it = it -> slot == s ?pre_q_ .erase (it ) :it + 1 ; 355where_ [(size_t ) (x .layer * NE + x .e )]= -1 ; 356x .layer = x .e = -1 ; 357x .state = 0 ; 358x .pre = false; 359x .left = 0 ; 360-- outstanding_ ; 361++ pre_cancel_ ; 362lru_back (s ); 363} 364 365// a read-ahead that is wanted now: its queued pieces go first 366void ExpertStream ::promote_slot (int s ) { 367 std::vector < Job > mine ; 368for (auto it = pre_q_ .begin ();it != pre_q_ .end ();) 369if (it -> slot == s ) {mine .push_back (* it );it = pre_q_ .erase (it ); } 370else ++ it ; 371for (auto it = mine .rbegin ();it != mine .rend ();++ it )urgent_q_ .push_front (* it ); 372} 373 374bool ExpertStream ::make_arena (mtl::Context & cx ,uint64_t budget ,const std::string & profile ,int min_slots , std::string & err , 375const std::function < uint64_t ()>& recheck ,const std::function < bool (uint64_t )>& grow ) { 376const double t0 = now_ms (); 377shrink_to_ = 0 ; 378for (auto & k :cls_ )k .n = 0 ;// a second try (after a shrink) lays the arena out again 379// the ranking: the profile's pairs, then every pair it misses, layer-interleaved 380 std::vector < std::pair < int ,int >> rank ; 381 std::vector < uint8_t > seen ((size_t )NL * NE ,0 ); 382if (FILE * f = std::fopen (profile .c_str (),"rb" )) { 383char magic [4 ]; 384uint32_t h [5 ]; 385if (std::fread (magic ,1 ,4 ,f )== 4 && std::memcmp (magic ,"STRP" ,4 )== 0 && std::fread (h ,4 ,5 ,f )== 5 && 386h [1 ]== (uint32_t )NL && h [2 ]== (uint32_t )ne_ ) { 387for (uint32_t i = 0 ;i < h [4 ];++ i ) { 388uint16_t p [2 ]; 389if (std::fread (p ,2 ,2 ,f )!= 2 )break ; 390if (p [0 ]< NL && p [1 ]< ne_ && !seen [(size_t )p [0 ]* NE + p [1 ]]) { 391seen [(size_t )p [0 ]* NE + p [1 ]]= 1 ; 392rank .push_back ({p [0 ],p [1 ]}); 393 } 394 } 395 } 396 std::fclose (f ); 397 }else { 398 std::fprintf (stderr ,"strata metal stream: no expert profile at %s: the arena starts layer-interleaved\n" ,profile .c_str ()); 399 } 400const size_t from_profile = rank .size (); 401for (int e = 0 ;e < ne_ ;++ e ) 402for (int l = 0 ;l < NL ;++ l ) 403if (!seen [(size_t )l * NE + e ])rank .push_back ({l ,e }); 404// the pool of each size class: at least min_slots (a prompt chunk's layer needs up to 512 at once), then the 405// top-ranked pairs that fit in the budget 406uint64_t used = 0 ; 407for (const auto & k :cls_ )used += (uint64_t )min_slots * k .pages * PAGE ; 408 std::vector < std::pair < int ,int >> fill ; 409for (const auto & p :rank ) { 410Cls & k = cls_ [(size_t )lay_ [(size_t )p .first ].cls ]; 411const uint64_t cost = k .n < min_slots ?0 :k .pages * PAGE ; 412if (used + cost > budget )break ; 413used += cost ; 414++ k .n ; 415fill .push_back (p ); 416 } 417int base = 0 ; 418for (auto & k :cls_ ) { 419k .n = std::max (k .n ,min_slots ); 420k .base = base ; 421base += k .n ; 422 } 423// the slots placed in chunks of at most maxBufferLength (and 8 GB), up to 4 (the kernels' buffers 0, 7, 8, 9) 424// (8 GB each unless the arena needs bigger ones to fit 4: the M4 refused one 20.6 GB buffer, the M5 Max takes an 425// 89 GB arena for UD-Q5_K_XL in 4 of ~23 GB; STRATA_METAL_ARENA_CHUNK_GB sets it) 426uint64_t total = 0 ,biggest = 0 ; 427for (const auto & k :cls_ ) { 428total += (uint64_t )k .n * k .pages * PAGE ; 429biggest = std::max < uint64_t > (biggest ,k .pages * PAGE ); 430 } 431uint64_t want = std::max < uint64_t > (8ull <<30 ,total /4 + 4 * biggest ); 432if (const char * e = std::getenv ("STRATA_METAL_ARENA_CHUNK_GB" ))want = (uint64_t ) (std::atof (e )* (1ull <<30 )); 433const uint64_t cmax = std::min < uint64_t > (cx .max_buffer_length (),want ) /PAGE * PAGE ; 434code_ .assign ((size_t )base ,0 ); 435host_ .assign ((size_t )base ,nullptr ); 436 std::vector < uint64_t > csize ; 437 std::vector < std::pair < int ,uint64_t >> at ((size_t )base ); 438uint64_t cur = 0 ; 439for (const auto & k :cls_ ) 440for (int s = k .base ;s < k .base + k .n ;++ s ) { 441if (csize .empty ()|| cur + k .pages * PAGE > cmax ) { 442if (!csize .empty ())csize .back ()= cur ; 443csize .push_back (0 ); 444cur = 0 ; 445 } 446at [(size_t )s ]= {(int )csize .size ()- 1 ,cur /PAGE }; 447cur += k .pages * PAGE ; 448 } 449if (!csize .empty ())csize .back ()= cur ; 450if (csize .size ()> 4 ) {err = "metal stream: the arena needs more than 4 buffers (lower STRATA_METAL_ARENA_GB)" ;return false; } 451if (recheck ) {// the memory macOS can give, asked again just before the arena is committed 452uint64_t total = 0 ; 453for (uint64_t b :csize )total += b ; 454const uint64_t allowed = recheck (); 455if (allowed + (64ull <<20 )< total ) { 456shrink_to_ = allowed ; 457err = "metal stream: less memory than planned is free now: the arena shrinks" ; 458return false; 459 } 460 } 461for (uint64_t b :csize ) {// anonymous memory wrapped no-copy: a prompt's buffers can alias a region of it 462void * m = mmap (nullptr , (size_t )b ,PROT_READ |PROT_WRITE ,MAP_ANON |MAP_PRIVATE ,-1 ,0 ); 463if (m == MAP_FAILED ) {err = "metal stream: cannot map the arena" ;return false; } 464chunks_ .push_back (cx .wrap (m , (size_t )b )); 465arena_bytes_ += b ; 466 } 467for (int s = 0 ;s < base ;++ s ) { 468code_ [(size_t )s ]= ((uint32_t )at [(size_t )s ].first <<28 ) | (uint32_t )at [(size_t )s ].second ; 469host_ [(size_t )s ]= chunks_ [(size_t )at [(size_t )s ].first ].as < uint8_t > ()+ at [(size_t )s ].second * PAGE ; 470 } 471smap_ = cx .alloc ((size_t )NL * NE * 4 ); 472 std::memset (smap_ .ptr ,0xFF , (size_t )NL * NE * 4 ); 473slots_ = std::vector < Slot > ((size_t )base ); 474retired_ .assign ((size_t )base ,0 ); 475where_ .assign ((size_t )NL * NE ,-1 ); 476for (auto & k :cls_ ) { 477for (int s = k .base ;s < k .base + k .n ;++ s ) { 478slots_ [(size_t )s ].prev = s == k .base ?-1 :s - 1 ; 479slots_ [(size_t )s ].next = s + 1 == k .base + k .n ?-1 :s + 1 ; 480 } 481k .head = k .n ?k .base :-1 ; 482k .tail = k .n ?k .base + k .n - 1 :-1 ; 483 } 484for (int i = 0 ;i < nio_ ;++ i )io_ .emplace_back ([this ] {io_main (); }); 485// the fill: the ranked pairs in steps (best first; each step in file order) on the I/O threads; before each step 486// grow() asks whether macOS still has the memory for it (arena_grow); the best-ranked ends at the LRU front 487uint64_t step = 1536ull <<20 ; 488if (const char * e = std::getenv ("STRATA_METAL_ARENA_STEP_GB" ))step = std::max < uint64_t > (64ull <<20 , (uint64_t ) (std::atof (e )* 1e9 )); 489 std::vector < int > next_free (cls_ .size ()); 490for (size_t c = 0 ;c < cls_ .size ();++ c )next_free [c ]= cls_ [c ].base ; 491size_t done = 0 ; 492bool stopped = false; 493uint64_t filled = 0 ; 494while (done < fill .size ()) { 495size_t j = done ; 496uint64_t sb = 0 ; 497while (j < fill .size ()&& (sb < step || j == done ))sb += cls_ [(size_t )lay_ [(size_t )fill [j ++ ].first ].cls ].pages * PAGE ; 498if (grow && !grow (sb )) {stopped = true;break ; } 499 std::vector < std::pair < int ,int >> order (fill .begin ()+ (long )done ,fill .begin ()+ (long )j ); 500 std::sort (order .begin (),order .end (), [& ](const auto & a ,const auto & b ) { 501return lay_ [(size_t )a .first ].g + (uint64_t )a .second * lay_ [(size_t )a .first ].gs < 502lay_ [(size_t )b .first ].g + (uint64_t )b .second * lay_ [(size_t )b .first ].gs ; 503 }); 504 { 505 std::lock_guard < std::mutex > g (mu_ ); 506for (const auto & p :order ) { 507const int c = lay_ [(size_t )p .first ].cls ; 508submit (next_free [(size_t )c ]++ ,p .first ,p .second , true); 509 } 510 } 511cv_ .notify_all (); 512 { 513 std::unique_lock < std::mutex > g (mu_ ); 514done_cv_ .wait (g , [& ] {return outstanding_ == 0 ; }); 515 } 516filled += sb ; 517done = j ; 518 } 519uint64_t retired_bytes = 0 ; 520size_t nretired = 0 ; 521 { 522 std::unique_lock < std::mutex > g (mu_ ); 523if (stopped )// the slots not filled stay unused (their pages never touched), all but min_slots of each class 524for (size_t c = 0 ;c < cls_ .size ();++ c ) { 525const Cls & k = cls_ [c ]; 526for (int s = std::max (next_free [c ],k .base + std::min (min_slots ,k .n ));s < k .base + k .n ;++ s ) { 527lru_unlink (s ); 528retired_ [(size_t )s ]= 1 ; 529retired_bytes += k .pages * PAGE ; 530++ nretired ; 531 } 532 } 533// the LRU order = the rank order (best at the front) 534for (size_t i = done ;i -- > 0 ;)lru_front (where_ [(size_t ) (fill [i ].first * NE + fill [i ].second )]); 535 } 536if (stopped ) 537 std::fprintf (stderr ,"strata metal stream: the arena's fill stopped after %.2f GB: macOS's free memory reached what it " 538"keeps; %.2f GB of the arena (%zu slots) stay unused\n" ,filled /1e9 ,retired_bytes /1e9 ,nretired ); 539arena_live_ = arena_bytes_ - retired_bytes ; 540fill_s_ = (now_ms ()- t0 ) /1e3 ; 541fill_bytes_ = bytes_read_ .load (); 542uint64_t pairs = 0 ; 543for (const auto & k :cls_ )pairs += (uint64_t )k .n ; 544 std::fprintf (stderr ,"strata metal stream: expert arena %.2f GB, %llu slots in %zu size classes, %zu experts read from the " 545"profile's top (%zu ranked) in %.1f s (%.2f GB/s); %d I/O threads, read-ahead top %d; %zu buffers\n" , 546 (arena_bytes_ - retired_bytes ) /1e9 , (unsigned long long ) (pairs - nretired ),cls_ .size (),done ,from_profile ,fill_s_ , 547fill_bytes_ /1e9 / std::max (1e-9 ,fill_s_ ),nio_ ,prefetch_ ?pre_k_ :0 ,chunks_ .size ()); 548// Wire the filled arena (mlock). Unwired, the arena is ordinary anonymous memory whenever the GPU is not running a command buffer 549// (the GPU's own wiring ends a few seconds after the last one; a Metal residency set did not hold it either, measured), and 550// macOS compresses it when anything else wants memory: a 20 GB file written beside the idle engine took tens of GB of the arena 551// into the compressor in seconds and froze the 128 GB M5 Max (watchdog panic, 2026-10-13). Wired, a file write can only 552// shrink the file cache. STRATA_METAL_WIRE_ARENA=0/1; the default is on for a Mac of 64 GB or more (the M4 32 GB was measured 553// unwired). Not when the fill stopped early for lack of memory (the unused slots would be wired too). 554 { 555uint64_t phys = 0 ; 556size_t plen = sizeof phys ; 557sysctlbyname ("hw.memsize" ,& phys ,& plen ,nullptr ,0 ); 558const char * we = std::getenv ("STRATA_METAL_WIRE_ARENA" ); 559const bool want = we && * we ? std::atoi (we )!= 0 : (double )phys >=kBigMac ; 560if (want && !stopped ) { 561const double tp = now_ms (); 562uint64_t pinned = 0 ; 563int failed = 0 ; 564for (const auto & c :chunks_ ) { 565if (mlock (c .ptr ,c .bytes )== 0 )pinned += c .bytes ; 566else ++ failed ; 567 } 568 std::fprintf (stderr ,"strata metal stream: %.1f GB of the arena wired (mlock) in %.0f ms%s; macOS cannot compress it while " 569"the engine idles (STRATA_METAL_WIRE_ARENA=0 turns it off)\n" ,pinned /1e9 ,now_ms ()- tp , 570failed ?"; SOME CHUNKS COULD NOT BE WIRED" :"" ); 571 } 572 } 573 (void )err ; 574return true; 575} 576 577// the experts a predicted routing names, most likely first (by the best logit over the window's tokens) 578void ExpertStream ::ahead (int ln ,int T ,const float * pred ,int K ) { 579K = std::min (K ,32 ); 580 std::pair < float ,int > pw [8 * 32 ]; 581int np = 0 ; 582for (int t = 0 ;t < T ;++ t ) { 583const float * lg = pred + (size_t )t * NE ; 584int top [32 ]; 585int nt = 0 ; 586for (int e = 0 ;e < ne_ ;++ e ) { 587if (nt < K ) {top [nt ++ ]= e ;continue ; } 588int m = 0 ; 589for (int j = 1 ;j < K ;++ j )if (lg [top [j ]]< lg [top [m ]])m = j ; 590if (lg [e ]> lg [top [m ]])top [m ]= e ; 591 } 592for (int j = 0 ;j < nt ;++ j ) { 593int q = 0 ; 594while (q < np && pw [q ].second != top [j ])++ q ; 595if (q == np )pw [np ++ ]= {lg [top [j ]],top [j ]}; 596else pw [q ].first = std::max (pw [q ].first ,lg [top [j ]]); 597 } 598 } 599 std::sort (pw ,pw + np , [](const auto & a ,const auto & b ) {return a .first > b .first ; }); 600bool any = false; 601 { 602 std::lock_guard < std::mutex > g (mu_ ); 603for (int j = 0 ;j < np ;++ j ) { 604const int key = ln * NE + pw [j ].second ; 605const int s0 = where_ [(size_t )key ]; 606if (s0 >=0 ) {lru_front (s0 );continue ; } 607const int s = victim (lay_ [(size_t )ln ].cls ); 608if (s < 0 )break ; 609submit (s ,ln ,pw [j ].second , false); 610slots_ [(size_t )s ].pin = stamp_ ; 611if (pre_mru_ )lru_front (s ); 612else lru_back (s ); 613++ pre_issued_ ; 614any = true; 615 } 616 } 617if (any )cv_ .notify_all (); 618} 619 620void ExpertStream ::at_layer (int l ,int T ,int topk ,const int32_t * ids ,const float * pred ,const float * pred2 ) { 621const double t0 = now_ms (); 622const bool prompt = T > 8 ;// a prompt chunk (the GEMM path): nearly every expert of the layer is used 623if (l == 0 ) {if (prompt )++ p_chunks_ ;else ++ windows_ ; } 624++ stamp_ ;// the slots this layer uses are pinned until the next handshake 625bool used [NE ]= {}; 626int want [NE ]; 627int nw = 0 ; 628for (int i = 0 ;i < T * topk ;++ i ) { 629const int e = ids [i ]; 630if (e < 0 || e >=NE || used [e ])continue ; 631used [e ]= true; 632want [nw ++ ]= e ; 633 } 634if (fake_ ) { 635for (int j = 0 ;j < nw ;++ j ) 636if (where_ [(size_t ) (l * NE + want [j ])]< 0 )smap_ .as < uint32_t > ()[l * NE + want [j ]]= code_ [0 ]; 637host_ms_ += now_ms ()- t0 ; 638return ; 639 } 640 std::vector < int > wait ; 641 { 642 std::lock_guard < std::mutex > g (mu_ ); 643// read-aheads of this layer (or older) that were not started and are not wanted: dropped (the slot goes free) 644 { 645 std::vector < int > drop ; 646for (const Job & j :pre_q_ ) { 647if (j .layer > l || slots_ [(size_t )j .slot ].state .load ()!= 1 )continue ; 648if (!(j .layer == l && used [j .e ])&& std::find (drop .begin (),drop .end (),j .slot )== drop .end ())drop .push_back (j .slot ); 649 } 650for (int s :drop )cancel_slot (s ); 651 } 652for (int j = 0 ;j < nw ;++ j )// pass 1: pin what is resident (or on its way), so no miss below evicts it 653if (where_ [(size_t ) (l * NE + want [j ])] >=0 )slots_ [(size_t )where_ [(size_t ) (l * NE + want [j ])]].pin = stamp_ ; 654for (int j = 0 ;j < nw ;++ j ) { 655const int e = want [j ],key = l * NE + e ; 656uint64_t & lk = prompt ?p_lookups_ :lookups_ ; 657++ lk ; 658int s = where_ [(size_t )key ]; 659if (s >=0 ) { 660Slot & x = slots_ [(size_t )s ]; 661x .pin = stamp_ ; 662const int st = x .state .load (); 663if (st == 0 ) {if (x .pre )++ (prompt ?p_pre_ :pre_hits_ );else ++ (prompt ?p_hits_ :hits_ ); } 664else { 665++ (prompt ?p_pre_ :pre_hits_ ); 666if (!prompt )++ late_ ; 667promote_slot (s );// a queued read-ahead becomes urgent 668wait .push_back (s ); 669 } 670if (!(prompt && x .pre ))lru_front (s );// a prompt's streamed experts stay at the LRU tail 671x .pre = false; 672continue ; 673 } 674++ (prompt ?p_misses_ :misses_ ); 675s = victim (lay_ [(size_t )l ].cls ); 676if (s < 0 ) { std::fprintf (stderr ,"strata metal stream: no free slot (layer %d)\n" ,l ); std::exit (6 ); } 677submit (s ,l ,e , true); 678slots_ [(size_t )s ].pin = stamp_ ; 679if (!prompt )lru_front (s ); 680wait .push_back (s ); 681 } 682 } 683if (!wait .empty ()) { 684cv_ .notify_all (); 685const double tw = now_ms (); 686 std::unique_lock < std::mutex > g (mu_ ); 687done_cv_ .wait (g , [& ] { 688for (int s :wait )if (slots_ [(size_t )s ].state .load ()!= 0 )return false; 689return true; 690 }); 691 (prompt ?p_wait_ms_ :wait_ms_ )+= now_ms ()- tw ; 692 } 693if (prompt ) { 694// a chunk uses nearly all of the next layer's experts: every one not in the arena is streamed in behind this 695// layer's compute, into the LRU tail (the decode-hot experts stay) 696if (l + 1 < NL ) { 697bool any = false; 698 std::lock_guard < std::mutex > g (mu_ ); 699const int ln = l + 1 ; 700for (int e = 0 ;e < ne_ ;++ e ) { 701if (where_ [(size_t ) (ln * NE + e )] >=0 )continue ; 702const int s = victim (lay_ [(size_t )ln ].cls ); 703if (s < 0 )break ; 704submit (s ,ln ,e , false); 705slots_ [(size_t )s ].pin = stamp_ ; 706++ p_streamed_ ; 707any = true; 708 } 709if (any )cv_ .notify_all (); 710 } 711 (prompt ?p_host_ms_ :host_ms_ )+= now_ms ()- t0 ; 712return ; 713 } 714// read-ahead: layer l + 1 (each token's top pre_k_ of the predicted router logits), then layer l + 2 (top pre_k2_) 715if (prefetch_ && pred && l + 1 < NL )ahead (l + 1 ,T ,pred ,pre_k_ ); 716if (pre_k2_ > 0 && pred2 && l + 2 < NL )ahead (l + 2 ,T ,pred2 ,pre_k2_ ); 717host_ms_ += now_ms ()- t0 ; 718} 719 720// A region of `bytes` at the end of one arena buffer, for a prompt's scratch buffers: its slots are emptied and held 721// (state 3) while a prompt runs (hold_region), and are ordinary slots again for decoding. 722uint8_t * ExpertStream ::region (uint64_t bytes ) { 723for (int c = (int )chunks_ .size ()- 1 ;c >=0 ;-- c ) { 724if (chunks_ [(size_t )c ].bytes < bytes + (64ull <<20 ))continue ; 725uint8_t * end = chunks_ [(size_t )c ].as < uint8_t > ()+ chunks_ [(size_t )c ].bytes ; 726uint8_t * lo = end - (bytes + PAGE - 1 ) /PAGE * PAGE ; 727region_slots_ .clear (); 728uint8_t * first = end ; 729for (int s = 0 ;s < (int )slots_ .size ();++ s ) { 730const uint8_t * h = host_ [(size_t )s ]; 731const uint64_t sz = cls_ [(size_t )cls_of (s )].pages * PAGE ; 732if (h + sz > lo && h < end ) {region_slots_ .push_back (s );first = std::min (first , (uint8_t * )h ); } 733 } 734 {// a class left with fewer slots than a prompt chunk's layer can use (NE) would stop with "no free slot": a small 735// arena (a Mac with little free memory at start) gets the prompt's buffers as their own allocation instead 736 std::vector < int > stolen (cls_ .size (),0 ); 737for (int s :region_slots_ )++ stolen [(size_t )cls_of (s )]; 738bool tight = false; 739for (size_t i = 0 ;i < cls_ .size ();++ i )tight = tight || (cls_ [i ].n > 0 && cls_ [i ].n - stolen [i ]< ne_ ); 740if (tight )return standalone_region (bytes ); 741 } 742region_ = lo ; 743region_bytes_ = (uint64_t ) (end - lo ); 744 std::fprintf (stderr ,"strata metal stream: %.2f GB of the arena (%zu slots) hold a prompt's buffers while it runs\n" , 745bytes /1e9 ,region_slots_ .size ()); 746return lo ; 747 } 748// no chunk is big enough for the prompt's buffers (an arena that shrank at the start, a 24 GB Mac): the fallback 749// inside the loop above is only reached when a chunk fits, so the buffers get their own allocation here too 750return standalone_region (bytes ); 751} 752 753// The prompt's buffers as their own anonymous allocation (fresh zero pages), when no region of the arena's slots 754// takes them: no slots are held while a prompt runs, and the arena keeps decoding with all of its slots. 755uint8_t * ExpertStream ::standalone_region (uint64_t bytes ) { 756const uint64_t sz = (bytes + PAGE - 1 ) /PAGE * PAGE ; 757void * m = mmap (nullptr , (size_t )sz ,PROT_READ |PROT_WRITE ,MAP_ANON |MAP_PRIVATE ,-1 ,0 ); 758if (m == MAP_FAILED )return nullptr ; 759region_slots_ .clear (); 760region_ = (uint8_t * )m ; 761region_bytes_ = 0 ;// fresh zero pages; nothing in the arena to empty 762 std::fprintf (stderr ,"strata metal stream: the arena is small: the prompt's %.2f GB of buffers are their own " 763"allocation, not a region of its slots\n" ,bytes /1e9 ); 764return region_ ; 765} 766 767void ExpertStream ::hold_region (bool hold ) { 768 std::unique_lock < std::mutex > g (mu_ ); 769if (hold ) { 770// nothing may be reading into those slots: the queued read-aheads are dropped, the running ones waited for 771 std::vector < int > drop ; 772for (const Job & j :pre_q_ ) 773if (slots_ [(size_t )j .slot ].state .load ()== 1 && std::find (drop .begin (),drop .end (),j .slot )== drop .end ()) 774drop .push_back (j .slot ); 775for (int s :drop )cancel_slot (s ); 776done_cv_ .wait (g , [& ] {return outstanding_ == 0 ; }); 777for (int s :region_slots_ ) { 778Slot & x = slots_ [(size_t )s ]; 779if (x .layer >=0 ) { 780const int key = x .layer * NE + x .e ; 781where_ [(size_t )key ]= -1 ; 782smap_ .as < uint32_t > ()[key ]= 0xFFFFFFFFu ; 783 } 784x .layer = x .e = -1 ; 785x .pre = false; 786x .state = 3 ; 787 } 788if (region_ ) std::memset (region_ ,0 , (size_t )region_bytes_ ); 789 }else { 790for (int s :region_slots_ ) { 791slots_ [(size_t )s ].state = 0 ; 792if (!retired_ [(size_t )s ])lru_back (s );// a retired slot's memory serves the prompt only 793 } 794 } 795} 796 797void ExpertStream ::reset_stats () { 798lookups_ = hits_ = pre_hits_ = late_ = misses_ = pre_issued_ = pre_cancel_ = windows_ = 0 ; 799p_lookups_ = p_hits_ = p_pre_ = p_misses_ = p_streamed_ = p_chunks_ = 0 ; 800p_wait_ms_ = p_host_ms_ = 0 ; 801bytes_read_ = 0 ; 802reads_ = 0 ; 803wait_ms_ = host_ms_ = 0 ; 804} 805 806void ExpertStream ::report (FILE * f )const { 807if (!ready ())return ; 808if (p_chunks_ ) 809 std::fprintf (f ,"expert stream prompts %llu chunks: %llu distinct lookups (%.1f per layer), in the arena %.4f, streamed " 810"ahead %.4f, missed %.4f; %llu streamed in; host %.1f ms per chunk, of it waiting %.1f ms\n" , 811 (unsigned long long )p_chunks_ , (unsigned long long )p_lookups_ ,p_lookups_ / (double )NL /p_chunks_ , 812p_hits_ / std::max (1.0 , (double )p_lookups_ ),p_pre_ / std::max (1.0 , (double )p_lookups_ ), 813p_misses_ / std::max (1.0 , (double )p_lookups_ ), (unsigned long long )p_streamed_ ,p_host_ms_ /p_chunks_ , 814p_wait_ms_ /p_chunks_ ); 815const double w = std::max < uint64_t > (1 ,windows_ ); 816 std::fprintf (f , 817"expert stream %llu windows: %llu distinct lookups (%.1f per window), hits %.4f, read-ahead hits " 818"%.4f (%llu of them late), misses %.4f (%.1f per window); read-aheads %llu (%.1f per window, %llu dropped); %.1f MB " 819"read per window (%llu reads); host %.2f ms per window, of it waiting %.2f ms\n" , 820 (unsigned long long )windows_ , (unsigned long long )lookups_ ,lookups_ /w , 821hits_ / std::max (1.0 , (double )lookups_ ),pre_hits_ / std::max (1.0 , (double )lookups_ ), 822 (unsigned long long )late_ ,misses_ / std::max (1.0 , (double )lookups_ ),misses_ /w , 823 (unsigned long long )pre_issued_ ,pre_issued_ /w , (unsigned long long )pre_cancel_ , 824 (bytes_read_ .load ()- 0 ) /1e6 /w , (unsigned long long )reads_ .load (),host_ms_ /w ,wait_ms_ /w ); 825} 826 827}// namespace strata::metal_engine