okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
376c0e158
main
1// Strata. src/dsv41/ds4_store.hpp - the RAM tier of the DeepSeek-V4.1 routed experts as a cache of its own: whole experts read 2// from the model's files by unbuffered requests (the OS page cache neither used nor disturbed), kept in a fixed arena of slots 3// that a replacement policy owns, filled on demand (the CPU lane's picks) and ahead of time (the lookahead's guesses). 4// 5// A slot holds an expert in the engine's blob layout (gate | up | down at the layer's offsets tr[r], the same as a VRAM slot), so 6// the CPU lane's rows read it in place and - when the arena is registered with the GPU - the device kernels read it over PCIe 7// (zero-copy, 24 GB/s on a 5070) through the same plan pointers as a VRAM expert. An expert is three matrices at three file 8// offsets (the GGUF's one tensor a role and layer): each is read aligned (4096) into the slot and moved into place (the read's 9// lead of up to 4095 bytes), the blob layout leaving 8192 bytes between matrices (and around the blob) for the aligned spans. 10// CPU-only read_in_place slots leave matrices at the read addresses returned by mat(); mapped slots keep the canonical layout. 11// 12// Memory: slots are allocated in chunks as they are first needed (private memory), never past the budget nor past the RAM this 13// process can still get less `floor_bytes` (the owner's session and the system keep theirs). 14// 15// Policy (the slot to give up, among the unpinned, not GPU-visible ones): lru (oldest touch), lfu (lowest decayed hit count). 16// A slot whose expert a window is computing is pinned from ensure() to release(); a slot the GPU may read is `visible` until 17// sync() takes it back at a window boundary (the GPU idle), which also publishes the newly ready ones. 18#pragma once 19 20#include "ds4_os.hpp" 21#include "ds4_pool.hpp" 22 23#include <algorithm> 24#include <atomic> 25#include <chrono> 26#include <cmath> 27#include <cstdint> 28#include <cstdio> 29#include <cstdlib> 30#include <cstring> 31#include <functional> 32#include <memory> 33#include <mutex> 34#include <string> 35#include <vector> 36 37namespace strata::ds4 { 38 39class ExpertStore { 40public : 41struct LayerGeo { 42int n_exp = 0 ; 43int file [3 ]= {-1 ,-1 ,-1 }; 44uint64_t off [3 ]= {0 ,0 ,0 },stride [3 ]= {0 ,0 ,0 };// matrix r of expert e: file[r], off[r] + e stride[r] 45uint64_t bytes [3 ]= {0 ,0 ,0 }; 46uint64_t tr [3 ]= {0 ,0 ,0 };// matrix r's place in the blob 47uint64_t blob = 0 ;// the blob's bytes (gaps of 8192 between matrices) 48 }; 49enum Policy {kLru = 0 ,kLfu = 1 }; 50struct Stats { 51 std::atomic < int64_t > hits {0 },misses {0 },prefetched {0 },prefetch_used {0 },prefetch_wasted {0 },evictions {0 },fails {0 }; 52 std::atomic < int64_t > bytes_read {0 },wait_ns {0 },no_slot {0 },cancelled {0 }; 53 }; 54struct Vis {// a slot the GPU may read from now on (dev != 0), or no longer (dev == 0) 55int layer = 0 ,e = 0 ; 56unsigned long long dev = 0 ; 57 }; 58 59struct Cfg { 60int threads = 8 ; 61bool read_in_place = false;// CPU-only slots: keep matrices where aligned reads land them 62size_t piece_bytes = 0 ;// read_in_place: each matrix read in pieces of this (multiple of 4096; 0: one read) 63size_t budget_bytes = 0 ;// the arena at most (grown in chunks as slots are first needed) 64size_t floor_bytes = 8ull <<30 ;// RAM left alone 65Policy policy = kLru ; 66float decay = 0.97f ;// lfu: heat x decay every `decay_every` accesses of its layer 67int decay_every = 240 ; 68 std::function < uint64_t ()> ram_avail ;// the RAM this process can still get (~0: unknown) 69// a new chunk of the arena for the GPU to read in place: returns the device address of `host` (null: not visible) 70 std::function < void * (void * host ,size_t bytes )> map_chunk ; 71 std::function < void (void * host )> unmap_chunk ; 72size_t reserve = 192 ;// slots kept evictable (not visible) for the window's demand and guesses 73int vis_percent = 100 ;// the share of experts the GPU may take (by a fixed hash): the rest stay the CPU lane's, so both lanes work 74 }; 75 76bool init (const Cfg & c ,const std::vector < LayerGeo >& layers ,const std::vector < os::fd_t >& dfds ,const std::vector < os::fd_t >& pfds ) { 77cfg_ = c ; 78if (cfg_ .map_chunk )cfg_ .read_in_place = false; 79geo_ = layers ; 80dfds_ = dfds ; 81pfds_ = pfds ; 82size_t blob = 0 ; 83for (const LayerGeo & g :geo_ )blob = std::max < size_t > (blob ,g .blob ); 84slot_bytes_ = (blob + 2 * kSlack + os::kDirectAlign - 1 )& ~(size_t ) (os::kDirectAlign - 1 ); 85if (blob == 0 || c .budget_bytes < slot_bytes_ )return false; 86nmax_ = c .budget_bytes /slot_bytes_ ; 87// one reserved range for the whole arena (chunks committed as they are needed), 64 KB aligned chunks 88arena_bytes_ = ((nmax_ + kChunk - 1 ) /kChunk )* kChunk * slot_bytes_ ; 89arena_ = (uint8_t * ) os::range_reserve (arena_bytes_ ); 90if (arena_ == nullptr )return false; 91slots_ .reset (new Slot [nmax_ ]); 92where_ .resize (geo_ .size ()); 93heat_ .resize (geo_ .size ()); 94hits_in_layer_ .assign (geo_ .size (),0 ); 95for (size_t l = 0 ;l < geo_ .size ();++ l ) { 96where_ [l ].assign ((size_t )geo_ [l ].n_exp ,-1 ); 97heat_ [l ].assign ((size_t )geo_ [l ].n_exp ,0.0f ); 98 } 99io_ .reset (new IoQueue (std::max (1 ,c .threads ))); 100grow ();// (the first chunk now: whether the GPU can map it is known from the start) 101// DS4_STORE_PREGROW=1 (default on Linux with the GPU mapping, =0 off): the whole arena now. cuMemHostRegister (the GPU mapping of a chunk) taken while a kernel of 102// the decode is running waited on it for good on Linux (H100, driver 580): registering all chunks before the first 103// kernel avoids it 104#if defined(__linux__ ) 105const bool pregrow = cfg_ .map_chunk && !(std::getenv ("DS4_STORE_PREGROW" )!= nullptr && std::atoi (std::getenv ("DS4_STORE_PREGROW" ))== 0 );// (Linux: on with the GPU mapping) 106#else 107const bool pregrow = std::getenv ("DS4_STORE_PREGROW" )!= nullptr && std::atoi (std::getenv ("DS4_STORE_PREGROW" ))!= 0 ; 108#endif 109if (pregrow ) 110while (grow ()) { 111 } 112return true; 113 } 114 ~ExpertStore () { 115io_ .reset (); 116for (size_t i = 0 ;i < chunks_ .size ();++ i ) 117if (cfg_ .unmap_chunk && chunk_dev_ [i ]!= nullptr )cfg_ .unmap_chunk (chunks_ [i ].first ); 118 os::range_release (arena_ ,arena_bytes_ ); 119 } 120 121size_t slot_bytes ()const {return slot_bytes_ ; } 122size_t slots_allocated ()const {return nalloc_ ; } 123size_t slots_max ()const {return nmax_ ; } 124const Stats & stats ()const {return st_ ; } 125double busy_ms ()const {return io_ ?io_ -> busy_ms () :0.0 ; } 126static constexpr size_t kSlack = 8192 ; 127 128/// The slot holding (layer, e) ready to read, or -1. (Any thread; a slot found stays valid while it is pinned or visible.) 129int find (int layer ,int e )const { 130if (layer < 0 || layer >= (int )where_ .size ())return -1 ;// (a layer the store does not cover: the DSpark drafter's) 131const int s = where_ [(size_t )layer ][(size_t )e ]; 132if (s < 0 )return -1 ; 133Slot & sp = slots_ [(size_t )s ]; 134try_ready (sp ); 135return sp .state .load (std::memory_order_acquire )== kReady && sp .layer == layer && sp .expert == e ?s :-1 ; 136 } 137/// (layer, e) in the store: 2 ready, 1 its read in flight, 0 not here 138int state_of (int layer ,int e )const { 139if (layer < 0 || layer >= (int )where_ .size ())return 0 ; 140const int s = where_ [(size_t )layer ][(size_t )e ]; 141if (s < 0 )return 0 ; 142Slot & sp = slots_ [(size_t )s ]; 143try_ready (sp ); 144const int st = sp .state .load (std::memory_order_acquire ); 145return st == kReady ?2 :st == kLoading ?1 :0 ; 146 } 147const uint8_t * mat (int slot ,int r )const { 148const Slot & sp = slots_ [(size_t )slot ]; 149const LayerGeo & g = geo_ [(size_t )sp .layer ]; 150uint8_t * fin = sp .base + g .tr [r ]; 151if (!cfg_ .read_in_place )return fin ; 152const uint64_t lead = (g .off [r ]+ (uint64_t )sp .expert * g .stride [r ]) % os::kDirectAlign ; 153return read_base (fin ,lead )+ lead ; 154 } 155/// The device address of the slot's blob (0: the arena is not mapped for the GPU) 156unsigned long long dev_blob (int slot )const { 157const size_t c = (size_t )slot /kChunk ; 158if (c >=chunk_dev_ .size ()|| chunk_dev_ [c ]== nullptr )return 0 ; 159return (unsigned long long ) ((uint8_t * )chunk_dev_ [c ]+ (slots_ [(size_t )slot ].base - (uint8_t * )chunks_ [c ].first )); 160 } 161 162/// Makes the experts es[0..n) of `layer` ready and pinned (reading what is not here), waiting for the reads; the 163/// caller releases them. False if a read failed or no slot could be had for one (ok[i] says which are fine; the caller 164/// reads the others another way). 165bool ensure (int layer ,const int * es ,int n , std::vector < char >& ok ) { 166 std::vector < int > sl ; 167begin (layer ,es ,n ,ok ,sl ); 168return wait_slots (sl ,ok ,0 ,n ); 169 } 170/// The first half of ensure(): the experts' slots found or their reads started (pinned), no waiting. sl[i] is the slot or -1. 171void begin (int layer ,const int * es ,int n , std::vector < char >& ok , std::vector < int >& sl ) { 172ok .assign ((size_t )n ,0 ); 173sl .assign ((size_t )n ,-1 ); 174if (layer < 0 || layer >= (int )geo_ .size ())return ; 175 std::lock_guard < std::mutex > lk (mu_ ); 176for (int i = 0 ;i < n ;++ i ) { 177const int e = es [i ]; 178touch_heat (layer ,e ); 179int s = where_ [(size_t )layer ][(size_t )e ]; 180if (s >=0 ) { 181Slot & sp = slots_ [(size_t )s ]; 182try_ready (sp ); 183if (sp .state .load ()== kReady && !sp .prefetch )st_ .hits .fetch_add (1 , std::memory_order_relaxed ); 184if (sp .prefetch )st_ .prefetch_used .fetch_add (1 , std::memory_order_relaxed ); 185sp .prefetch = false; 186sp .pin ++ ; 187sp .tick = ++ clock_ ; 188sl [(size_t )i ]= s ; 189continue ; 190 } 191st_ .misses .fetch_add (1 , std::memory_order_relaxed ); 192s = start_fill (layer ,e , true); 193sl [(size_t )i ]= s ; 194 } 195 } 196/// Whether bytes [lo, hi) of slot s's matrix r (a slot from begin, pinned) have landed: 1 yes, -1 a read of the slot 197/// failed and these did not land (read them elsewhere), 0 not yet. 198int bytes_ready (int s ,int r ,uint64_t lo ,uint64_t hi )const { 199const Slot & sp = slots_ [(size_t )s ]; 200const uint64_t pb = sp .pbytes [r ]; 201const uint64_t lead = (geo_ [(size_t )sp .layer ].off [r ]+ (uint64_t )sp .expert * geo_ [(size_t )sp .layer ].stride [r ]) % os::kDirectAlign ; 202const uint64_t k0 = (lead + lo ) /pb ,k1 = (lead + hi - 1 ) /pb ; 203const uint64_t need = (k1 >=63 ? ~0ull : ((1ull << (k1 + 1 ))- 1 ))& ~((1ull <<k0 )- 1 ); 204if ((sp .mask [r ].load (std::memory_order_acquire )& need )== need )return 1 ; 205return sp .bad .load (std::memory_order_acquire ) ?-1 :0 ; 206 } 207/// True when the reads of slot sl (from begin) are all done. 208bool loaded (int s )const {return s >=0 && slots_ [(size_t )s ].left .load (std::memory_order_acquire ) <=0 ; } 209/// The second half: waits for the slots sl[a..b) and marks ok[i] for the good ones. False if any failed or had no slot. 210bool wait_slots (std::vector < int >& sl , std::vector < char >& ok ,int a ,int b ) { 211const auto t0 = std::chrono::steady_clock::now (); 212bool all = true; 213for (int i = a ;i < b ;++ i ) { 214const int s = sl [(size_t )i ]; 215if (s < 0 ) { 216all = false; 217continue ; 218 } 219Slot & sp = slots_ [(size_t )s ]; 220while (sp .left .load (std::memory_order_acquire )> 0 )io_ -> wait_any (2000 ,& sp .left ); 221 std::lock_guard < std::mutex > lk (mu_ ); 222finish (sp ,sp .pin <=1 ); 223if (sp .state .load ()== kReady )ok [(size_t )i ]= 1 ; 224else { 225sp .pin -- ; 226sl [(size_t )i ]= -1 ; 227all = false; 228 } 229 } 230st_ .wait_ns .fetch_add (std::chrono::duration_cast < std::chrono::nanoseconds > (std::chrono::steady_clock::now ()- t0 ).count (), 231 std::memory_order_relaxed ); 232return all ; 233 } 234void release (int layer ,const int * es ,int n ,const std::vector < char >& ok ) { 235if (layer < 0 || layer >= (int )geo_ .size ())return ; 236 std::lock_guard < std::mutex > lk (mu_ ); 237for (int i = 0 ;i < n ;++ i ) 238if (ok [(size_t )i ]) { 239const int s = where_ [(size_t )layer ][(size_t )es [i ]]; 240if (s >=0 && slots_ [(size_t )s ].pin > 0 )slots_ [(size_t )s ].pin -- ; 241 } 242 } 243/// Starts reading (layer, e) if it is neither here nor on its way (a guess: unpinned, may be given up before it is used). 244void prefetch (int layer ,int e ) { 245if (layer < 0 || layer >= (int )geo_ .size ()|| e < 0 || e >=geo_ [(size_t )layer ].n_exp )return ; 246if (where_ [(size_t )layer ][(size_t )e ] >=0 )return ; 247 std::lock_guard < std::mutex > lk (mu_ ); 248if (where_ [(size_t )layer ][(size_t )e ] >=0 )return ; 249if (start_fill (layer ,e , false) >=0 )st_ .prefetched .fetch_add (1 , std::memory_order_relaxed ); 250 } 251/// Reads the experts of `list` (layer, expert; hottest first) into free slots and returns when they are in (a start that 252/// is already warm: the profile's hottest, so the first tokens find them). The first `list.size()` fit the arena less 253/// `leave` slots; returns how many were read. 254size_t preload (const std::vector < std::pair < int ,int >>& list ,size_t leave ) { 255size_t n = 0 ; 256 { 257 std::lock_guard < std::mutex > lk (mu_ ); 258const size_t room = nmax_ > leave ?nmax_ - leave :0 ; 259const size_t take = std::min (list .size (),room ); 260for (size_t k = take ;k -- > 0 ;) {// (coldest first: the hottest get the newest ticks) 261const int layer = list [k ].first ,e = list [k ].second ; 262if (layer < 0 || layer >= (int )geo_ .size ()|| e < 0 || e >=geo_ [(size_t )layer ].n_exp )continue ; 263if (where_ [(size_t )layer ][(size_t )e ] >=0 )continue ; 264const int s = start_fill (layer ,e , false); 265if (s < 0 )break ; 266slots_ [(size_t )s ].prefetch = false;// (warm, not a guess) 267++ n ; 268 } 269 } 270for (size_t i = 0 ;;++ i ) {// until every read is done 271bool busy = false; 272 { 273 std::lock_guard < std::mutex > lk (mu_ ); 274for (size_t j = 0 ;j < nalloc_ ;++ j ) { 275Slot & sp = slots_ [j ]; 276if (sp .state .load (std::memory_order_acquire )!= kLoading )continue ; 277if (sp .left .load (std::memory_order_acquire )> 0 )busy = true; 278else { 279try_ready (sp ); 280if (sp .state .load (std::memory_order_acquire )== kLoading )finish (sp ); 281 } 282 } 283 } 284if (!busy )break ; 285io_ -> wait_any (5000 ); 286 } 287return n ; 288 } 289/// Guesses still waiting in the queue for a layer the token is past: dropped unread (their slots free once the queue has gone by) 290void cancel_stale (int layer_now ) { 291 std::lock_guard < std::mutex > lk (mu_ ); 292for (size_t i = 0 ;i < nalloc_ ;++ i ) { 293Slot & sp = slots_ [i ]; 294if (sp .prefetch && sp .pin == 0 && sp .layer >=0 && sp .layer <=layer_now && sp .state .load (std::memory_order_acquire )== kLoading ) 295sp .cancel .store (true, std::memory_order_release ); 296 } 297 } 298/// An access the host saw for an expert the GPU computed (keeps it warm in the policy's eyes). 299void touch (int layer ,int e ) { 300if (layer < 0 || layer >= (int )where_ .size ())return ; 301 std::lock_guard < std::mutex > lk (mu_ ); 302touch_heat (layer ,e ); 303const int s = where_ [(size_t )layer ][(size_t )e ]; 304if (s >=0 )slots_ [(size_t )s ].tick = ++ clock_ ; 305 } 306bool gpu_mapped ()const {return !chunk_dev_ .empty ()&& chunk_dev_ [0 ]!= nullptr ; } 307/// The arena's address range (the device sees its host pointers as they are when the mapping is the identity) 308unsigned long long arena_lo ()const {return (unsigned long long ) (uintptr_t )arena_ ; } 309unsigned long long arena_hi ()const {return (unsigned long long ) (uintptr_t ) (arena_ + arena_bytes_ ); } 310bool identity_mapped ()const { 311for (size_t i = 0 ;i < chunks_ .size ();++ i ) 312if (chunk_dev_ [i ]!= nullptr && chunk_dev_ [i ]!= chunks_ [i ].first )return false; 313return true; 314 } 315size_t max_blob ()const {return slot_bytes_ - 2 * kSlack ; } 316 317/// Waits until no read is in flight (each finished read's slot made ready): DS4_STORE_ZC_DET's window boundary, so which 318/// slots the GPU may read depends on the routing alone, not on how far the drives had got. 319void drain () { 320for (;;) { 321bool busy = false; 322 { 323 std::lock_guard < std::mutex > lk (mu_ ); 324for (size_t j = 0 ;j < nalloc_ ;++ j ) { 325Slot & sp = slots_ [j ]; 326if (sp .state .load (std::memory_order_acquire )!= kLoading )continue ; 327if (sp .left .load (std::memory_order_acquire )> 0 )busy = true; 328else { 329try_ready (sp ); 330if (sp .state .load (std::memory_order_acquire )== kLoading )finish (sp ); 331 } 332 } 333 } 334if (!busy )return ; 335io_ -> wait_any (5000 ); 336 } 337 } 338/// At a window boundary (nothing reading the slots; the caller applies `ev` to the device's table before the next window): 339/// every ready slot not visible yet becomes visible (`gpu_ok(layer, e)`: false for an expert VRAM holds), and visible 340/// slots of the lowest score are taken back until `cfg.reserve` slots can be given up. Returns the number of events. 341size_t sync (std::vector < Vis >& ev ,const std::function < bool (int ,int )>& gpu_ok ) { 342 std::lock_guard < std::mutex > lk (mu_ ); 343size_t nvis = 0 ,nfree = 0 ; 344for (size_t i = 0 ;i < nalloc_ ;++ i ) { 345Slot & sp = slots_ [i ]; 346if (sp .state .load (std::memory_order_acquire )== kLoading && sp .left .load (std::memory_order_acquire )== 0 ) { 347try_ready (sp ); 348if (sp .state .load (std::memory_order_acquire )== kLoading )finish (sp ); 349 } 350const int st = sp .state .load (std::memory_order_acquire ); 351if (st == kFree ) { 352++ nfree ; 353continue ; 354 } 355if (st != kReady )continue ; 356if (sp .visible ) { 357++ nvis ; 358continue ; 359 } 360if (sp .pin == 0 )++ nfree ; 361if (sp .pin == 0 && dev_blob ((int )i )!= 0 && gpu_ok (sp .layer ,sp .expert )&& !sp .prefetch && vis_hash (sp .layer ,sp .expert )< cfg_ .vis_percent ) { 362sp .visible = true; 363++ nvis ; 364if (sp .pin == 0 )-- nfree ; 365ev .push_back ({sp .layer ,sp .expert ,dev_blob ((int )i )}); 366 } 367 } 368// give slots back until the reserve is there: the visible ones with the lowest score 369if (nfree < cfg_ .reserve && nvis > 0 ) { 370 std::vector < std::pair < double ,size_t >> cand ; 371cand .reserve (nvis ); 372for (size_t i = 0 ;i < nalloc_ ;++ i ) 373if (slots_ [i ].visible && slots_ [i ].state .load (std::memory_order_acquire )== kReady )cand .push_back ({score (slots_ [i ]),i }); 374const size_t want = std::min (cand .size (),cfg_ .reserve - nfree ); 375 std::partial_sort (cand .begin (),cand .begin ()+ (long )want ,cand .end ()); 376for (size_t k = 0 ;k < want ;++ k ) { 377Slot & sp = slots_ [cand [k ].second ]; 378sp .visible = false; 379ev .push_back ({sp .layer ,sp .expert ,0ull }); 380 } 381 } 382return ev .size (); 383 } 384/// RAM is short: gives back whole chunks from the end of the arena (their experts forgotten) - up to `want`, stopping at one 385/// with a slot in use (pinned, loading, or GPU-visible). Returns the chunks given back. 386size_t shrink_chunks (size_t want ) { 387 std::lock_guard < std::mutex > lk (mu_ ); 388size_t done = 0 ; 389while (done < want && !chunks_ .empty ()) { 390const size_t c = chunks_ .size ()- 1 ,first = c * kChunk ; 391bool busy = false; 392for (size_t i = first ;i < nalloc_ && !busy ;++ i ) { 393Slot & sp = slots_ [i ]; 394if (sp .state .load (std::memory_order_acquire )== kLoading && sp .left .load (std::memory_order_acquire )== 0 ) {// (read by now) 395try_ready (sp ); 396if (sp .state .load (std::memory_order_acquire )== kLoading )finish (sp ); 397 } 398busy = sp .pin > 0 || sp .visible || sp .state .load (std::memory_order_acquire )== kLoading ; 399 } 400if (busy )break ; 401for (size_t i = first ;i < nalloc_ ;++ i ) { 402Slot & sp = slots_ [i ]; 403if (sp .layer >=0 && sp .expert >=0 ) { 404where_ [(size_t )sp .layer ][(size_t )sp .expert ]= -1 ; 405st_ .evictions .fetch_add (1 , std::memory_order_relaxed ); 406 } 407sp .layer = sp .expert = -1 ; 408sp .prefetch = false; 409sp .state .store (kFree , std::memory_order_release ); 410sp .base = nullptr ; 411 } 412if (cfg_ .unmap_chunk && chunk_dev_ [c ]!= nullptr )cfg_ .unmap_chunk (chunks_ [c ].first ); 413 os::range_decommit (chunks_ [c ].first ,chunks_ [c ].second ); 414chunks_ .pop_back (); 415chunk_dev_ .pop_back (); 416nalloc_ = first ; 417free_hint_ = std::min (free_hint_ ,first ); 418++ done ; 419++ shrunk_ ; 420 } 421return done ; 422 } 423size_t shrunk ()const {return shrunk_ ; } 424/// An expert VRAM took over: no longer a visible slot 425void unmark (int layer ,int e ) { 426if (layer < 0 || layer >= (int )where_ .size ())return ; 427 std::lock_guard < std::mutex > lk (mu_ ); 428const int s = where_ [(size_t )layer ][(size_t )e ]; 429if (s >=0 )slots_ [(size_t )s ].visible = false; 430 } 431size_t visible_count ()const { 432size_t n = 0 ; 433for (size_t i = 0 ;i < nalloc_ ;++ i )n += slots_ [i ].visible ?1 :0 ; 434return n ; 435 } 436 437private : 438static uint8_t * read_base (uint8_t * fin ,uint64_t lead ) { 439return (uint8_t * ) ((uintptr_t ) (fin - lead )& ~(uintptr_t ) (os::kDirectAlign - 1 )); 440 } 441static constexpr int kFree = 0 ,kLoading = 1 ,kReady = 2 ,kFailed = 3 ; 442// slots a chunk of the arena (the unit the GPU mapping registers; DS4_STORE_CHUNK_SLOTS: a test knob for the registration segment size) 443static size_t chunk_slots () { 444const char * e = std::getenv ("DS4_STORE_CHUNK_SLOTS" ); 445const long v = e ? std::atol (e ) :0 ; 446return v >=8 && v <=4096 ? (size_t )v :64 ; 447 } 448const size_t kChunk = chunk_slots (); 449struct Slot { 450uint8_t * base = nullptr ;// the blob's first byte 451int layer = -1 ,expert = -1 ,pin = 0 ; 452bool prefetch = false,visible = false; 453 std::atomic < int > state {kFree },left {0 }; 454 std::atomic < bool > bad {false},cancel {false}; 455 std::atomic < uint64_t > mask [3 ]= {};// the pieces of each matrix that have landed 456uint64_t pbytes [3 ]= {};// a piece's bytes (from the matrix's aligned read start) 457uint64_t tick = 0 ; 458 }; 459 460static int vis_hash (int layer ,int e ) {return (int ) (((unsigned )layer * 2654435761u + (unsigned )e * 40503u ) >>7 ) %100 ; } 461double score (const Slot & sp )const { 462if (cfg_ .policy == kLru )return (double )sp .tick ; 463return (double )heat_ [(size_t )sp .layer ][(size_t )sp .expert ]+ 1e-9 * (double )sp .tick ; 464 } 465void touch_heat (int layer ,int e ) { 466heat_ [(size_t )layer ][(size_t )e ]+= 1.0f ; 467if (cfg_ .policy != kLru && ++ hits_in_layer_ [(size_t )layer ] % (uint64_t )cfg_ .decay_every == 0 ) 468for (float & h :heat_ [(size_t )layer ])h *=cfg_ .decay ;// (a linear pass over 384 floats every 240 accesses of that layer) 469 } 470// a slot for (layer, e) and its reads started; -1 if there is none to be had. mu_ held. 471int start_fill (int layer ,int e ,bool demand ) { 472int s = take_slot (demand ); 473if (s < 0 ) { 474st_ .no_slot .fetch_add (1 , std::memory_order_relaxed ); 475return -1 ; 476 } 477Slot & sp = slots_ [(size_t )s ]; 478if (sp .layer >=0 && sp .expert >=0 ) { 479where_ [(size_t )sp .layer ][(size_t )sp .expert ]= -1 ; 480if (sp .prefetch )st_ .prefetch_wasted .fetch_add (1 , std::memory_order_relaxed ); 481st_ .evictions .fetch_add (1 , std::memory_order_relaxed ); 482 } 483sp .layer = layer ; 484sp .expert = e ; 485sp .pin = demand ?1 :0 ; 486sp .prefetch = !demand ; 487sp .visible = false; 488sp .tick = ++ clock_ ; 489sp .state .store (kLoading , std::memory_order_release ); 490sp .bad .store (false); 491sp .cancel .store (false); 492where_ [(size_t )layer ][(size_t )e ]= s ; 493const LayerGeo & g = geo_ [(size_t )layer ]; 494IoQueue ::Job jobs [3 ]; 495if (cfg_ .read_in_place && cfg_ .piece_bytes > 0 )return start_pieces (sp ,s ,layer ,e ,demand ); 496sp .left .store (3 , std::memory_order_release ); 497for (int r = 0 ;r < 3 ;++ r ) { 498const uint64_t off = g .off [r ]+ (uint64_t )e * g .stride [r ]; 499const uint64_t lead = off % os::kDirectAlign ; 500uint8_t * fin = sp .base + g .tr [r ];// where the matrix belongs 501// the aligned read lands the file's byte `off` at dst + lead: dst is fin - lead rounded down to 4096 (its span spills 502// under 4096 bytes either way into the blob's gaps), the matrix is then moved up to fin 503uint8_t * dst = read_base (fin ,lead ); 504IoQueue ::Job & j = jobs [r ]; 505j .fd = pfds_ [(size_t )g .file [r ]]; 506j .dfd = dfds_ [(size_t )g .file [r ]]; 507j .off = off ; 508j .len = g .bytes [r ]; 509j .dst = dst ; 510j .keep = cfg_ .read_in_place ?nullptr :fin ; 511j .left = & sp .left ; 512j .bad = & sp .bad ; 513j .cancel = demand ?nullptr :& sp .cancel ; 514sp .mask [r ].store (0 , std::memory_order_relaxed ); 515sp .pbytes [r ]= os::direct_span (off ,g .bytes [r ]); 516j .mask = & sp .mask [r ]; 517j .bit = 1 ; 518 } 519st_ .bytes_read .fetch_add ((int64_t ) (g .bytes [0 ]+ g .bytes [1 ]+ g .bytes [2 ]), std::memory_order_relaxed ); 520io_ -> push (jobs ,3 , !demand );// (a guess waits behind every demand read) 521return s ; 522 } 523// start_fill's reads in pieces (read_in_place): each matrix's aligned span cut into at most 64 pieces of piece_bytes or more, 524// landing where the one read would have put them. mu_ held. 525int start_pieces (Slot & sp ,int s ,int layer ,int e ,bool demand ) { 526const LayerGeo & g = geo_ [(size_t )layer ]; 527 std::vector < IoQueue ::Job > per [3 ]; 528for (int r = 0 ;r < 3 ;++ r ) { 529const uint64_t off = g .off [r ]+ (uint64_t )e * g .stride [r ],lead = off % os::kDirectAlign ,a0 = off - lead ; 530const uint64_t span = os::direct_span (off ,g .bytes [r ]); 531uint64_t pb = std::max < uint64_t > (cfg_ .piece_bytes , (span + 63 ) /64 ); 532pb = (pb + os::kDirectAlign - 1 )& ~(uint64_t ) (os::kDirectAlign - 1 ); 533sp .pbytes [r ]= pb ; 534sp .mask [r ].store (0 , std::memory_order_relaxed ); 535uint8_t * dst = read_base (sp .base + g .tr [r ],lead ); 536for (uint64_t k = 0 ;k * pb < span ;++ k ) { 537IoQueue ::Job j ; 538j .fd = pfds_ [(size_t )g .file [r ]]; 539j .dfd = dfds_ [(size_t )g .file [r ]]; 540j .off = a0 + k * pb ; 541j .len = std::min (off + g .bytes [r ],a0 + (k + 1 )* pb )- j .off ; 542j .dst = dst + k * pb ; 543j .left = & sp .left ; 544j .bad = & sp .bad ; 545j .cancel = demand ?nullptr :& sp .cancel ; 546j .mask = & sp .mask [r ]; 547j .bit = 1ull <<k ; 548per [r ].push_back (j ); 549 } 550 } 551// gate and up piece by piece (a row's gate/up job needs both), then down 552 std::vector < IoQueue ::Job > jobs ; 553for (size_t k = 0 ;k < std::max (per [0 ].size (),per [1 ].size ());++ k ) 554for (int r = 0 ;r < 2 ;++ r ) 555if (k < per [r ].size ())jobs .push_back (per [r ][k ]); 556jobs .insert (jobs .end (),per [2 ].begin (),per [2 ].end ()); 557sp .left .store ((int )jobs .size (), std::memory_order_release ); 558st_ .bytes_read .fetch_add ((int64_t ) (g .bytes [0 ]+ g .bytes [1 ]+ g .bytes [2 ]), std::memory_order_relaxed ); 559io_ -> push (jobs .data (), (int )jobs .size (), !demand ); 560return s ; 561 } 562// loading -> ready once its reads are done and whole (lock-free; a failed one is cleaned up by finish / take_slot) 563void try_ready (Slot & sp )const { 564int want = kLoading ; 565if (sp .left .load (std::memory_order_acquire )== 0 && !sp .bad .load (std::memory_order_acquire )) 566sp .state .compare_exchange_strong (want ,kReady , std::memory_order_acq_rel ); 567 } 568// mu_ held; reads done. A failed (or dropped) read frees the slot - unless it is pinned and `last` is false: a window 569// holding it may still be reading its pieces that did land (DS4_LANE_STREAM), so only its last holder (wait_slots) frees it 570void finish (Slot & sp ,bool last = false) { 571if (sp .state .load ()!= kLoading )return ; 572if (sp .bad .load ()&& sp .pin > 0 && !last )return ; 573if (sp .bad .load ()) { 574where_ [(size_t )sp .layer ][(size_t )sp .expert ]= -1 ; 575sp .layer = sp .expert = -1 ; 576sp .state .store (kFree , std::memory_order_release ); 577sp .prefetch = false; 578if (sp .cancel .load ())st_ .cancelled .fetch_add (1 , std::memory_order_relaxed ); 579else st_ .fails .fetch_add (1 , std::memory_order_relaxed ); 580return ; 581 } 582sp .state .store (kReady , std::memory_order_release ); 583 } 584bool grow () { 585if (nalloc_ >=nmax_ )return false; 586const size_t n = std::min (kChunk ,nmax_ - nalloc_ ); 587const size_t bytes = n * slot_bytes_ ; 588const uint64_t avail = cfg_ .ram_avail ?cfg_ .ram_avail () : ~uint64_t {0 }; 589if (avail != ~uint64_t {0 }&& avail < bytes + cfg_ .floor_bytes )return false; 590void * p = arena_ + nalloc_ * slot_bytes_ ; 591if (!os::range_commit (p ,bytes ))return false; 592chunks_ .push_back ({p ,bytes }); 593void * dev = cfg_ .map_chunk ?cfg_ .map_chunk (p ,bytes ) :nullptr ; 594chunk_dev_ .push_back (dev ); 595for (size_t i = 0 ;i < n ;++ i )slots_ [nalloc_ + i ].base = (uint8_t * )p + i * slot_bytes_ + kSlack ; 596nalloc_ += n ; 597return true; 598 } 599// the slot to give up (or a free one): the policy's lowest among the unpinned, not visible, ready ones. mu_ held. 600int take_slot (bool demand ) { 601for (size_t i = free_hint_ ;i < nalloc_ ;++ i ) 602if (slots_ [i ].state .load (std::memory_order_acquire )== kFree ) { 603free_hint_ = i + 1 ; 604return (int )i ; 605 } 606if (grow ())return take_slot (demand ); 607int best = -1 ; 608double bv = 0 ; 609for (size_t i = 0 ;i < nalloc_ ;++ i ) { 610Slot & sp = slots_ [i ]; 611if (sp .state .load (std::memory_order_acquire )== kLoading && sp .left .load (std::memory_order_acquire )== 0 ) { 612try_ready (sp ); 613if (sp .state .load (std::memory_order_acquire )== kLoading )finish (sp ); 614if (sp .state .load (std::memory_order_acquire )== kFree ) { 615free_hint_ = std::min (free_hint_ ,i ); 616return (int )i ; 617 } 618 } 619if (sp .pin > 0 || sp .visible || sp .state .load (std::memory_order_acquire )!= kReady )continue ; 620const double v = score (sp ); 621if (best < 0 || v < bv ) { 622best = (int )i ; 623bv = v ; 624 } 625 } 626if (best < 0 )return -1 ; 627free_hint_ = std::min < size_t > (free_hint_ , (size_t )best ); 628return best ; 629 } 630 631Cfg cfg_ ; 632 std::vector < LayerGeo > geo_ ; 633 std::vector < os::fd_t > dfds_ ,pfds_ ; 634size_t slot_bytes_ = 0 ,nmax_ = 0 ,nalloc_ = 0 ,free_hint_ = 0 ,arena_bytes_ = 0 ; 635uint8_t * arena_ = nullptr ; 636size_t shrunk_ = 0 ; 637 std::unique_ptr < Slot []> slots_ ; 638 std::vector < std::pair < void * ,size_t >> chunks_ ; 639 std::vector < void *> chunk_dev_ ; 640 std::vector < std::vector < int >> where_ ; 641 std::vector < std::vector < float >> heat_ ; 642 std::vector < uint64_t > hits_in_layer_ ; 643uint64_t clock_ = 0 ; 644 std::mutex mu_ ; 645 std::unique_ptr < IoQueue > io_ ; 646Stats st_ ; 647}; 648 649}// namespace strata::ds4