okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4dad59ab3
main
1#include "strata/core/remote_experts.hpp" 2#include "strata/core/device.hpp" // primary_device() (STRATA_PRIMARY_DEVICE) 3#include "strata/core/remote_expert_opt.hpp" 4 5#include "strata/kernels/cpu/expert_layout.hpp" 6#include "strata/kernels/cpu/hadamard.hpp" 7#include "strata/kernels/iq_kernels.hpp" 8#include "strata/kernels/quantize_act.hpp" 9#include "strata/kernels/s2_expert_grouped.hpp" 10#include "strata/kernels/window_limits.hpp" 11 12#include <algorithm> 13#include <chrono> 14#include <cstdio> 15#include <cstdlib> 16#include <cstring> 17 18namespace strata::core { 19namespace { 20constexpr int64_t H = strata::kernels::cpu::H ; 21constexpr int64_t FF = strata::kernels::cpu::FF ; 22constexpr int64_t CAP = strata::kernels::kWindowMaxT * 10 ;// a window's rows x top-10 23 24// Small enough to copy as one pinned buffer per layer. The kernels read the 25// individual arrays through pointers into the same device allocation. 26struct RemoteMeta { 27unsigned long long ptr [CAP ]; 28int32_t start [CAP + 1 ]; 29int32_t dst [CAP ]; 30int32_t tok [CAP ]; 31int32_t count ; 32}; 33 34struct DeviceScope { 35int previous = -1 ; 36bool ok = false; 37cudaError_t status = cudaSuccess ; 38const char * failed_step = nullptr ; 39explicit DeviceScope (int device ) { 40status = cudaGetDevice (& previous ); 41if (status != cudaSuccess ) { 42previous = -1 ; 43failed_step = "cudaGetDevice" ; 44return ; 45 } 46status = cudaSetDevice (device ); 47if (status != cudaSuccess ) { 48failed_step = "cudaSetDevice" ; 49return ; 50 } 51ok = true; 52 } 53 ~DeviceScope () {if (previous >=0 )cudaSetDevice (previous ); } 54 std::string error (int device )const { 55return std::string ("CUDA" )+ std::to_string (device )+ " experts: " + 56 (failed_step ?failed_step :"device switch" )+ 57"(" + std::to_string (device )+ ") failed: " + cudaGetErrorString (status )+ 58" (CUDA error " + std::to_string ((int )status )+ ")" ; 59 } 60}; 61 62bool check (cudaError_t result ,const char * what , std::string & err ,int device ) { 63if (result == cudaSuccess )return true; 64err = "CUDA" + std::to_string (device )+ " experts: " + what + ": " + cudaGetErrorString (result ); 65return false; 66} 67}// namespace 68 69RemoteExperts ::~RemoteExperts () {close (); } 70 71bool RemoteExperts ::preflight (int device ,double & free_gib , std::string & err ) { 72int count = 0 ; 73if (!check (cudaGetDeviceCount (& count ),"cudaGetDeviceCount" ,err ,device ))return false; 74if (device < 0 || device >=count ) { 75err = "CUDA" + std::to_string (device )+ " experts: CUDA device is not visible" ; 76return false; 77 } 78if (device == primary_device ()) {// the primary may be any visible ordinal; the helper cannot be it 79err = "CUDA" + std::to_string (device )+ " experts: the helper cannot be the primary device " 80"(STRATA_PRIMARY_DEVICE)" ; 81return false; 82 } 83// The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up 84// costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows). Only possible 85// before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default. 86#if !defined(STRATA_USE_HIP )&& !defined(STRATA_GPU_METAL ) 87const char * spin = std::getenv ("STRATA_REMOTE_SPIN" ); 88if (!(spin && spin [0 ]== '0' ))cudaInitDevice (device ,cudaDeviceScheduleSpin |cudaDeviceMapHost ,0 ); 89cudaGetLastError (); 90#endif 91// HIP has no cudaInitDevice equivalent; retain its default scheduling policy. 92DeviceScope scope (device ); 93if (!scope .ok ) {err = scope .error (device );return false; } 94size_t free_bytes = 0 ,total_bytes = 0 ; 95if (!check (cudaMemGetInfo (& free_bytes ,& total_bytes ),"preflight free memory" ,err ,device ))return false; 96free_gib = (double )free_bytes /1073741824.0 ; 97return true; 98} 99 100void RemoteExperts ::close () { 101if (device_ < 0 )return ; 102DeviceScope scope (device_ ); 103if (scope .ok ) { 104if (stream_ )cudaStreamSynchronize (stream_ ); 105if (read_stream_ )cudaStreamSynchronize (read_stream_ ); 106cache_ .close (); 107if (d_x_ )cudaFree (d_x_ ); 108if (d_out_ )cudaFree (d_out_ ); 109if (d_q8_ )cudaFree (d_q8_ ); 110if (d_scales_ )cudaFree (d_scales_ ); 111if (d_xr_ )cudaFree (d_xr_ ); 112if (d_scratch_ )cudaFree (d_scratch_ ); 113if (d_meta_ )cudaFree (d_meta_ ); 114if (h_x_ )cudaFreeHost (h_x_ ); 115if (h_out_ )cudaFreeHost (h_out_ ); 116if (h_meta_ )cudaFreeHost (h_meta_ ); 117if (stream_ )cudaStreamDestroy (stream_ ); 118if (read_stream_ )cudaStreamDestroy (read_stream_ ); 119 } 120device_ = -1 ; 121stream_ = nullptr ; 122read_stream_ = nullptr ; 123h_x_ = h_out_ = d_x_ = d_out_ = nullptr ; 124h_meta_ = d_meta_ = nullptr ; 125d_q8_ = nullptr ; 126d_scales_ = nullptr ; 127d_xr_ = nullptr ; 128d_sx_ = d_sh_ = nullptr ; 129d_scratch_ = nullptr ; 130d_start_ = d_dst_ = d_tok_ = d_count_ = nullptr ; 131d_ptr_ = nullptr ; 132original_row_ .clear (); 133layers_present_ .clear (); 134} 135 136bool RemoteExperts ::open (int device ,int slots ,int64_t layers ,int64_t experts , 137const std::vector < std::pair < int32_t ,int32_t >>& ranked , 138const ExpertCache & primary ,ExpertSource & source , 139 std::vector < uint8_t >& claimed , std::string & err ,bool auto_size ) { 140close (); 141int count = 0 ; 142if (!check (cudaGetDeviceCount (& count ),"cudaGetDeviceCount" ,err ,device ))return false; 143if (device < 0 || device >=count || slots <=0 || ranked .empty ()|| 144layers <=0 || experts <=0 || claimed .size ()!= (size_t )layers * (size_t )experts || 145device == primary_device ()) {// the helper cannot be the primary device (any visible ordinal) 146err = "CUDA" + std::to_string (device )+ " experts: need the device, ranked experts and positive slot count" ; 147return false; 148 } 149DeviceScope scope (device ); 150if (!scope .ok ) {err = scope .error (device );return false; } 151device_ = device ; 152n_expert_ = experts ; 153const auto & lay = strata::kernels::cpu::expert_layout (); 154size_t free_bytes = 0 ,total_bytes = 0 ; 155if (!check (cudaMemGetInfo (& free_bytes ,& total_bytes ),"free memory" ,err ,device )) {close ();return false; } 156uint64_t needed = 0 ; 157 std::vector < std::pair < int32_t ,int32_t >> selected ; 158selected .reserve ((size_t ) std::min < int64_t > (slots ,layers * experts )); 159 std::vector < uint8_t > picked (claimed .size (),0 ); 160for (const auto & pair :ranked ) { 161if (pair .first < 0 || pair .first >=layers || pair .second < 0 || pair .second >=experts )continue ; 162const size_t index = (size_t )pair .first * (size_t )experts + (size_t )pair .second ; 163if (primary .slot_of (pair .first ,pair .second )< 0 && !claimed [index ]&& !picked [index ]) { 164const uint64_t bytes = lay .native ? (lay .blob_bytes (pair .first )+ 255 ) /256 * 256 :lay .max_blob ; 165if (auto_size && needed + bytes + (512ull <<20 )> free_bytes )break ; 166selected .push_back (pair ); 167needed += bytes ; 168picked [index ]= 1 ; 169if ((int )selected .size () >=slots )break ; 170 } 171 } 172if (selected .empty ()) { 173err = "CUDA" + std::to_string (device )+ (auto_size ?" experts: no unclaimed expert fits with 512 MiB free" 174 :" experts: no unclaimed experts remain" ); 175close ();return false; 176 } 177 std::vector < int64_t > sizes ; 178if (lay .native ) { 179sizes .reserve (selected .size ()); 180for (const auto & pair :selected )sizes .push_back ((int64_t )lay .blob_bytes (pair .first )); 181 } 182// Leave room for the CUDA context, staging and later driver allocations, especially under WDDM. 183if (needed + (512ull <<20 )> free_bytes ) { 184err = "CUDA" + std::to_string (device )+ " experts: slots leave less than 512 MiB free; reduce --expert-cache-device" + std::to_string (device ); 185close ();return false; 186 } 187const bool cache_ok = lay .native ?cache_ .open_sized (sizes ,layers ,experts ,err ) 188 :cache_ .open ((int64_t )selected .size (),layers ,experts , 189 (int64_t )lay .max_blob ,err ); 190if (!cache_ok ) {err = "CUDA" + std::to_string (device )+ " experts: " + err ;close ();return false; } 191for (const auto & pair :selected ) { 192const int32_t slot = cache_ .admit (pair .first ,pair .second ); 193const uint8_t * blob = source .blob (pair .first ,pair .second ); 194if (slot < 0 || !blob || !cache_ .fill_slot_blocking (slot ,blob ,err , (int64_t )lay .blob_bytes (pair .first ))) { 195err = "CUDA" + std::to_string (device )+ " experts: " + 196 (err .empty () ?"cache fill failed" :err ); 197close ();return false; 198 } 199 } 200const auto & first = selected .front (); 201if (!cache_ .verify_slot (cache_ .slot_of (first .first ,first .second ),source .blob (first .first ,first .second ), 202err , (int64_t )lay .blob_bytes (first .first ))) { 203err = "CUDA" + std::to_string (device )+ " experts: " + err ; 204close ();return false; 205 } 206 207const size_t scratch = std::max < size_t > ( 208 (size_t ) strata::kernels::moe_hit_grouped_scratch_bytes (CAP ,H ,FF ), 209 strata::kernels::native_expert_scratch_bytes (CAP ,FF )); 210const size_t meta_bytes = sizeof (RemoteMeta )+ (remote_opt_ ?remote_opt_ -> metadata_bytes () :0 ); 211const bool allocated = 212check (cudaStreamCreateWithFlags (& stream_ ,cudaStreamNonBlocking ),"stream" ,err ,device )&& 213check (cudaHostAlloc ((void ** )& h_x_ , (size_t )CAP * H * sizeof (float ),cudaHostAllocPortable |cudaHostAllocMapped ),"input staging" ,err ,device )&& 214check (cudaHostAlloc ((void ** )& h_out_ , (size_t )CAP * H * sizeof (float ),cudaHostAllocPortable |cudaHostAllocMapped ),"result staging" ,err ,device )&& 215check (cudaHostAlloc (& h_meta_ ,meta_bytes ,cudaHostAllocPortable ),"metadata staging" ,err ,device )&& 216check (cudaMalloc ((void ** )& d_x_ , (size_t )CAP * H * sizeof (float )),"input" ,err ,device )&& 217check (cudaMalloc ((void ** )& d_out_ , (size_t )CAP * H * sizeof (float )),"result" ,err ,device )&& 218check (cudaMalloc ((void ** )& d_q8_ , (size_t )CAP * (H /32 )* 36 ),"activation" ,err ,device )&& 219check (cudaMalloc ((void ** )& d_scales_ , (size_t )CAP * (H /32 )* sizeof (float )),"activation scales" ,err ,device )&& 220check (cudaMalloc (& d_scratch_ ,scratch ),"scratch" ,err ,device )&& 221check (cudaMalloc (& d_meta_ ,meta_bytes ),"group metadata" ,err ,device )&& 222 (!strata::kernels::cpu::hadamard_spec ().any ()|| 223check (cudaMalloc ((void ** )& d_xr_ , (size_t )CAP * H * sizeof (float )),"rotated input" ,err ,device )); 224if (!allocated ) {close ();return false; } 225if (!check (cudaStreamCreateWithFlags (& read_stream_ ,cudaStreamNonBlocking ),"cache read stream" ,err ,device )) { 226close (); 227return false; 228 } 229if (strata::kernels::cpu::hadamard_spec ().any ()) {// APR: this device's copies of the sign vectors 230d_sx_ = strata::kernels::hadamard_device_signs (strata::kernels::cpu::hadamard_signs ((int )H ), (int )H ); 231d_sh_ = strata::kernels::hadamard_device_signs (strata::kernels::cpu::hadamard_signs ((int )FF ), (int )FF ); 232 } 233// Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers 234// directly - two copies fewer per layer, each of which is a PCIe round trip. STRATA_REMOTE_ZEROCOPY=0 copies. 235const char * zc = std::getenv ("STRATA_REMOTE_ZEROCOPY" ); 236zero_copy_ = !(zc && zc [0 ]== '0' )&& 237cudaHostGetDevicePointer ((void ** )& z_x_ ,h_x_ ,0 )== cudaSuccess && 238cudaHostGetDevicePointer ((void ** )& z_out_ ,h_out_ ,0 )== cudaSuccess ; 239cudaGetLastError (); 240auto * meta = (RemoteMeta * )d_meta_ ; 241d_ptr_ = meta -> ptr ; 242d_start_ = meta -> start ; 243d_dst_ = meta -> dst ; 244d_tok_ = meta -> tok ; 245d_count_ = & meta -> count ; 246owned_ .resize (CAP ); 247layers_present_ .assign ((size_t )layers ,0 ); 248group_of_ .resize (CAP ); 249group_id_ .reserve (CAP ); 250ptr_ .reserve (CAP ); 251start_ .reserve (CAP + 1 ); 252dst_ .reserve (CAP ); 253tok_ .reserve (CAP ); 254original_row_ .reserve (CAP ); 255computed_ = 0 ; 256launched_layers_ = 0 ; 257returned_bytes_ = full_row_bytes_ = 0 ; 258for (const auto & pair :selected ) { 259layers_present_ [(size_t )pair .first ]= 1 ; 260claimed [(size_t )pair .first * (size_t )experts + (size_t )pair .second ]= 1 ; 261 } 262return true; 263} 264 265bool RemoteExperts ::begin (int64_t layer ,const float * x ,const int32_t * ids ,int64_t n_tok , 266int64_t k ,const int32_t * kind ,const int32_t * primary_res , 267 std::string & err ) { 268// cumulative host time in here (staging and launches), reported per request by the driver 269struct Timer {double & acc ; std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now (); 270 ~Timer () {acc += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); } }timer {ms_begin_ }; 271const int64_t n = n_tok * k ; 272if (n <=0 || n > CAP || n_tok > strata::kernels::kWindowMaxT || k != (int ) strata::core::kCompiledGeometry .n_expert_used || layer < 0 || 273 (size_t )layer >=layers_present_ .size ()|| device_ < 0 ) { 274err = "CUDA" + std::to_string (device_ )+ " experts: invalid layer, routing width or window size" ; 275return false; 276 } 277 std::fill (owned_ .begin (),owned_ .begin ()+ n ,0 ); 278group_id_ .clear ();ptr_ .clear ();start_ .clear ();dst_ .clear ();tok_ .clear ();original_row_ .clear (); 279if (!layers_present_ [(size_t )layer ])return true; 280 std::fill (group_of_ .begin (),group_of_ .begin ()+ n ,-1 ); 281for (int64_t i = 0 ;i < n ;++ i ) { 282const int32_t e = ids [i ]; 283if ((kind && kind [i ]!= -1 )|| e < 0 || e >=n_expert_ || 284 (primary_res && primary_res [(size_t )layer * (size_t )n_expert_ + (size_t )e ] >=0 ))continue ; 285const int32_t slot = cache_ .slot_of (layer ,e ); 286if (slot < 0 )continue ; 287owned_ [(size_t )i ]= 1 ; 288int32_t group = -1 ; 289for (size_t g = 0 ;g < group_id_ .size ();++ g ) 290if (group_id_ [g ]== e ) {group = (int32_t )g ;break ; } 291if (group < 0 ) { 292group = (int32_t )group_id_ .size (); 293group_id_ .push_back (e ); 294ptr_ .push_back ((unsigned long long )cache_ .device_slot (slot )); 295 } 296group_of_ [(size_t )i ]= group ; 297++ computed_ ; 298 } 299if (group_id_ .empty ())return true; 300for (size_t g = 0 ;g < group_id_ .size ();++ g ) { 301start_ .push_back ((int32_t )dst_ .size ()); 302for (int64_t i = 0 ;i < n ;++ i )if (group_of_ [(size_t )i ]== (int32_t )g ) { 303// The grouped kernels read the activation from `tok`, so their 304// output row can instead be packed densely for the USB4 return. 305original_row_ .push_back ((int32_t )i ); 306dst_ .push_back ((int32_t )dst_ .size ()); 307tok_ .push_back ((int32_t ) (i /k )); 308 } 309 } 310start_ .push_back ((int32_t )dst_ .size ()); 311// Private pinned buffers survive until this GPU has consumed them. The CPU 312// pool can write other output rows without a cross-device race. 313 std::memcpy (h_x_ ,x , (size_t )n_tok * H * sizeof (float )); 314auto * meta = (RemoteMeta * )h_meta_ ; 315 std::memcpy (meta -> ptr ,ptr_ .data (),ptr_ .size ()* sizeof (ptr_ [0 ])); 316 std::memcpy (meta -> start ,start_ .data (),start_ .size ()* sizeof (start_ [0 ])); 317 std::memcpy (meta -> dst ,dst_ .data (),dst_ .size ()* sizeof (dst_ [0 ])); 318 std::memcpy (meta -> tok ,tok_ .data (),tok_ .size ()* sizeof (tok_ [0 ])); 319meta -> count = (int32_t )group_id_ .size (); 320const bool reduce = remote_opt_ && remote_opt_ -> active (); 321if (reduce )remote_opt_ -> prepare (* this ,meta + 1 ); 322DeviceScope scope (device_ ); 323if (!scope .ok ) {err = scope .error (device_ );return false; } 324groups_ = (int32_t )group_id_ .size (); 325const cudaStream_t s = stream_ ; 326const bool staged = 327 (zero_copy_ || check (cudaMemcpyAsync (d_x_ ,h_x_ , (size_t )n_tok * H * sizeof (float ),cudaMemcpyHostToDevice ,s ),"copy input" ,err ,device_ ))&& 328check (cudaMemcpyAsync (d_meta_ ,h_meta_ ,sizeof (RemoteMeta )+ (reduce ?remote_opt_ -> metadata_bytes () :0 ), 329cudaMemcpyHostToDevice ,s ),"copy group metadata" ,err ,device_ ); 330if (!staged )return false; 331const auto & lay = strata::kernels::cpu::expert_layout (); 332if (lay .native ) { 333const auto & fmt = lay .fmt [(size_t )layer ]; 334const float * xe = zero_copy_ ?z_x_ :d_x_ ; 335if (fmt .had_gu ) {// APR: Hadamard-folded gate/up take H (s * x) 336 strata::kernels::hadamard_rows (xe ,d_xr_ ,n_tok ,H ,fmt .had_block ,d_sx_ ,s ); 337xe = d_xr_ ; 338 } 339 strata::kernels::quantize_q8_1_rows (xe ,n_tok ,H ,d_q8_ ,s ); 340auto L = strata::kernels::native_expert_layout (fmt .gu_type ,fmt .d_type ,fmt .n_embd ,fmt .n_ff ); 341if (fmt .had_d ) {L .had_block = fmt .had_block ;L .d_signs = d_sh_ ; } 342 strata::kernels::native_expert_grouped (L ,d_ptr_ ,d_start_ ,d_count_ ,d_dst_ ,d_tok_ , 343groups_ , (int64_t )dst_ .size (),d_q8_ ,d_scratch_ ,zero_copy_ && !reduce ?z_out_ :d_out_ ,s ); 344 }else { 345 strata::kernels::quantize_q8_0_scaled (zero_copy_ ?z_x_ :d_x_ ,d_q8_ ,d_scales_ ,n_tok * H ,s ); 346 strata::kernels::moe_grouped_s2_window (d_ptr_ ,d_start_ ,d_count_ ,d_dst_ ,d_tok_ , 347groups_ , (int64_t )dst_ .size (),d_q8_ ,d_scales_ ,d_scratch_ ,zero_copy_ && !reduce ?z_out_ :d_out_ ,s , 348 (int )n_tok ); 349 } 350const uint64_t compact_bytes = (uint64_t ) (reduce ?n_tok :dst_ .size ())* H * sizeof (float ); 351if (reduce ) { 352if (!remote_opt_ -> reduce (* this , (RemoteMeta * )d_meta_ + 1 ,err ))return false; 353 }else if (!zero_copy_ && !check (cudaMemcpyAsync (h_out_ ,d_out_ , (size_t )compact_bytes ,cudaMemcpyDeviceToHost ,s ), 354"copy results" ,err ,device_ ))return false; 355++ launched_layers_ ; 356returned_bytes_ += compact_bytes ; 357full_row_bytes_ += (uint64_t )n * H * sizeof (float ); 358return true; 359} 360 361bool RemoteExperts ::finish (float * out , std::string & err ) { 362if (group_id_ .empty ())return true; 363DeviceScope scope (device_ ); 364if (!scope .ok ) {err = scope .error (device_ );return false; } 365const auto w0 = std::chrono::steady_clock::now (); 366// Spin on the stream like PeerExperts::finish instead of the blocking sync: the layer waits for this helper 367// on the CPU pool's critical path, and a blocking sync's wake-up costs more than the helper's small batch 368// takes - on HIP especially, where the CUDA branch's cudaInitDevice(ScheduleSpin) does not exist and the 369// device keeps its default policy. STRATA_REMOTE_SPIN=0 keeps the blocking sync (the same switch the CUDA 370// branch reads). 371#if defined(STRATA_USE_HIP )// HIP only: the CUDA branch's cudaInitDevice(ScheduleSpin) already makes the sync spin 372static const bool spin = [] { 373const char * v = std::getenv ("STRATA_REMOTE_SPIN" ); 374return !(v != nullptr && v [0 ]== '0' ); 375 }(); 376if (spin ) { 377cudaError_t e ; 378while ((e = cudaStreamQuery (stream_ ))== cudaErrorNotReady ) { 379 } 380if (!check (e ,"finish" ,err ,device_ ))return false; 381 }else if (!check (cudaStreamSynchronize (stream_ ),"finish" ,err ,device_ )) { 382return false; 383 } 384#else 385if (!check (cudaStreamSynchronize (stream_ ),"finish" ,err ,device_ ))return false; 386#endif 387ms_wait_ += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- w0 ).count (); 388if (remote_opt_ && remote_opt_ -> active ()) {remote_opt_ -> accumulate (* this );return true; } 389for (size_t i = 0 ;i < original_row_ .size ();++ i ) 390 std::memcpy (out + (size_t )original_row_ [i ]* H ,h_out_ + i * H , (size_t )H * sizeof (float )); 391return true; 392} 393 394bool RemoteExperts ::copy_cached_blobs (const int32_t * layers ,const int32_t * experts ,uint8_t * const * dst , 395size_t n ,uint8_t * hit , std::string & err ) { 396 std::fill (hit ,hit + n ,0 ); 397if (device_ < 0 || read_stream_ == nullptr || n == 0 )return true; 398const auto & lay = strata::kernels::cpu::expert_layout (); 399DeviceScope scope (device_ ); 400if (!scope .ok ) {err = scope .error (device_ );return false; } 401 std::lock_guard < std::mutex > lock (read_mu_ ); 402bool queued = false; 403for (size_t i = 0 ;i < n ;++ i ) { 404if (dst [i ]== nullptr )continue ; 405const int32_t slot = cache_ .slot_of (layers [i ],experts [i ]); 406if (slot < 0 )continue ; 407const size_t bytes = (size_t )lay .blob_bytes (layers [i ]); 408if (!check (cudaMemcpyAsync (dst [i ],cache_ .device_slot (slot ),bytes ,cudaMemcpyDeviceToHost ,read_stream_ ), 409"cache read" ,err ,device_ )) { 410// Nothing may still be writing a caller's buffer when this returns. If the drain succeeds, the 411// hits queued before the failure are complete and the caller may keep them; if it does not, 412// forget every hit and let the caller refill all of them from its fallback. 413if (cudaStreamSynchronize (read_stream_ )!= cudaSuccess ) std::fill (hit ,hit + n ,0 ); 414return false; 415 } 416hit [i ]= 1 ; 417queued = true; 418 } 419if (queued && !check (cudaStreamSynchronize (read_stream_ ),"cache read wait" ,err ,device_ )) { 420 std::fill (hit ,hit + n ,0 );// a failed wait means no copied buffer may be trusted 421return false; 422 } 423return true; 424} 425 426bool RemotePrefillSource ::copy_blob (int64_t layer ,int64_t expert ,uint8_t * dst ) { 427if (dst != nullptr && from_helper (layer ,expert )) { 428const int32_t l = (int32_t )layer ,e = (int32_t )expert ; 429uint8_t * d = dst ; 430 std::string err ; 431for (RemoteExperts * h :helpers_ ) { 432uint8_t got = 0 ; 433const bool ok = h -> copy_cached_blobs (& l ,& e ,& d ,1 ,& got ,err ); 434if (got ) { 435helper_blobs_ .fetch_add (1 , std::memory_order_relaxed ); 436helper_bytes_ .fetch_add (strata::kernels::cpu::expert_layout ().blob_bytes (layer ), 437 std::memory_order_relaxed ); 438return true; 439 } 440if (!ok )break ; 441 } 442warn (err ); 443 } 444return fallback_ .copy_blob (layer ,expert ,dst ); 445} 446 447bool RemotePrefillSource ::copy_blobs (const int32_t * layers ,const int32_t * experts ,uint8_t * const * dst ,size_t n ) { 448if (helpers_ .empty ()|| n == 0 )return fallback_ .copy_blobs (layers ,experts ,dst ,n ); 449 thread_local std::vector < int32_t > hl ,he ; 450 thread_local std::vector < uint8_t *> hd ; 451 thread_local std::vector < size_t > idx ; 452 thread_local std::vector < uint8_t > got ; 453 thread_local std::vector < uint8_t > served ; 454 thread_local std::vector < int32_t > ml ,me ; 455 thread_local std::vector < uint8_t *> md ; 456 thread_local std::vector < int > which ; 457which .assign (n ,-1 ); 458served .assign (n ,0 ); 459for (size_t i = 0 ;i < n ;++ i ) { 460if (dst [i ]== nullptr )continue ; 461for (size_t k = 0 ;k < helpers_ .size ();++ k ) 462if (helpers_ [k ]-> holds (layers [i ],experts [i ])) {which [i ]= (int )k ;break ; } 463 } 464// One stream batch per helper, so several hits pay one wait; the misses go to the file source in one 465// call, which keeps its own batched-read merging for them. 466uint64_t blobs = 0 ,bytes = 0 ; 467const auto & lay = strata::kernels::cpu::expert_layout (); 468for (size_t k = 0 ;k < helpers_ .size ();++ k ) { 469hl .clear ();he .clear ();hd .clear ();idx .clear (); 470for (size_t i = 0 ;i < n ;++ i ) 471if (which [i ]== (int )k ) { 472hl .push_back (layers [i ]);he .push_back (experts [i ]);hd .push_back (dst [i ]);idx .push_back (i ); 473 } 474if (hl .empty ())continue ; 475got .assign (hl .size (),0 ); 476 std::string err ; 477if (!helpers_ [k ]-> copy_cached_blobs (hl .data (),he .data (),hd .data (),hl .size (),got .data (),err ))warn (err ); 478for (size_t j = 0 ;j < got .size ();++ j ) 479if (got [j ]) { 480served [idx [j ]]= 1 ; 481++ blobs ; 482bytes += lay .blob_bytes (hl [j ]); 483 } 484 } 485if (blobs != 0 ) { 486helper_blobs_ .fetch_add (blobs , std::memory_order_relaxed ); 487helper_bytes_ .fetch_add (bytes , std::memory_order_relaxed ); 488 } 489ml .clear ();me .clear ();md .clear (); 490for (size_t i = 0 ;i < n ;++ i ) 491if (!served [i ]) {ml .push_back (layers [i ]);me .push_back (experts [i ]);md .push_back (dst [i ]); } 492if (ml .empty ())return true; 493return fallback_ .copy_blobs (ml .data (),me .data (),md .data (),ml .size ()); 494} 495 496void RemotePrefillSource ::warn (const std::string & err ) { 497if (err .empty ()|| warned_ .exchange (true))return ; 498 std::fprintf (stderr ,"prefill: a helper cache read failed (%s); the file source fills that blob instead\n" , 499err .c_str ()); 500} 501}// namespace strata::core