okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7961f0837
main
1// src/core/peer_experts.cpp - see include/strata/core/peer_experts.hpp. 2#include "strata/core/peer_experts.hpp" 3 4#include "strata/core/device.hpp" // primary_device() (STRATA_PRIMARY_DEVICE) 5#include "strata/kernels/cpu/expert_layout.hpp" 6#include "strata/kernels/cpu/hadamard.hpp" 7#include "strata/kernels/elementwise.hpp" 8#include "strata/kernels/iq_kernels.hpp" 9#include "strata/kernels/quantize_act.hpp" 10#include "strata/kernels/s2_expert_grouped.hpp" 11#include "strata/kernels/window_limits.hpp" 12 13#include <algorithm> 14#include <chrono> 15#include <cstdio> 16#include <cstring> 17#include <cstdlib> 18#include <stdexcept> 19#include <vector> 20 21namespace strata::core { 22 23static bool g_peer_portable = false; 24void set_peer_portable (bool on ) {g_peer_portable = on ; } 25bool peer_portable () {return g_peer_portable ; } 26 27namespace { 28 29constexpr int64_t H = strata::kernels::cpu::H ; 30constexpr int64_t CAP = strata::kernels::kWindowMaxT * 10 ;// entries per layer: a window's rows x top-10 31 32struct Meta {// one block, uploaded with one copy per layer 33unsigned long long ptr [CAP ]; 34int32_t start [CAP + 1 ]; 35int32_t dst [CAP ]; 36int32_t tok [CAP ]; 37int32_t count [4 ];// [0] groups, [1] entries 38int32_t out_row [CAP ];// multi-GPU: compact row -> entry row in the host `out` 39}; 40 41/// Switches the calling thread to `dev` and back. The engine's own thread lives on device 0. 42struct On { 43int prev = 0 ; 44explicit On (int dev ) {cudaGetDevice (& prev );if (prev != dev )cudaSetDevice (dev ); } 45 ~On () {int cur = 0 ;cudaGetDevice (& cur );if (cur != prev )cudaSetDevice (prev ); } 46}; 47 48/// #2666: `cudaDeviceCanAccessPeer` said yes and `cudaDeviceEnablePeerAccess` succeeded, and on a pair of GPUs behind a host bridge 49/// (2x RTX A4000, "PHB" in nvidia-smi topo) `cudaMemcpyPeerAsync` then returned success having moved nothing: the peer's input rows 50/// were zeros and the rows it sent back never arrived, so the first prompt's MoE output was garbage and the logits NaN. Without 51/// peer access enabled the same copies are right (the driver stages them). So the pair is asked once, with a small copy each way, 52/// whether the direct path really carries data. true = both ways exact (or nothing could be tested: the old trust is kept). 53bool p2p_copies_data (int device ) { 54constexpr size_t kN = 1 <<14 ;// floats 55 std::vector < float > h (kN ),back (kN ); 56for (size_t i = 0 ;i < kN ;++ i )h [i ]= 1.0f + (float ) ((i * 2654435761u ) %4093u ); 57float * d [2 ]= {nullptr ,nullptr }; 58const int dev [2 ]= {0 ,device }; 59bool ok = true,tested = true; 60for (int k = 0 ;k < 2 && tested ;++ k ) { 61On on (dev [k ]); 62if (cudaMalloc ((void ** )& d [k ],kN * 4 )!= cudaSuccess ) {cudaGetLastError ();tested = false; } 63 } 64for (int dir = 0 ;dir < 2 && tested && ok ;++ dir ) {// 0: device 0 -> peer, 1: peer -> device 0 65const int from = dir == 0 ?0 :1 ,to = 1 - from ; 66 { 67On on (dev [from ]); 68if (cudaMemcpy (d [from ],h .data (),kN * 4 ,cudaMemcpyHostToDevice )!= cudaSuccess ) {tested = false;break ; } 69 } 70 { 71On on (dev [to ]); 72if (cudaMemset (d [to ],0 ,kN * 4 )!= cudaSuccess ) {tested = false;break ; } 73 } 74if (cudaMemcpyPeer (d [to ],dev [to ],d [from ],dev [from ],kN * 4 )!= cudaSuccess ) {tested = false;break ; } 75 { 76On on (dev [to ]); 77if (cudaMemcpy (back .data (),d [to ],kN * 4 ,cudaMemcpyDeviceToHost )!= cudaSuccess ) {tested = false;break ; } 78 } 79ok = std::memcmp (back .data (),h .data (),kN * 4 )== 0 ; 80 } 81for (int k = 0 ;k < 2 ;++ k ) 82if (d [k ]!= nullptr ) {On on (dev [k ]);cudaFree (d [k ]); } 83if (!tested ) {cudaGetLastError ();return true; } 84return ok ; 85} 86 87bool ck (cudaError_t e ,const char * what , std::string & err ) { 88if (e == cudaSuccess )return true; 89err = std::string ("peer experts: " )+ what + ": " + cudaGetErrorString (e ); 90return false; 91} 92 93}// namespace 94 95PeerExperts ::~PeerExperts () {close (); } 96 97void PeerExperts ::close () { 98if (device_ < 0 )return ; 99 { 100On on (device_ ); 101if (stream_ )cudaStreamSynchronize (stream_ ); 102if (refill_ )cudaStreamSynchronize (refill_ ); 103cache_ .close (); 104if (d_x_ )cudaFree (d_x_ ); 105if (d_out_ )cudaFree (d_out_ ); 106if (d_meta_ )cudaFree (d_meta_ ); 107if (d_q8_ )cudaFree (d_q8_ ); 108if (d_scratch_ )cudaFree (d_scratch_ ); 109if (h_x_ )cudaFreeHost (h_x_ ); 110if (h_out_ )cudaFreeHost (h_out_ ); 111if (h_meta_ )cudaFreeHost (h_meta_ ); 112if (d_gate_vals_ )cudaFree (d_gate_vals_ ); 113if (h_gate_ )cudaFreeHost ((void * )h_gate_ ); 114if (refill_ev_ )cudaEventDestroy (refill_ev_ ); 115if (stream_ )cudaStreamDestroy (stream_ ); 116if (refill_ )cudaStreamDestroy (refill_ ); 117 } 118d_x_ = d_out_ = h_x_ = h_out_ = nullptr ; 119d_meta_ = h_meta_ = d_scratch_ = nullptr ; 120d_q8_ = nullptr ; 121d_sx_ = d_sh_ = nullptr ; 122d_gate_vals_ = nullptr ; 123h_gate_ = nullptr ; 124stream_ = refill_ = nullptr ; 125refill_ev_ = nullptr ; 126device_ = -1 ; 127} 128 129bool PeerExperts ::open (int device ,const std::vector < std::pair < int32_t ,int32_t >>& ranked ,const ExpertCache & primary , 130ExpertSource & src ,int64_t n_layers ,int64_t n_expert ,int reserve_mib ,int64_t max_slots , 131 std::string & err ) { 132close (); 133int count = 0 ; 134if (!ck (cudaGetDeviceCount (& count ),"cudaGetDeviceCount" ,err ))return false; 135if (device < 1 || device >=count ) { 136err = "peer experts: CUDA device " + std::to_string (device )+ " is not visible (" + std::to_string (count )+ 137" devices; set CUDA_VISIBLE_DEVICES)" ; 138return false; 139 } 140const auto & lay = strata::kernels::cpu::expert_layout (); 141if (lay .native && std::any_of (lay .fmt .begin (),lay .fmt .end (), [](const auto & f ) {return f .n_embd != H ; })) { 142err = "peer experts: latent projections are not supported; use --layer-split" ; 143return false; 144 } 145n_layers_ = n_layers ; 146n_expert_ = n_expert ; 147src_ = & src ; 148res_ .assign ((size_t ) (n_layers * n_expert ),kNotResident ); 149 {// direct access both ways (NVLink or another P2P path): the prompt path copies activations and results over it 150int a = 0 ,b = 0 ; 151cudaDeviceCanAccessPeer (& a ,primary_device (),device ); 152cudaDeviceCanAccessPeer (& b ,device ,primary_device ()); 153if (const char * np = std::getenv ("STRATA_PEER_NO_P2P" );np != nullptr && std::atoi (np )!= 0 )a = 0 ;// test knob: pretend the pair has no P2P 154p2p_ = a && b ; 155if (p2p_ ) { 156On on0 (primary_device ()); 157cudaError_t e0 = cudaDeviceEnablePeerAccess (device ,0 ); 158if (e0 == cudaErrorPeerAccessAlreadyEnabled ) {cudaGetLastError ();e0 = cudaSuccess ; } 159On on1 (device ); 160cudaError_t e1 = cudaDeviceEnablePeerAccess (primary_device (),0 ); 161if (e1 == cudaErrorPeerAccessAlreadyEnabled ) {cudaGetLastError ();e1 = cudaSuccess ; } 162p2p_ = e0 == cudaSuccess && e1 == cudaSuccess ; 163// recommend, never force: the direct path is used only if a test copy each way arrives exact (#2666) 164if (p2p_ && !p2p_copies_data (device )) { 165 std::fprintf (stderr ,"strata: peer GPU %d: peer access is enabled but a test copy between the two GPUs arrived wrong " 166"(a host bridge between them, no real P2P): the prompt path takes the host route instead " 167"(STRATA_PEER_NO_P2P=1 does that by hand)\n" ,device ); 168 {On q0 (0 );cudaDeviceDisablePeerAccess (device );cudaGetLastError (); } 169 {On q1 (device );cudaDeviceDisablePeerAccess (0 );cudaGetLastError (); } 170p2p_ = false; 171 } 172 } 173 } 174On on (device ); 175device_ = device ; 176// scratch first, so the slots take what is really left 177int64_t ff = strata::kernels::cpu::FF ; 178if (lay .native ) 179for (const auto & f :lay .fmt )ff = std::max < int64_t > (ff ,f .n_ff ); 180const size_t scratch = std::max < size_t > ((size_t ) strata::kernels::moe_hit_grouped_scratch_bytes (CAP ,H ,ff ), 181 strata::kernels::native_expert_scratch_bytes (CAP ,ff )); 182const bool alloc_ok = 183ck (cudaStreamCreateWithFlags (& stream_ ,cudaStreamNonBlocking ),"stream" ,err )&& 184ck (cudaStreamCreateWithFlags (& refill_ ,cudaStreamNonBlocking ),"refill stream" ,err )&& 185ck (cudaEventCreateWithFlags (& refill_ev_ ,cudaEventDisableTiming ),"event" ,err )&& 186ck (cudaHostAlloc ((void ** )& h_x_ , (size_t )CAP * H * sizeof (float ),cudaHostAllocPortable |cudaHostAllocMapped ),"input staging" ,err )&& 187ck (cudaHostAlloc ((void ** )& h_out_ , (size_t )CAP * H * sizeof (float ),cudaHostAllocPortable |cudaHostAllocMapped ),"result staging" ,err )&& 188ck (cudaHostAlloc (& h_meta_ ,sizeof (Meta ),cudaHostAllocPortable |cudaHostAllocMapped ),"plan staging" ,err )&& 189ck (cudaMalloc ((void ** )& d_x_ , (size_t )CAP * H * sizeof (float )),"input" ,err )&& 190ck (cudaMalloc ((void ** )& d_out_ , (size_t )CAP * H * sizeof (float )),"result" ,err )&& 191ck (cudaMalloc (& d_meta_ ,sizeof (Meta )),"plan" ,err )&& 192ck (cudaMalloc ((void ** )& d_q8_ , (size_t )CAP * (H /32 )* 36 ),"activations" ,err )&& 193ck (cudaMalloc (& d_scratch_ ,scratch ),"scratch" ,err ); 194if (!alloc_ok ) {close ();return false; } 195if (strata::kernels::cpu::hadamard_spec ().any ()) {// APR: this device's copies of the sign vectors 196d_sx_ = strata::kernels::hadamard_device_signs (strata::kernels::cpu::hadamard_signs ((int )H ), (int )H ); 197d_sh_ = strata::kernels::hadamard_device_signs (strata::kernels::cpu::hadamard_signs ((int )ff ), (int )ff ); 198 } 199 200// the pairs the primary does not hold, in rank order, as many as fit 201size_t free_b = 0 ,total_b = 0 ; 202if (!ck (cudaMemGetInfo (& free_b ,& total_b ),"cudaMemGetInfo" ,err )) {close ();return false; } 203const uint64_t reserve = (uint64_t ) std::max (reserve_mib ,128 ) <<20 ; 204const uint64_t budget = free_b > reserve ?free_b - reserve :0 ; 205 std::vector < std::pair < int32_t ,int32_t >> pick ; 206 std::vector < int64_t > sizes ; 207uint64_t used = 0 ; 208for (const auto & pr :ranked ) { 209if (primary .slot_of (pr .first ,pr .second ) >=0 )continue ; 210const uint64_t b = lay .blob_bytes (pr .first ); 211const uint64_t b256 = lay .native ? (b + 255 ) /256 * 256 :lay .max_blob ; 212if (used + b256 > budget )break ; 213if (max_slots > 0 && (int64_t )pick .size () >=max_slots )break ; 214used += b256 ; 215pick .push_back (pr ); 216sizes .push_back ((int64_t )b ); 217 } 218if (pick .empty ()) {err = "peer experts: no room or no expert left for the peer" ;close ();return false; } 219const bool opened = lay .native ?cache_ .open_sized (sizes ,n_layers ,n_expert ,err ) 220 :cache_ .open ((int64_t )pick .size (),n_layers ,n_expert , (int64_t )lay .max_blob ,err ); 221if (!opened ) {err = "peer experts: " + err ;close ();return false; } 222// open() zeroes the arena with cudaMemset on the legacy stream, which is not ordered against the non-blocking 223// refill stream: wait for it, or the zeroing can land on top of the fills 224if (!ck (cudaDeviceSynchronize (),"arena zeroing" ,err )) {close ();return false; } 225// mapped reads: advise the next kAhead pairs so their reads overlap 226constexpr size_t kAhead = 256 ; 227const bool advise = src .advise_pairs (pick .data (), (int64_t ) std::min (kAhead ,pick .size ())); 228for (size_t i = 0 ;i < pick .size ();++ i ) { 229const auto & pr = pick [i ]; 230if (advise && i + kAhead < pick .size ()) (void )src .advise_pairs (& pick [i + kAhead ],1 ); 231const int32_t slot = cache_ .admit (pr .first ,pr .second ); 232const uint8_t * b = src .blob (pr .first ,pr .second ); 233if (slot < 0 || b == nullptr || !cache_ .fill_slot (slot ,b ,refill_ ,err , (int64_t )lay .blob_bytes (pr .first ))) { 234err = "peer experts: fill failed: " + err ; 235close (); 236return false; 237 } 238src .note_async_read (b ,refill_ );// #1237 239res_ [(size_t ) (pr .first * n_expert + pr .second )]= slot ; 240 } 241if (!ck (cudaStreamSynchronize (refill_ ),"fill" ,err )) {close ();return false; } 242const auto & f0 = pick .front (); 243if (!cache_ .verify_slot (res_ [(size_t ) (f0 .first * n_expert + f0 .second )],src .blob (f0 .first ,f0 .second ),err , 244 (int64_t )lay .blob_bytes (f0 .first ))) { 245err = "peer experts: " + err ; 246close (); 247return false; 248 } 249resident_ = (int64_t )pick .size (); 250return true; 251} 252 253bool PeerExperts ::direct_mode () { 254static const bool v = [] {const char * e = std::getenv ("STRATA_PEER_DIRECT" );return e == nullptr || std::atoi (e )!= 0 ; }(); 255return v ; 256} 257 258bool PeerExperts ::launch (int64_t layer ,const float * x ,const int32_t * ids ,int64_t n_tok ,int64_t k , 259const int32_t * kind , std::string & err ,float * out ) { 260const bool direct = direct_mode ()&& out != nullptr ; 261struct Timer { 262double & acc ; 263 std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now (); 264 ~Timer () {acc += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); } 265 }timer {ms_launch }; 266launched_direct_ = false; 267launched_rows_ = 0 ; 268row_of_ .clear (); 269const int64_t n = n_tok * k ; 270if (n > CAP ) {err = "peer experts: window too large" ;return false; } 271Meta & m = * (Meta * )h_meta_ ; 272int groups = 0 ,rows = 0 ; 273// distinct experts in routing order; each one's entries become compact rows 274for (int64_t i = 0 ;i < n ;++ i ) { 275if (kind [i ]!= 2 )continue ; 276bool seen = false; 277for (int64_t j = 0 ;j < i ;++ j ) 278if (kind [j ]== 2 && ids [j ]== ids [i ]) {seen = true;break ; } 279if (seen )continue ; 280const int32_t slot = res_ [(size_t ) (layer * n_expert_ + ids [i ])]; 281if (slot < 0 ) {err = "peer experts: an entry was planned for the peer but is not resident" ;return false; } 282m .ptr [groups ]= (unsigned long long )cache_ .device_slot (slot ); 283m .start [groups ]= rows ; 284for (int64_t j = i ;j < n ;++ j ) 285if (kind [j ]== 2 && ids [j ]== ids [i ]) { 286m .dst [rows ]= rows ; 287m .tok [rows ]= (int32_t ) (j /k ); 288m .out_row [rows ]= (int32_t )j ; 289row_of_ .push_back ((int32_t )j ); 290++ rows ; 291 } 292++ groups ; 293++ experts_ ; 294 } 295if (groups == 0 )return true; 296m .start [groups ]= rows ; 297m .count [0 ]= groups ; 298m .count [1 ]= rows ; 299entries_ += rows ; 300launched_rows_ = rows ; 301// direct: x is the verifier's pinned (portable) doorbell row block - copied from where it is 302if (!direct ) std::memcpy (h_x_ ,x , (size_t ) (n_tok * H )* sizeof (float )); 303On on (device_ ); 304const cudaStream_t s = stream_ ; 305if (!ck (cudaMemcpyAsync (d_x_ ,direct ?x :h_x_ , (size_t ) (n_tok * H )* sizeof (float ),cudaMemcpyHostToDevice ,s ),"input" ,err )|| 306 !ck (cudaMemcpyAsync (d_meta_ ,h_meta_ ,sizeof (Meta ),cudaMemcpyHostToDevice ,s ),"plan" ,err )) 307return false; 308Meta * dm = (Meta * )d_meta_ ; 309const auto & lay = strata::kernels::cpu::expert_layout (); 310if (lay .native ) { 311const auto & f = lay .fmt [(size_t )layer ]; 312// APR: Hadamard-folded gate/up take H (s * x); d_x_ is this device's private copy, rotated in place 313if (f .had_gu ) strata::kernels::hadamard_rows (d_x_ ,d_x_ ,n_tok ,H ,f .had_block ,d_sx_ ,s ); 314 strata::kernels::quantize_q8_1_rows (d_x_ ,n_tok ,H ,d_q8_ ,s ); 315auto L = strata::kernels::native_expert_layout (f .gu_type ,f .d_type ,f .n_embd ,f .n_ff ); 316if (f .had_d ) {L .had_block = f .had_block ;L .d_signs = d_sh_ ; } 317 strata::kernels::native_expert_grouped (L ,dm -> ptr ,dm -> start ,dm -> count ,dm -> dst ,dm -> tok ,groups ,rows ,d_q8_ , 318d_scratch_ ,d_out_ ,s ); 319 }else { 320err = "peer experts: only native packs are supported" ; 321return false; 322 } 323if (direct ) {// the rows straight into the host `out` (zero-copy, coalesced float4 writes) 324try { 325 strata::kernels::scatter_rows_f32 (d_out_ ,out ,dm -> out_row ,rows ,H ,s ); 326 }catch (const std::exception & e ) {err = std::string ("peer experts: scatter: " )+ e .what ();return false; } 327launched_direct_ = true; 328return true; 329 } 330return ck (cudaMemcpyAsync (h_out_ ,d_out_ , (size_t )rows * H * sizeof (float ),cudaMemcpyDeviceToHost ,s ), 331"results" ,err ); 332} 333 334bool PeerExperts ::finish (float * out , std::string & err ) { 335if (launched_rows_ == 0 )return true; 336++ launches ; 337const auto t0 = std::chrono::steady_clock::now (); 338 { 339On on (device_ ); 340// spin on the stream (a blocking sync would sleep the pool thread and wake it late) 341cudaError_t e ; 342while ((e = cudaStreamQuery (stream_ ))== cudaErrorNotReady ) { 343 } 344if (!ck (e ,"finish" ,err ))return false; 345 } 346ms_wait += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); 347if (launched_direct_ ) {launched_rows_ = 0 ;return true; } 348for (size_t r = 0 ;r < row_of_ .size ();++ r ) 349 std::memcpy (out + (size_t )row_of_ [r ]* H ,h_out_ + r * H , (size_t )H * sizeof (float )); 350launched_rows_ = 0 ; 351return true; 352} 353 354bool PeerExperts ::adapt (const float * usage ,const int32_t * res0 ,int max_swaps , std::string & err ) { 355if (!pending_ .empty ()|| max_swaps <=0 )return true; 356const auto & lay = strata::kernels::cpu::expert_layout (); 357struct Swap {float gain ;int32_t layer ,in ,out ; }; 358 std::vector < Swap > swaps ; 359 std::vector < std::pair < float ,int32_t >> cand ,vict ; 360for (int64_t l = 0 ;l < n_layers_ ;++ l ) { 361cand .clear (); 362vict .clear (); 363const float * u = usage + l * n_expert_ ; 364const int32_t * r0 = res0 + l * n_expert_ ; 365const int32_t * r1 = res_ .data ()+ l * n_expert_ ; 366for (int32_t e = 0 ;e < (int32_t )n_expert_ ;++ e ) { 367if (r1 [e ] >=0 )vict .emplace_back (u [e ],e ); 368else if (r0 [e ]< 0 && u [e ] >=2.0f )cand .emplace_back (u [e ],e ); 369 } 370if (cand .empty ()|| vict .empty ())continue ; 371 std::sort (cand .begin (),cand .end (), [](auto & a ,auto & b ) {return a .first > b .first ; }); 372const size_t nc = std::min (cand .size (),vict .size ()); 373 std::partial_sort (vict .begin (),vict .begin ()+ (ptrdiff_t )nc ,vict .end (), 374 [](auto & a ,auto & b ) {return a .first < b .first ; }); 375for (size_t i = 0 ;i < nc ;++ i ) { 376if (cand [i ].first < vict [i ].first + 1.5f )break ; 377swaps .push_back ({cand [i ].first - vict [i ].first , (int32_t )l ,cand [i ].second ,vict [i ].second }); 378 } 379 } 380if (swaps .empty ())return true; 381 std::sort (swaps .begin (),swaps .end (), [](const Swap & a ,const Swap & b ) {return a .gain > b .gain ; }); 382if ((int )swaps .size ()> max_swaps )swaps .resize ((size_t )max_swaps ); 383const bool gated = gate_landed_ != nullptr ; 384if (gated ) {// the copies go in layer order and each layer's landing raises the gate's counter 385 std::stable_sort (swaps .begin (),swaps .end (), [](const Swap & a ,const Swap & b ) {return a .layer < b .layer ; }); 386gate_landed_ -> store (-1 , std::memory_order_release ); 387if (h_gate_ != nullptr )* h_gate_ = -1 ; 388gate_has_ -> assign ((size_t )n_layers_ ,0 ); 389* gate_last_ = -1 ; 390 } 391On on (device_ ); 392int32_t issued_layer = -1 ;// the layer whose copies are on the stream and not yet ticked 393auto tick = [& ](int32_t layer )-> bool { 394if ((h_gate_ != nullptr 395 ?cudaMemcpyAsync ((void * )h_gate_ ,d_gate_vals_ + layer ,4 ,cudaMemcpyDeviceToHost ,refill_ ) 396 :cudaLaunchHostFunc (refill_ , [](void * p ) { 397auto * t = (Tick * )p ; 398int32_t cur = t -> counter -> load (std::memory_order_relaxed ); 399while (cur < t -> layer && !t -> counter -> compare_exchange_weak (cur ,t -> layer , std::memory_order_release )) {} 400 },& ticks_ [(size_t )layer ]))== cudaSuccess ) 401return true; 402 (void )cudaGetLastError (); 403cudaStreamSynchronize (refill_ );// no callback: wait here, the gate opens at once 404gate_landed_ -> store ((int32_t )n_layers_ , std::memory_order_release ); 405return false; 406 }; 407for (const Swap & s :swaps ) { 408const size_t in = (size_t ) (s .layer * n_expert_ + s .in ),out = (size_t ) (s .layer * n_expert_ + s .out ); 409const int32_t slot = res_ [out ]; 410const uint8_t * b = src_ -> blob (s .layer ,s .in ); 411if (slot < 0 || b == nullptr )continue ; 412if (gated && issued_layer >=0 && issued_layer != s .layer )tick (issued_layer ); 413if (!ck (cudaMemcpyAsync (cache_ .device_slot (slot ),b , (size_t )lay .blob_bytes (s .layer ),cudaMemcpyHostToDevice , 414refill_ ),"refill" ,err )) 415return false; 416if (gated ) { 417 (* gate_has_ )[(size_t )s .layer ]= 1 ; 418* gate_last_ = std::max (* gate_last_ ,s .layer ); 419issued_layer = s .layer ; 420 } 421res_ [out ]= kNotResident ;// evicted now: the CPU computes it meanwhile 422pending_ .emplace_back ((int32_t )in ,slot ); 423++ swaps_ ; 424 } 425if (gated && issued_layer >=0 )tick (issued_layer ); 426if (!ck (cudaEventRecord (refill_ev_ ,refill_ ),"refill event" ,err ))return false; 427// #2188: hand the copies and their landing signals to the GPU now (WDDM batches a stream's work until a driver 428// call flushes it, and the verify window only spins on the pinned int; Linux submits at once: a no-op) 429if (gated && h_gate_ != nullptr && issued_layer >=0 ) (void )cudaStreamQuery (refill_ ); 430return true; 431} 432 433volatile int32_t * PeerExperts ::set_overlap_gate (std::atomic < int32_t >* landed , std::vector < uint8_t >* has ,int32_t * last , 434bool copy_signal ) { 435gate_landed_ = landed ; 436gate_has_ = has ; 437gate_last_ = last ; 438ticks_ .resize ((size_t )n_layers_ ); 439for (int64_t l = 0 ;l < n_layers_ ;++ l )ticks_ [(size_t )l ]= {landed , (int32_t )l }; 440if (copy_signal && h_gate_ == nullptr ) { 441On on (device_ ); 442 std::vector < int32_t > iota ((size_t )n_layers_ ); 443for (size_t i = 0 ;i < iota .size ();++ i )iota [i ]= (int32_t )i ; 444int32_t * vals = nullptr ; 445void * hp = nullptr ; 446if (cudaMalloc ((void ** )& vals ,iota .size ()* 4 )== cudaSuccess && 447cudaMemcpy (vals ,iota .data (),iota .size ()* 4 ,cudaMemcpyHostToDevice )== cudaSuccess && 448cudaHostAlloc (& hp ,64 ,cudaHostAllocPortable )== cudaSuccess ) { 449* (volatile int32_t * )hp = -1 ; 450d_gate_vals_ = vals ; 451h_gate_ = (volatile int32_t * )hp ; 452 }else {// host functions then 453 (void )cudaGetLastError (); 454if (vals )cudaFree (vals ); 455 } 456 } 457return h_gate_ ; 458} 459 460void PeerExperts ::flip_pending () { 461for (const auto & [i ,slot ] :pending_ )res_ [(size_t )i ]= slot ; 462} 463 464void PeerExperts ::apply_pending (bool wait ) { 465if (pending_ .empty ())return ; 466 { 467On on (device_ ); 468if (wait )cudaEventSynchronize (refill_ev_ ); 469else if (cudaEventQuery (refill_ev_ )!= cudaSuccess )return ; 470 } 471for (const auto & [i ,slot ] :pending_ )res_ [(size_t )i ]= slot ; 472pending_ .clear (); 473} 474 475}// namespace strata::core