okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
db137d917
main
1#include <sycl/sycl.hpp> 2#include <dpct/dpct.hpp> 3#include "strata/core/remote_experts.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 11#include <algorithm> 12#include <chrono> 13#include <cstdlib> 14#include <cstring> 15 16namespace strata::core { 17namespace { 18constexpr int64_t H = strata::kernels::cpu::H ; 19constexpr int64_t FF = strata::kernels::cpu::FF ; 20constexpr int64_t CAP = strata::kernels::cpu::MAXT * 10 ; 21 22// Small enough to copy as one pinned buffer per layer. The kernels read the 23// individual arrays through pointers into the same device allocation. 24struct RemoteMeta { 25unsigned long long ptr [CAP ]; 26int32_t start [CAP + 1 ]; 27int32_t dst [CAP ]; 28int32_t tok [CAP ]; 29int32_t count ; 30}; 31 32struct DeviceScope { 33int previous = -1 ; 34bool ok = false; 35 dpct::err0 status = 0 ; 36const char * failed_step = nullptr ; 37explicit DeviceScope (int device ) { 38status = DPCT_CHECK_ERROR (previous = dpct::get_current_device_id ()); 39if (status != 0 ) { 40previous = -1 ; 41failed_step = "cudaGetDevice" ; 42return ; 43 } 44/* 45DPCT1093: The "device" device may be not the one intended for use. 46Adjust the selected device if needed. 47*/ 48status = DPCT_CHECK_ERROR (dpct::select_device (device )); 49if (status != 0 ) { 50failed_step = "cudaSetDevice" ; 51return ; 52 } 53ok = true; 54 } 55/* 56DPCT1093: The "previous" device may be not the one intended for use. 57Adjust the selected device if needed. 58*/ 59 ~DeviceScope () {if (previous >=0 ) dpct::select_device (previous ); } 60 std::string error (int device )const { 61return std::string ("CUDA" )+ std::to_string (device )+ 62" experts: " + (failed_step ?failed_step :"device switch" )+ 63/* 64DPCT1009: SYCL reports errors using exceptions and does not 65use error codes. Please replace the "get_error_string_dummy(...)" 66with a real error-handling function. 67*/ 68"(" + 69 std::to_string (device )+ 70") failed: " + dpct::get_error_string_dummy (status )+ 71" (CUDA error " + std::to_string ((int )status )+ ")" ; 72 } 73}; 74 75bool check (dpct::err0 result ,const char * what , std::string & err ,int device ) { 76if (result == 0 )return true; 77/* 78DPCT1009: SYCL reports errors using exceptions and does not use error 79codes. Please replace the "get_error_string_dummy(...)" with a real 80error-handling function. 81*/ 82err = "CUDA" + std::to_string (device )+ " experts: " + what + ": " + 83 dpct::get_error_string_dummy (result ); 84return false; 85} 86}// namespace 87 88RemoteExperts ::~RemoteExperts () {close (); } 89 90bool RemoteExperts ::preflight (int device ,double & free_gib , 91 std::string & err )try { 92int count = 0 ; 93if (!check (DPCT_CHECK_ERROR (count = dpct::device_count ()), 94"cudaGetDeviceCount" ,err ,device ))return false; 95if (device < 1 || device >=count ) { 96err = "CUDA" + std::to_string (device )+ " experts: CUDA device is not visible" ; 97return false; 98 } 99// The layer waits for this GPU on the CPU pool's critical path: spin instead of sleeping, whose wake-up 100// costs more than a small expert batch takes (measured: ~0.3 ms per round trip on Windows). Only possible 101// before the device's context exists, so first thing; STRATA_REMOTE_SPIN=0 keeps the driver's default. 102const char * spin = std::getenv ("STRATA_REMOTE_SPIN" ); 103/* 104DPCT1007: Migration of cudaInitDevice is not supported. 105*/ 106 (void )spin ;// SYCL: no cudaInitDevice scheduling flags; the runtime picks its own wait policy 107/* 108DPCT1026: The call to cudaGetLastError was removed because this 109functionality is redundant in SYCL. 110*/ 111DeviceScope scope (device ); 112if (!scope .ok ) {err = scope .error (device );return false; } 113size_t free_bytes = 0 ,total_bytes = 0 ; 114/* 115DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for 116device information which may not be supported by all compilers or runtimes. 117You may need to adjust the code. 118*/ 119if (!check (DPCT_CHECK_ERROR (dpct::get_current_device ().get_memory_info ( 120free_bytes ,total_bytes )), 121"preflight free memory" ,err ,device ))return false; 122free_gib = (double )free_bytes /1073741824.0 ; 123return true; 124} 125catch (sycl::exception const & exc ) { 126 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 127 <<", line:" <<__LINE__ << std::endl ; 128 std::exit (1 ); 129} 130 131void RemoteExperts ::close () { 132if (device_ < 0 )return ; 133DeviceScope scope (device_ ); 134if (scope .ok ) { 135if (stream_ )stream_ -> wait (); 136cache_ .close (); 137if (d_x_ ) sycl::free (d_x_ , dpct::get_in_order_queue ()); 138if (d_out_ ) sycl::free (d_out_ , dpct::get_in_order_queue ()); 139if (d_q8_ ) sycl::free (d_q8_ , dpct::get_in_order_queue ()); 140if (d_scales_ ) sycl::free (d_scales_ , dpct::get_in_order_queue ()); 141if (d_scratch_ ) sycl::free (d_scratch_ , dpct::get_in_order_queue ()); 142if (d_meta_ ) sycl::free (d_meta_ , dpct::get_in_order_queue ()); 143if (h_x_ ) sycl::free (h_x_ , dpct::get_in_order_queue ()); 144if (h_out_ ) sycl::free (h_out_ , dpct::get_in_order_queue ()); 145if (h_meta_ ) sycl::free (h_meta_ , dpct::get_in_order_queue ()); 146if (stream_ ) dpct::get_current_device ().destroy_queue (stream_ ); 147 } 148device_ = -1 ; 149stream_ = & dpct::get_in_order_queue (); 150h_x_ = h_out_ = d_x_ = d_out_ = nullptr ; 151h_meta_ = d_meta_ = nullptr ; 152d_q8_ = nullptr ; 153d_scales_ = nullptr ; 154d_scratch_ = nullptr ; 155d_start_ = d_dst_ = d_tok_ = d_count_ = nullptr ; 156d_ptr_ = nullptr ; 157original_row_ .clear (); 158layers_present_ .clear (); 159} 160 161bool RemoteExperts ::open (int device ,int slots ,int64_t layers ,int64_t experts , 162const std::vector < std::pair < int32_t ,int32_t >> & ranked , 163const ExpertCache & primary ,ExpertSource & source , 164 std::vector < uint8_t > & claimed , std::string & err ,bool /*auto_size*/ )try { 165close (); 166if (strata::kernels::cpu::hadamard_spec ().any ()) {// APR: this helper does not rotate the expert input yet (SYCL) 167err = "second-GPU experts: Hadamard-folded (Gyro) experts are not supported on a second Intel GPU yet" ; 168return false; 169 } 170int count = 0 ; 171if (!check (DPCT_CHECK_ERROR (count = dpct::device_count ()), 172"cudaGetDeviceCount" ,err ,device ))return false; 173if (device < 1 || device >=count || slots <=0 || ranked .empty ()|| 174layers <=0 || experts <=0 || claimed .size ()!= (size_t )layers * (size_t )experts ) { 175err = "CUDA" + std::to_string (device )+ " experts: need the device, ranked experts and positive slot count" ; 176return false; 177 } 178DeviceScope scope (device ); 179if (!scope .ok ) {err = scope .error (device );return false; } 180device_ = device ; 181n_expert_ = experts ; 182const auto & lay = strata::kernels::cpu::expert_layout (); 183 std::vector < std::pair < int32_t ,int32_t >> selected ; 184selected .reserve ((size_t )slots ); 185 std::vector < uint8_t > picked (claimed .size (),0 ); 186for (const auto & pair :ranked ) { 187if (pair .first < 0 || pair .first >=layers || pair .second < 0 || pair .second >=experts )continue ; 188const size_t index = (size_t )pair .first * (size_t )experts + (size_t )pair .second ; 189if (primary .slot_of (pair .first ,pair .second )< 0 && !claimed [index ]&& !picked [index ]) { 190selected .push_back (pair ); 191picked [index ]= 1 ; 192if ((int )selected .size () >=slots )break ; 193 } 194 } 195if (selected .empty ()) {err = "CUDA" + std::to_string (device )+ " experts: no unclaimed experts remain" ;close ();return false; } 196 std::vector < int64_t > sizes ; 197if (lay .native ) { 198sizes .reserve (selected .size ()); 199for (const auto & pair :selected )sizes .push_back ((int64_t )lay .blob_bytes (pair .first )); 200 } 201size_t free_bytes = 0 ,total_bytes = 0 ; 202/* 203DPCT1106: 'cudaMemGetInfo' was migrated with the Intel extensions for 204device information which may not be supported by all compilers or runtimes. 205You may need to adjust the code. 206*/ 207if (!check (DPCT_CHECK_ERROR (dpct::get_current_device ().get_memory_info ( 208free_bytes ,total_bytes )), 209"free memory" ,err ,device )) { 210close ();return false; 211 } 212uint64_t needed = 0 ; 213for (const auto & pair :selected ) 214needed += lay .native ? (lay .blob_bytes (pair .first )+ 255 ) /256 * 256 :lay .max_blob ; 215// Leave room for the CUDA context, staging and later driver allocations, especially under WDDM. 216if (needed + (512ull <<20 )> free_bytes ) { 217err = "CUDA" + std::to_string (device )+ " experts: slots leave less than 512 MiB free; reduce --expert-cache-device" + std::to_string (device ); 218close ();return false; 219 } 220const bool cache_ok = lay .native ?cache_ .open_sized (sizes ,layers ,experts ,err ) 221 :cache_ .open ((int64_t )selected .size (),layers ,experts , 222 (int64_t )lay .max_blob ,err ); 223if (!cache_ok ) {err = "CUDA" + std::to_string (device )+ " experts: " + err ;close ();return false; } 224for (const auto & pair :selected ) { 225const int32_t slot = cache_ .admit (pair .first ,pair .second ); 226const uint8_t * blob = source .blob (pair .first ,pair .second ); 227if (slot < 0 || !blob || !cache_ .fill_slot_blocking (slot ,blob ,err , (int64_t )lay .blob_bytes (pair .first ))) { 228err = "CUDA" + std::to_string (device )+ " experts: " + 229 (err .empty () ?"cache fill failed" :err ); 230close ();return false; 231 } 232 } 233const auto & first = selected .front (); 234if (!cache_ .verify_slot (cache_ .slot_of (first .first ,first .second ),source .blob (first .first ,first .second ), 235err , (int64_t )lay .blob_bytes (first .first ))) { 236err = "CUDA" + std::to_string (device )+ " experts: " + err ; 237close ();return false; 238 } 239 240const size_t scratch = std::max < size_t > ( 241 (size_t ) strata::kernels::moe_hit_grouped_scratch_bytes (CAP ,H ,FF ), 242 strata::kernels::native_expert_scratch_bytes (CAP ,FF )); 243const bool allocated = 244/* 245DPCT1025: The SYCL queue is created ignoring the flag and priority 246options. 247*/ 248check (DPCT_CHECK_ERROR ( 249stream_ = dpct::get_current_device ().create_queue (true)), 250"stream" ,err ,device )&& 251/* 252DPCT1048: The original value cudaHostAllocPortable is not meaningful 253in the migrated code and was removed or replaced with 0. You may need to 254check the migrated code. 255*/ 256/* 257DPCT1048: The original value cudaHostAllocMapped is not meaningful in 258the migrated code and was removed or replaced with 0. You may need to 259check the migrated code. 260*/ 261check ( 262DPCT_CHECK_ERROR (h_x_ = sycl::malloc_host < float > ( 263 (size_t )CAP * H , dpct::get_in_order_queue ())), 264"input staging" ,err ,device )&& 265/* 266DPCT1048: The original value cudaHostAllocPortable is not meaningful 267in the migrated code and was removed or replaced with 0. You may need to 268check the migrated code. 269*/ 270/* 271DPCT1048: The original value cudaHostAllocMapped is not meaningful in 272the migrated code and was removed or replaced with 0. You may need to 273check the migrated code. 274*/ 275check ( 276DPCT_CHECK_ERROR (h_out_ = sycl::malloc_host < float > ( 277 (size_t )CAP * H , dpct::get_in_order_queue ())), 278"result staging" ,err ,device )&& 279/* 280DPCT1048: The original value cudaHostAllocPortable is not meaningful 281in the migrated code and was removed or replaced with 0. You may need to 282check the migrated code. 283*/ 284check (DPCT_CHECK_ERROR ( 285h_meta_ = (void * )sycl::malloc_host ( 286sizeof (RemoteMeta ), dpct::get_in_order_queue ())), 287"metadata staging" ,err ,device )&& 288check ( 289DPCT_CHECK_ERROR (d_x_ = sycl::malloc_device < float > ( 290 (size_t )CAP * H , dpct::get_in_order_queue ())), 291"input" ,err ,device )&& 292check ( 293DPCT_CHECK_ERROR (d_out_ = sycl::malloc_device < float > ( 294 (size_t )CAP * H , dpct::get_in_order_queue ())), 295"result" ,err ,device )&& 296check (DPCT_CHECK_ERROR ( 297d_q8_ = (uint8_t * )sycl::malloc_device ( 298 (size_t )CAP * (H /32 )* 36 , dpct::get_in_order_queue ())), 299"activation" ,err ,device )&& 300check (DPCT_CHECK_ERROR ( 301d_scales_ = sycl::malloc_device < float > ( 302 (size_t )CAP * (H /32 ), dpct::get_in_order_queue ())), 303"activation scales" ,err ,device )&& 304check (DPCT_CHECK_ERROR (d_scratch_ = (void * )sycl::malloc_device ( 305scratch , dpct::get_in_order_queue ())), 306"scratch" ,err ,device )&& 307check (DPCT_CHECK_ERROR ( 308d_meta_ = (void * )sycl::malloc_device ( 309sizeof (RemoteMeta ), dpct::get_in_order_queue ())), 310"group metadata" ,err ,device ); 311if (!allocated ) {close ();return false; } 312// Zero-copy: the helper reads its input from, and writes its compact rows into, the pinned host buffers 313// directly - two copies fewer per layer, each of which is a PCIe round trip. STRATA_REMOTE_ZEROCOPY=0 copies. 314const char * zc = std::getenv ("STRATA_REMOTE_ZEROCOPY" ); 315zero_copy_ = !(zc && zc [0 ]== '0' )&& 316DPCT_CHECK_ERROR (* (void ** )& z_x_ = (float * )h_x_ )== 0 && 317DPCT_CHECK_ERROR (* (void ** )& z_out_ = (float * )h_out_ )== 0 ; 318/* 319DPCT1026: The call to cudaGetLastError was removed because this 320functionality is redundant in SYCL. 321*/ 322auto * meta = (RemoteMeta * )d_meta_ ; 323d_ptr_ = meta -> ptr ; 324d_start_ = meta -> start ; 325d_dst_ = meta -> dst ; 326d_tok_ = meta -> tok ; 327d_count_ = & meta -> count ; 328owned_ .resize (CAP ); 329layers_present_ .assign ((size_t )layers ,0 ); 330group_of_ .resize (CAP ); 331group_id_ .reserve (CAP ); 332ptr_ .reserve (CAP ); 333start_ .reserve (CAP + 1 ); 334dst_ .reserve (CAP ); 335tok_ .reserve (CAP ); 336original_row_ .reserve (CAP ); 337computed_ = 0 ; 338launched_layers_ = 0 ; 339returned_bytes_ = full_row_bytes_ = 0 ; 340for (const auto & pair :selected ) { 341layers_present_ [(size_t )pair .first ]= 1 ; 342claimed [(size_t )pair .first * (size_t )experts + (size_t )pair .second ]= 1 ; 343 } 344return true; 345} 346catch (sycl::exception const & exc ) { 347 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 348 <<", line:" <<__LINE__ << std::endl ; 349 std::exit (1 ); 350} 351 352bool RemoteExperts ::begin (int64_t layer ,const float * x ,const int32_t * ids , 353int64_t n_tok ,int64_t k ,const int32_t * kind , 354const int32_t * primary_res , std::string & err )try { 355// cumulative host time in here (staging and launches), reported per request by the driver 356struct Timer {double & acc ; std::chrono::steady_clock::time_point t0 = std::chrono::steady_clock::now (); 357 ~Timer () {acc += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t0 ).count (); } }timer {ms_begin_ }; 358const int64_t n = n_tok * k ; 359if (n <=0 || n > CAP || n_tok > strata::kernels::cpu::MAXT || k != (int ) strata::core::kCompiledGeometry .n_expert_used || layer < 0 || 360 (size_t )layer >=layers_present_ .size ()|| device_ < 0 ) { 361err = "CUDA" + std::to_string (device_ )+ " experts: invalid layer, routing width or window size" ; 362return false; 363 } 364 std::fill (owned_ .begin (),owned_ .begin ()+ n ,0 ); 365group_id_ .clear ();ptr_ .clear ();start_ .clear ();dst_ .clear ();tok_ .clear ();original_row_ .clear (); 366if (!layers_present_ [(size_t )layer ])return true; 367 std::fill (group_of_ .begin (),group_of_ .begin ()+ n ,-1 ); 368for (int64_t i = 0 ;i < n ;++ i ) { 369const int32_t e = ids [i ]; 370if ((kind && kind [i ]!= -1 )|| e < 0 || e >=n_expert_ || 371 (primary_res && primary_res [(size_t )layer * (size_t )n_expert_ + (size_t )e ] >=0 ))continue ; 372const int32_t slot = cache_ .slot_of (layer ,e ); 373if (slot < 0 )continue ; 374owned_ [(size_t )i ]= 1 ; 375int32_t group = -1 ; 376for (size_t g = 0 ;g < group_id_ .size ();++ g ) 377if (group_id_ [g ]== e ) {group = (int32_t )g ;break ; } 378if (group < 0 ) { 379group = (int32_t )group_id_ .size (); 380group_id_ .push_back (e ); 381ptr_ .push_back ((unsigned long long )cache_ .device_slot (slot )); 382 } 383group_of_ [(size_t )i ]= group ; 384++ computed_ ; 385 } 386if (group_id_ .empty ())return true; 387for (size_t g = 0 ;g < group_id_ .size ();++ g ) { 388start_ .push_back ((int32_t )dst_ .size ()); 389for (int64_t i = 0 ;i < n ;++ i )if (group_of_ [(size_t )i ]== (int32_t )g ) { 390// The grouped kernels read the activation from `tok`, so their 391// output row can instead be packed densely for the USB4 return. 392original_row_ .push_back ((int32_t )i ); 393dst_ .push_back ((int32_t )dst_ .size ()); 394tok_ .push_back ((int32_t ) (i /k )); 395 } 396 } 397start_ .push_back ((int32_t )dst_ .size ()); 398// Private pinned buffers survive until this GPU has consumed them. The CPU 399// pool can write other output rows without a cross-device race. 400 std::memcpy (h_x_ ,x , (size_t )n_tok * H * sizeof (float )); 401auto * meta = (RemoteMeta * )h_meta_ ; 402 std::memcpy (meta -> ptr ,ptr_ .data (),ptr_ .size ()* sizeof (ptr_ [0 ])); 403 std::memcpy (meta -> start ,start_ .data (),start_ .size ()* sizeof (start_ [0 ])); 404 std::memcpy (meta -> dst ,dst_ .data (),dst_ .size ()* sizeof (dst_ [0 ])); 405 std::memcpy (meta -> tok ,tok_ .data (),tok_ .size ()* sizeof (tok_ [0 ])); 406meta -> count = (int32_t )group_id_ .size (); 407DeviceScope scope (device_ ); 408if (!scope .ok ) {err = scope .error (device_ );return false; } 409groups_ = (int32_t )group_id_ .size (); 410const dpct::queue_ptr s = stream_ ; 411const bool staged = 412/* 413DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 414While the origin API might be synchronous, it depends on the type of 415operand memory, so you may need to call wait() on event return by memcpy 416API to ensure synchronization behavior. 417*/ 418 (zero_copy_ || 419check (DPCT_CHECK_ERROR ( 420s -> memcpy (d_x_ ,h_x_ , (size_t )n_tok * H * sizeof (float ))), 421"copy input" ,err ,device_ ))&& 422/* 423DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 424While the origin API might be synchronous, it depends on the type of 425operand memory, so you may need to call wait() on event return by memcpy 426API to ensure synchronization behavior. 427*/ 428check (DPCT_CHECK_ERROR (s -> memcpy (d_meta_ ,h_meta_ ,sizeof (RemoteMeta ))), 429"copy group metadata" ,err ,device_ ); 430if (!staged )return false; 431const auto & lay = strata::kernels::cpu::expert_layout (); 432if (lay .native ) { 433 strata::kernels::quantize_q8_1_rows (zero_copy_ ?z_x_ :d_x_ ,n_tok ,H ,d_q8_ ,s ); 434const auto & fmt = lay .fmt [(size_t )layer ]; 435auto L = strata::kernels::native_expert_layout (fmt .gu_type ,fmt .d_type ,fmt .n_embd ,fmt .n_ff ); 436 strata::kernels::native_expert_grouped (L ,d_ptr_ ,d_start_ ,d_count_ ,d_dst_ ,d_tok_ , 437groups_ , (int64_t )dst_ .size (),d_q8_ ,d_scratch_ ,zero_copy_ ?z_out_ :d_out_ ,s ); 438 }else { 439 strata::kernels::quantize_q8_0_scaled (zero_copy_ ?z_x_ :d_x_ ,d_q8_ ,d_scales_ ,n_tok * H ,s ); 440 strata::kernels::moe_grouped_s2 (d_ptr_ ,d_start_ ,d_count_ ,d_dst_ ,d_tok_ , 441groups_ , (int64_t )dst_ .size (),d_q8_ ,d_scales_ ,d_scratch_ ,zero_copy_ ?z_out_ :d_out_ ,s ); 442 } 443const uint64_t compact_bytes = (uint64_t )dst_ .size ()* H * sizeof (float ); 444/* 445DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While 446the origin API might be synchronous, it depends on the type of operand 447memory, so you may need to call wait() on event return by memcpy API to 448ensure synchronization behavior. 449*/ 450if (!zero_copy_ && !check (DPCT_CHECK_ERROR (s -> memcpy ( 451h_out_ ,d_out_ , (size_t )compact_bytes )), 452"copy results" ,err ,device_ ))return false; 453++ launched_layers_ ; 454returned_bytes_ += compact_bytes ; 455full_row_bytes_ += (uint64_t )n * H * sizeof (float ); 456return true; 457} 458catch (sycl::exception const & exc ) { 459 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 460 <<", line:" <<__LINE__ << std::endl ; 461 std::exit (1 ); 462} 463 464bool RemoteExperts ::finish (float * out , std::string & err )try { 465if (group_id_ .empty ())return true; 466DeviceScope scope (device_ ); 467if (!scope .ok ) {err = scope .error (device_ );return false; } 468const auto w0 = std::chrono::steady_clock::now (); 469if (!check (DPCT_CHECK_ERROR (stream_ -> wait ()),"finish" ,err , 470device_ ))return false; 471ms_wait_ += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- w0 ).count (); 472for (size_t i = 0 ;i < original_row_ .size ();++ i ) 473 std::memcpy (out + (size_t )original_row_ [i ]* H ,h_out_ + i * H , (size_t )H * sizeof (float )); 474return true; 475} 476catch (sycl::exception const & exc ) { 477 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 478 <<", line:" <<__LINE__ << std::endl ; 479 std::exit (1 ); 480} 481 482}// namespace strata::core