okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f812e9a16
main
1// src/core/session.cpp - one token through all 48 layers. See the header for why the graphs are per-layer. 2#define DPCT_PROFILING_ENABLED 3#include <sycl/sycl.hpp> 4#include <dpct/dpct.hpp> 5#include "strata/sycl_queue.hpp" 6#include "strata/core/session.hpp" 7#include "strata/kernels/mrope.hpp" 8#include "strata/core/progress.hpp" 9 10#include "strata/kernels/qsa.hpp" 11#include "strata/kernels/elementwise.hpp" 12#include "strata/kernels/quantize_act.hpp" 13#include "strata/kernels/s2_expert_grouped.hpp" 14#include "strata/kernels/cpu/pool.hpp" 15#include "strata/kernels/ngram.hpp" 16 17#include <atomic> 18#include <chrono> 19#include <cstdio> 20#include <cstdlib> 21#include <cstring> 22#include <vector> 23 24// `_mm_pause` for the doorbell spin. Guarded because it is x86-only; a target without it still builds, the 25// spin is just less polite to the pipeline. 26#if defined(_MSC_VER )|| defined(__x86_64__ )|| defined(__i386__ ) 27#include <immintrin.h> 28#define STRATA_SPIN_PAUSE () _mm_pause() 29#else 30#define STRATA_SPIN_PAUSE () ((void) 0) 31#endif 32 33namespace strata::core { 34namespace { 35 36constexpr uint64_t SESSION_STATE_ALIGN = 256 ; 37 38uint64_t align_up (uint64_t n ,uint64_t a ) {return (n + a - 1 ) /a * a ; } 39 40/// The floats one GDN layer's recurrent + conv state needs. `gdn_buffers_bytes` carves them for ONE layer and 41/// `GdnBuffers::state`/`conv_state` point INTO that carve, so a session with 36 GDN layers has to give each one 42/// its own - they cannot share, because the recurrence is the whole point. 43uint64_t gdn_state_floats (const ModelGeometry & g ) { 44return (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 45 (uint64_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 46} 47 48}// namespace 49 50/// `NG_HIST` rows of `hc_dim` floats: the PLE conv's history, which is the ONLY PLE state that lives in the 51/// session arena. The table and the weights are model-level and the caller owns them. 52static uint64_t ple_hist_bytes () { 53return (uint64_t ) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof (float ); 54} 55 56uint64_t session_bytes (const ModelGeometry & g ,int64_t max_cells ,int64_t k ,int64_t layer_lo ,int64_t layer_hi ) { 57if (layer_hi < 0 || layer_hi > g .n_layers )layer_hi = g .n_layers ; 58if (layer_lo < 0 )layer_lo = 0 ; 59// QSA layers are `l % interval == interval-1`, so exactly `bound / interval` of them live below `bound` 60const int64_t I = std::max < int64_t > (g .qsa_interval ,1 ); 61const int64_t q_lo = layer_lo /I ,q_hi = layer_hi /I ; 62const int64_t q_n = std::max < int64_t > (q_hi - q_lo ,g .n_qsa_layers ()> 0 ?1 :0 ); 63const int64_t gdn_n = std::max < int64_t > ((layer_hi - layer_lo )- std::max < int64_t > (q_hi - q_lo ,0 ),0 ); 64uint64_t n = 0 ; 65n += gdn_buffers_bytes (g ); 66n += (uint64_t )gdn_n * gdn_state_floats (g )* 4 ; 67// One QSA state carries the RoPE table; the others borrow it (P7: 64 MiB per layer at 262K). 68if (g .n_qsa_layers ()> 0 ) 69n += qsa_state_bytes (g ,max_cells , true)+ (uint64_t ) (q_n - 1 )* qsa_state_bytes (g ,max_cells , false); 70n += qsa_buffers_bytes (g ,max_cells ); 71n += moe_buffers_bytes (g ,k ); 72n += block_buffers_bytes (g ); 73n += ple_hist_bytes ();// the PLE's NG_HIST normalized history rows 74return align_up (n ,SESSION_STATE_ALIGN )+ 4096 ; 75} 76 77uint64_t session_init (const ModelGeometry & g ,int64_t max_cells ,int64_t k ,void * base ,SessionState & s , 78int64_t layer_lo ,int64_t layer_hi ) { 79if (layer_hi < 0 || layer_hi > g .n_layers )layer_hi = g .n_layers ; 80if (layer_lo < 0 )layer_lo = 0 ; 81uint8_t * p = (uint8_t * )base ; 82uint64_t used = 0 ; 83auto take = [& ](uint64_t bytes ) { 84uint8_t * r = p + used ; 85used = align_up (used + bytes ,SESSION_STATE_ALIGN ); 86return r ; 87 }; 88 89s .max_cells = max_cells ; 90s .k = k ; 91s .layer_lo = layer_lo ; 92s .layer_hi = layer_hi ; 93const int64_t I = std::max < int64_t > (g .qsa_interval ,1 ); 94const int64_t q_n_range = layer_hi /I - layer_lo /I ; 95s .qsa_ord0 = layer_lo /I ; 96s .qsa_alloc = std::max < int64_t > (q_n_range ,g .n_qsa_layers ()> 0 ?1 :0 ); 97s .gdn_ord0 = layer_lo - layer_lo /I ; 98s .gdn_alloc = std::max < int64_t > ((layer_hi - layer_lo )- q_n_range ,0 ); 99 100gdn_buffers_init (g ,take (gdn_buffers_bytes (g )),s .gdn ); 101s .gdn_state = (float * )take ((uint64_t )s .gdn_alloc * gdn_state_floats (g )* 4 ); 102 103// the QSA states are separate allocations carved from one arena, because `QsaState` is a struct of 104// pointers and `qsa_state_init` writes them - a contiguous array would need the arena to be laid out the 105// same way, which is a coupling with nothing to gain. Only the range's ordinals are initialized; the 106// rest stay value-initialized nulls. The FIRST ALLOCATED one (the session's primary, ordinal qsa_ord0) 107// owns the RoPE table that the others - and the prefill staging identity, and the MTP drafter - borrow. 108const uint64_t first = qsa_state_bytes (g ,max_cells , true),rest = qsa_state_bytes (g ,max_cells , false); 109s .qsa_state_arena = take (g .n_qsa_layers ()> 0 ?first + (uint64_t ) (s .qsa_alloc - 1 )* rest :0 ); 110s .qsa_states = new QsaState [(size_t )g .n_qsa_layers ()](); 111s .qsa_buf_arena = take (qsa_buffers_bytes (g ,max_cells )); 112 113uint8_t * qp = (uint8_t * )s .qsa_state_arena ; 114// a layer whose pinned RAM could not be had (KV streaming's host copy) is half-built: going on would have the 115// attention read null host pointers at the first request ("illegal memory access"), so the session fails here 116for (int64_t j = 0 ;j < s .qsa_alloc ;++ j ) 117if (qsa_state_init (g ,max_cells ,qp + (j == 0 ?0 :first + (uint64_t ) (j - 1 )* rest ), 118s .qsa_states [s .qsa_ord0 + j ],j == 0 ?nullptr :& s .qsa_states [s .qsa_ord0 ])== 0 ) 119return 0 ; 120qsa_buffers_init (g ,max_cells ,s .qsa_buf_arena ,s .qsa_bufs ); 121 122s .moe_arena = take (moe_buffers_bytes (g ,k )); 123moe_buffers_init (g ,k ,s .moe_arena ,s .moe ); 124s .block_arena = take (block_buffers_bytes (g )); 125block_buffers_init (g ,s .block_arena ,s .block ); 126// THE PLE HISTORY: NG_HIST rows of hc_dim floats, row-fastest. Sequence state, carved here and zeroed by 127// `session_zero`; it survives every token, which is the whole point of a conv history. 128s .ple_hist = (float * )take (ple_hist_bytes ()); 129s .R = s .block .R ; 130return used ; 131} 132 133void session_release (SessionState & s ) { 134for (int64_t j = 0 ;s .qsa_states != nullptr && j < s .qsa_alloc ;++ j ) 135if (s .qsa_states [j ].owns_rope ) { 136 strata::kernels::rope_table_release (s .qsa_states [j ].cos_tab ); 137s .qsa_states [j ].owns_rope = false; 138 } 139} 140 141void session_zero (SessionState & s ,const ModelGeometry & g ,const float * R_init ,void * stream ) { 142 dpct::queue_ptr cs = strata::q_of (stream ); 143// the residual: `hc` copies of the one vector a caller hands in. A real sequence's first token is the 144// embedding broadcast to every stream, which is the reference's own initial condition. 145if (R_init != nullptr ) { 146for (int64_t c = 0 ;c < g .hc ;++ c ) 147/* 148DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 149API. While the origin API might be synchronous, it depends on the 150type of operand memory, so you may need to call wait() on event 151return by memcpy API to ensure synchronization behavior. 152*/ 153cs -> memcpy (s .block .R + (size_t )c * g .n_embd ,R_init , 154 (size_t )g .n_embd * 4 ); 155 }else { 156cs -> memset (s .block .R ,0 , (size_t )g .hc * g .n_embd * 4 ); 157 } 158// every owned GDN layer's recurrence and conv history 159cs -> memset (s .gdn_state ,0 , (size_t )s .gdn_alloc * gdn_state_floats (g )* 4 ); 160// and every owned QSA layer's cache and indexer 161for (int64_t j = 0 ;j < s .qsa_alloc ;++ j )qsa_state_zero (s .qsa_states [s .qsa_ord0 + j ],g ,stream ); 162// **AND THE PLE'S CONV HISTORY AND TOKEN WINDOW.** A sequence that started with a warm history would 163// convolve over rows belonging to a different sequence - the conv reads NG_HIST previous NORMALIZED rows, 164// so a stale one is a real contribution and not a zero. The token window resets to `NG_HIST`-many nulls 165// for the same reason: `ngram_rows` treats a missing predecessor as the EOS cut, which is what a sequence 166// boundary IS. 167cs -> memset (s .ple_hist ,0 , (size_t )ple_hist_bytes ()); 168s .ple_prev [0 ]= -1 ; 169s .ple_prev [1 ]= -1 ; 170s .ple_token = -1 ; 171} 172 173/// Sets `s.gdn.state`/`conv_state` for `layer`, which is what makes one layer's GDN state its own. Shared by 174/// the direct and captured paths so the two cannot disagree about which slice a layer owns. 175void gdn_point_at (const ModelGeometry & g ,int64_t layer ,SessionState & s ) { 176if (is_qsa_layer (g ,layer ))return ; 177int64_t gdn_index = 0 ; 178for (int64_t l = 0 ;l < layer ;++ l )if (!is_qsa_layer (g ,l ))++ gdn_index ; 179s .gdn .state = s .gdn_state + (size_t ) (gdn_index - s .gdn_ord0 )* gdn_state_floats (g ); 180s .gdn .conv_state = s .gdn .state + (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 181} 182 183/// The per-token staging every QSA layer's captured H2D reads FROM. Must run before each replay: the graphs 184/// captured the SOURCE POINTER, not the value, and that is exactly why the buffers are pinned and fixed. 185void stage_token (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s ) { 186const strata::kernels::QsaShapes sh = qsa_shapes (g ); 187for (int64_t j = 0 ;j < s .qsa_alloc ;++ j ) { 188QsaState & q = s .qsa_states [s .qsa_ord0 + j ]; 189qsa_step_fill (q .host_step ,pos ,sh ); 190for (int64_t h = 0 ;h < g .n_head ;++ h )q .host_pos [h ]= (int32_t ) (pos_base + pos ); 191 } 192} 193 194bool session_capture (const WeightTable & tables ,const ModelGeometry & g ,SessionState & s ,const float * parts , 195SessionGraphs & gr , std::string & err ,bool split ,int64_t layer_lo ,int64_t layer_hi ) { 196if (gr .captured )return true; 197if (layer_hi < 0 || layer_hi > g .n_layers )layer_hi = g .n_layers ; 198if (layer_lo < 0 )layer_lo = 0 ; 199gr .execs = 200new dpct::experimental::command_graph_exec_ptr [(size_t )g .n_layers ](); 201gr .posts = 202new dpct::experimental::command_graph_exec_ptr [(size_t )g .n_layers ](); 203for (int64_t i = 0 ;i < g .n_layers ;++ i )gr .posts [i ]= nullptr ; 204if (split ) { 205gr .preA = 206new dpct::experimental::command_graph_exec_ptr [(size_t ) 207g .n_layers ](); 208gr .preB = 209new dpct::experimental::command_graph_exec_ptr [(size_t ) 210g .n_layers ](); 211for (int64_t i = 0 ;i < g .n_layers ;++ i ) {gr .preA [i ]= nullptr ;gr .preB [i ]= nullptr ; } 212for (int k = 0 ;k < 5 ;++ k ) { 213gr .preP [k ]= 214new dpct::experimental::command_graph_exec_ptr [(size_t )g 215 .n_layers ](); 216for (int64_t i = 0 ;i < g .n_layers ;++ i )gr .preP [k ][i ]= nullptr ; 217 } 218 } 219gr .split_captured = split ; 220gr .n = 0 ; 221 222int64_t qsa_index = s .qsa_ord0 ; 223for (int64_t l = layer_lo ;l < layer_hi ;++ l ) { 224gdn_point_at (g ,l ,s ); 225const bool qsa = is_qsa_layer (g ,l ); 226QsaState & qst = qsa ?s .qsa_states [qsa_index ] :s .qsa_states [s .qsa_primary ()]; 227 228// **TWO GRAPHS PER LAYER, SPLIT AT THE ROUTER.** `pre` ends with the doorbell rung; the host then runs 229// the CPU pool on what it published; `post` combines those experts with THIS layer's weights. Capturing 230// them together is what the old single graph could not do, and the reason it could not is that 231// `moe_combine` needs the pool's answer and the pool needs the router's. 232auto capture = 233 [& ](bool post , dpct::experimental::command_graph_exec_ptr * out , 234const char * what ,int half = 0 ,int stage_prefix = 0 )-> bool { 235try { 236 dpct::queue_ptr cs = & dpct::get_in_order_queue (); 237if (DPCT_CHECK_ERROR ( 238cs = dpct::get_current_device ().create_queue (true))!= 0 ) { 239err = std::string ("session_capture: stream create failed" ); 240return false; 241 } 242if (DPCT_CHECK_ERROR (dpct::experimental::begin_recording (cs ))!= 2430 ) { 244err = "session_capture: begin failed at layer " + std::to_string (l ); 245return false; 246 } 247err .clear (); 248// R0.9: `half` is 0 for every mode except the split capture, where it selects a prefix of the 249// stages so the mixer and the FFN-front-plus-router can be timed separately. 250const bool ok = post 251 ?block_layer_post (tables ,g ,l ,s .k ,s .moe ,s .block ,parts , (void * )cs ,err ) 252 :block_layer_pre (tables ,g ,l ,0 ,0 ,s .gdn ,qst ,s .qsa_bufs ,s .moe ,s .k , 253s .block , (void * )cs ,err ,s .db ,s .ple .ready () ?& s .ple :nullptr , 254half ,stage_prefix ); 255if (!ok ) { 256err = "session_capture: " + std::string (what )+ " layer " + std::to_string (l )+ ": " + err ; 257return false; 258 } 259 dpct::experimental::command_graph_ptr graph = nullptr ; 260const dpct::err0 ce = 261DPCT_CHECK_ERROR (dpct::experimental::end_recording (cs ,& graph )); 262 dpct::get_current_device ().destroy_queue (cs ); 263/* 264DPCT1000: Error handling if-stmt was detected but could not be 265rewritten. 266*/ 267if (ce != 0 ) { 268/* 269DPCT1001: The statement could not be removed. 270*/ 271err = "session_capture: " + std::string (what )+ " layer " + 272 std::to_string (l )+ ": " + 273/* 274DPCT1009: SYCL reports errors using exceptions and 275does not use error codes. Please replace the 276"get_error_string_dummy(...)" with a real error-handling 277function. 278*/ 279 dpct::get_error_string_dummy (ce )+ 280" (a synchronous call in the layer?)" ; 281return false; 282 } 283if (DPCT_CHECK_ERROR ( 284* out = 285new sycl::ext::oneapi::experimental::command_graph < 286 sycl::ext::oneapi::experimental::graph_state:: 287executable > (graph -> finalize ()))!= 0 ) { 288err = "session_capture: instantiate failed at layer " + std::to_string (l ); 289return false; 290 } 291delete (graph ); 292return true; 293 } 294catch (sycl::exception const & exc ) { 295 std::cerr 296 <<exc .what () 297 <<"Exception caught at file:" <<__FILE__ 298 <<", line:" <<__LINE__ << std::endl ; 299 std::exit (1 ); 300 } 301 }; 302if (!capture (/*post=*/ false,& gr .execs [l ],"pre" ))return false; 303if (!capture (/*post=*/ true,& gr .posts [l ],"post" ))return false; 304if (split ) { 305if (!capture (/*post=*/ false,& gr .preA [l ],"preA" ,/*half=*/ 1 ))return false; 306if (!capture (/*post=*/ false,& gr .preB [l ],"preB" ,/*half=*/ 2 ))return false; 307// Prefixes 1..5, ALL through the new parameter - including the fifth, so that it and the fourth 308// differ only in the one stage between them and not in how many nodes their graphs carry. 309for (int k = 1 ;k <=5 ;++ k ) 310if (!capture (/*post=*/ false,& gr .preP [k - 1 ][l ],"preP" ,/*half=*/ 0 ,/*stage_prefix=*/ k )) 311return false; 312 } 313++ gr .n ; 314if (qsa )++ qsa_index ; 315 } 316gr .captured = true; 317gr .parts_dev = const_cast < float *> (parts );// the address the graphs baked in; the loop copies here 318return true; 319} 320 321bool session_replay (const ModelGeometry & g ,int64_t pos ,int32_t pos_base , 322SessionState & s ,SessionGraphs & gr ,void * stream , 323 std::string & err )try { 324if (!gr .captured || gr .n != g .n_layers ) {err = "session_replay: not captured" ;return false; } 325 dpct::queue_ptr cs = strata::q_of (stream ); 326stage_token (g ,pos ,pos_base ,s ); 327for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 328const dpct::err0 e = 329DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .execs [l ])); 330/* 331DPCT1000: Error handling if-stmt was detected but could not be 332rewritten. 333*/ 334if (e != 0 ) { 335/* 336DPCT1009: SYCL reports errors using exceptions and does not use 337error codes. Please replace the "get_error_string_dummy(...)" with a 338real error-handling function. 339*/ 340/* 341DPCT1001: The statement could not be removed. 342*/ 343err = "session_replay: layer " + std::to_string (l )+ ": " + 344 dpct::get_error_string_dummy (e ); 345return false; 346 } 347 } 348return true; 349} 350catch (sycl::exception const & exc ) { 351 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 352 <<", line:" <<__LINE__ << std::endl ; 353 std::exit (1 ); 354} 355 356bool session_replay_full (const ModelGeometry & g ,int64_t pos ,int32_t pos_base , 357SessionState & s ,SessionGraphs & gr ,void * stream , 358 std::string & err )try { 359if (!gr .captured || gr .n != g .n_layers || gr .posts == nullptr ) { 360err = "session_replay_full: not captured with post graphs" ; 361return false; 362 } 363 dpct::queue_ptr cs = strata::q_of (stream ); 364stage_token (g ,pos ,pos_base ,s ); 365for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 366// `pre[l]` then `post[l]`, in the order `session_loop` uses. The two are ordered on one stream, and 367// `post[l]` reads what `pre[l]` wrote, so they cannot be reordered or run concurrently. 368 dpct::err0 e = DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .execs [l ])); 369/* 370DPCT1000: Error handling if-stmt was detected but could not be 371rewritten. 372*/ 373if (e != 0 ) { 374/* 375DPCT1009: SYCL reports errors using exceptions and does not use 376error codes. Please replace the "get_error_string_dummy(...)" with a 377real error-handling function. 378*/ 379/* 380DPCT1001: The statement could not be removed. 381*/ 382err = "session_replay_full: pre[" + std::to_string (l )+ 383"]: " + dpct::get_error_string_dummy (e ); 384return false; 385 } 386e = DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .posts [l ])); 387/* 388DPCT1000: Error handling if-stmt was detected but could not be 389rewritten. 390*/ 391if (e != 0 ) { 392/* 393DPCT1009: SYCL reports errors using exceptions and does not use 394error codes. Please replace the "get_error_string_dummy(...)" with a 395real error-handling function. 396*/ 397/* 398DPCT1001: The statement could not be removed. 399*/ 400err = "session_replay_full: post[" + std::to_string (l )+ 401"]: " + dpct::get_error_string_dummy (e ); 402return false; 403 } 404 } 405return true; 406} 407catch (sycl::exception const & exc ) { 408 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 409 <<", line:" <<__LINE__ << std::endl ; 410 std::exit (1 ); 411} 412 413bool session_replay_stages_per_layer (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s , 414SessionGraphs & gr ,void * stream , std::vector < double >& mixer_per_layer , 415double & ms_ffn ,double & ms_post , std::string & err ) { 416if (!gr .split_captured || gr .preA == nullptr || gr .preB == nullptr ) { 417err = "session_replay_stages: not captured with the split" ; 418return false; 419 } 420 dpct::queue_ptr cs = strata::q_of (stream ); 421stage_token (g ,pos ,pos_base ,s ); 422 423// Four events PER LAYER rather than four reused ones: reusing them would need a synchronisation after 424// every layer to read them before the next launch overwrote them, and a per-layer sync would report the 425// serialised time rather than the graph's. 426const int64_t n = g .n_layers ; 427 std::vector < dpct::event_ptr > ev ((size_t )(n * 4 )); 428for (auto & e :ev ) { 429if (DPCT_CHECK_ERROR (e = new sycl::event ())!= 0 ) { 430err = "session_replay_stages: event create" ;return false; 431 } 432 } 433struct Free { 434 std::vector < dpct::event_ptr > * v ; 435 ~Free () {for (auto & e :* v )DPCT_CHECK_ERROR (dpct::destroy_event (e )); } 436 }frees {& ev }; 437 438for (int64_t l = 0 ;l < n ;++ l ) { 439 dpct::sync_barrier (ev [(size_t )(l * 4 + 0 )],cs ); 440if (DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .preA [l ]))!= 0 ) { 441err = "stages: preA" ;return false; 442 } 443 dpct::sync_barrier (ev [(size_t )(l * 4 + 1 )],cs ); 444if (DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .preB [l ]))!= 0 ) { 445err = "stages: preB" ;return false; 446 } 447 dpct::sync_barrier (ev [(size_t )(l * 4 + 2 )],cs ); 448if (DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .posts [l ]))!= 0 ) { 449err = "stages: post" ;return false; 450 } 451 dpct::sync_barrier (ev [(size_t )(l * 4 + 3 )],cs ); 452 } 453if (DPCT_CHECK_ERROR (cs -> wait ())!= 0 ) { 454err = "stages: final sync" ;return false; 455 } 456 457mixer_per_layer .assign ((size_t )n ,0.0 ); 458ms_ffn = 0 ;ms_post = 0 ; 459for (int64_t l = 0 ;l < n ;++ l ) { 460float a = 0 ,b = 0 ,c = 0 ; 461a = (ev [(size_t )(l * 4 + 1 )] 462-> get_profiling_info < 463 sycl::info::event_profiling::command_end > ()- 464ev [(size_t )(l * 4 + 0 )] 465-> get_profiling_info < 466 sycl::info::event_profiling::command_start > ()) / 4671000000.0f ; 468b = (ev [(size_t )(l * 4 + 2 )] 469-> get_profiling_info < 470 sycl::info::event_profiling::command_end > ()- 471ev [(size_t )(l * 4 + 1 )] 472-> get_profiling_info < 473 sycl::info::event_profiling::command_start > ()) / 4741000000.0f ; 475c = (ev [(size_t )(l * 4 + 3 )] 476-> get_profiling_info < 477 sycl::info::event_profiling::command_end > ()- 478ev [(size_t )(l * 4 + 2 )] 479-> get_profiling_info < 480 sycl::info::event_profiling::command_start > ()) / 4811000000.0f ; 482mixer_per_layer [(size_t )l ]= (double )a ; 483ms_ffn += b ;ms_post += c ; 484 } 485return true; 486} 487 488bool session_replay_stages (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s , 489SessionGraphs & gr ,void * stream ,double & ms_mixer ,double & ms_ffn ,double & ms_post , 490 std::string & err ) { 491 std::vector < double > per ; 492if (!session_replay_stages_per_layer (g ,pos ,pos_base ,s ,gr ,stream ,per ,ms_ffn ,ms_post ,err ))return false; 493ms_mixer = 0 ; 494for (double v :per )ms_mixer += v ; 495return true; 496} 497 498bool session_replay_stage_sweep (const ModelGeometry & g ,int64_t pos , 499int32_t pos_base ,SessionState & s , 500SessionGraphs & gr ,void * stream ,int k , 501double & ms , std::string & err )try { 502if (!gr .split_captured || gr .preP [0 ]== nullptr ) { 503err = "session_replay_stage_sweep: not captured with the split" ; 504return false; 505 } 506if (k < 1 || k > 5 ) {err = "session_replay_stage_sweep: k must be 1..5" ;return false; } 507 dpct::queue_ptr cs = strata::q_of (stream ); 508stage_token (g ,pos ,pos_base ,s ); 509 510 dpct::event_ptr a ,b ; 511if (DPCT_CHECK_ERROR (a = new sycl::event ())!= 0 || 512DPCT_CHECK_ERROR (b = new sycl::event ())!= 0 ) { 513err = "session_replay_stage_sweep: event create" ; 514return false; 515 } 516 dpct::sync_barrier (a ,cs ); 517for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 518const dpct::err0 e = 519DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .preP [k - 1 ][l ])); 520/* 521DPCT1000: Error handling if-stmt was detected but could not be 522rewritten. 523*/ 524if (e != 0 ) { 525/* 526DPCT1001: The statement could not be removed. 527*/ 528 dpct::destroy_event (a ); 529 dpct::destroy_event (b ); 530/* 531DPCT1009: SYCL reports errors using exceptions and does not use 532error codes. Please replace the "get_error_string_dummy(...)" with a 533real error-handling function. 534*/ 535err = std::string ("session_replay_stage_sweep: launch: " )+ 536 dpct::get_error_string_dummy (e ); 537return false; 538 } 539 } 540 dpct::sync_barrier (b ,cs ); 541if (DPCT_CHECK_ERROR (cs -> wait ())!= 0 ) { 542 dpct::destroy_event (a ); 543 dpct::destroy_event (b ); 544err = "session_replay_stage_sweep: sync" ; 545return false; 546 } 547float v = 0 ; 548v = (b -> get_profiling_info < sycl::info::event_profiling::command_end > ()- 549a -> get_profiling_info < sycl::info::event_profiling::command_start > ()) / 5501000000.0f ; 551 dpct::destroy_event (a ); 552 dpct::destroy_event (b ); 553ms = (double )v ; 554return true; 555} 556catch (sycl::exception const & exc ) { 557 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 558 <<", line:" <<__LINE__ << std::endl ; 559 std::exit (1 ); 560} 561 562bool session_replay_stage_prefixes (const ModelGeometry & g ,int64_t pos , 563int32_t pos_base ,SessionState & s , 564SessionGraphs & gr ,void * stream , 565 std::vector < double > & stage_ms , 566 std::vector < double > & mixer_per_layer , 567 std::string & err )try { 568if (!gr .split_captured || gr .preP [0 ]== nullptr ) { 569err = "session_replay_stage_prefixes: not captured with the split" ; 570return false; 571 } 572 dpct::queue_ptr cs = strata::q_of (stream ); 573stage_token (g ,pos ,pos_base ,s ); 574const int64_t n = g .n_layers ; 575const size_t r_floats = (size_t )g .hc * (size_t )g .n_embd ; 576 577float * saved = nullptr ; 578if (DPCT_CHECK_ERROR (saved = sycl::malloc_device < float > ( 579r_floats , dpct::get_in_order_queue ()))!= 0 ) { 580err = "session_replay_stage_prefixes: could not save the residual" ; 581return false; 582 } 583 std::vector < dpct::event_ptr > ev ((size_t )(n * 6 )); 584bool ev_ok = true; 585for (auto & e :ev )if (DPCT_CHECK_ERROR (e = new sycl::event ())!= 0 ) { 586ev_ok = false;break ; 587 } 588if (!ev_ok ) { 589for (auto & e :ev )DPCT_CHECK_ERROR (dpct::destroy_event (e )); 590 sycl::free (saved , dpct::get_in_order_queue ()); 591err = "session_replay_stage_prefixes: event create" ; 592return false; 593 } 594struct Cleanup { 595 std::vector < dpct::event_ptr > * v ; 596float * p ; 597 ~Cleanup () { 598for (auto & e :* v )DPCT_CHECK_ERROR (dpct::destroy_event (e )); 599 sycl::free (p , dpct::get_in_order_queue ()); 600 } 601 }cleanup {& ev ,saved }; 602 603double t [5 ]= {0 ,0 ,0 ,0 ,0 }; 604mixer_per_layer .assign ((size_t )n ,0.0 ); 605for (int64_t l = 0 ;l < n ;++ l ) { 606// The residual as this layer receives it, before any prefix has advanced it. 607/* 608DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 609While the origin API might be synchronous, it depends on the type of 610operand memory, so you may need to call wait() on event return by memcpy 611API to ensure synchronization behavior. 612*/ 613cs -> memcpy (saved ,s .block .R ,r_floats * sizeof (float )); 614for (int k = 1 ;k <=5 ;++ k ) { 615/* 616DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 617API. While the origin API might be synchronous, it depends on the 618type of operand memory, so you may need to call wait() on event 619return by memcpy API to ensure synchronization behavior. 620*/ 621if (k > 1 )cs -> memcpy (s .block .R ,saved ,r_floats * sizeof (float )); 622 dpct::sync_barrier (ev [(size_t )(l * 6 + k - 1 )],cs ); 623const dpct::experimental::command_graph_exec_ptr ge = 624 (k == 5 ) ?gr .execs [l ] :gr .preP [k - 1 ][l ]; 625const dpct::err0 e = DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* ge )); 626/* 627DPCT1000: Error handling if-stmt was detected but could not be 628rewritten. 629*/ 630if (e != 0 ) { 631/* 632DPCT1001: The statement could not be removed. 633*/ 634err = std::string ( 635"session_replay_stage_prefixes: launch prefix " )+ 636 std::to_string (k )+ ": " + 637/* 638DPCT1009: SYCL reports errors using exceptions and 639does not use error codes. Please replace the 640"get_error_string_dummy(...)" with a real error-handling 641function. 642*/ 643 dpct::get_error_string_dummy (e ); 644return false; 645 } 646 } 647 dpct::sync_barrier (ev [(size_t )(l * 6 + 5 )],cs ); 648 } 649if (DPCT_CHECK_ERROR (cs -> wait ())!= 0 ) { 650err = "prefixes: final sync" ;return false; 651 } 652 653float t1 = 0 ,t2 = 0 ,t3 = 0 ,t4 = 0 ,t5 = 0 ; 654for (int64_t l = 0 ;l < n ;++ l ) { 655float a = 0 ,b = 0 ,c = 0 ,d = 0 ,e = 0 ; 656a = (ev [(size_t )(l * 6 + 1 )] 657-> get_profiling_info < 658 sycl::info::event_profiling::command_end > ()- 659ev [(size_t )(l * 6 + 0 )] 660-> get_profiling_info < 661 sycl::info::event_profiling::command_start > ()) / 6621000000.0f ; 663b = (ev [(size_t )(l * 6 + 2 )] 664-> get_profiling_info < 665 sycl::info::event_profiling::command_end > ()- 666ev [(size_t )(l * 6 + 1 )] 667-> get_profiling_info < 668 sycl::info::event_profiling::command_start > ()) / 6691000000.0f ; 670c = (ev [(size_t )(l * 6 + 3 )] 671-> get_profiling_info < 672 sycl::info::event_profiling::command_end > ()- 673ev [(size_t )(l * 6 + 2 )] 674-> get_profiling_info < 675 sycl::info::event_profiling::command_start > ()) / 6761000000.0f ; 677d = (ev [(size_t )(l * 6 + 4 )] 678-> get_profiling_info < 679 sycl::info::event_profiling::command_end > ()- 680ev [(size_t )(l * 6 + 3 )] 681-> get_profiling_info < 682 sycl::info::event_profiling::command_start > ()) / 6831000000.0f ; 684e = (ev [(size_t )(l * 6 + 5 )] 685-> get_profiling_info < 686 sycl::info::event_profiling::command_end > ()- 687ev [(size_t )(l * 6 + 4 )] 688-> get_profiling_info < 689 sycl::info::event_profiling::command_start > ()) / 6901000000.0f ; 691t1 += a ;t2 += b ;t3 += c ;t4 += d ;t5 += e ; 692mixer_per_layer [(size_t )l ]= (double )c ;// prefix 3 IS the mixer: stages 0..2 693 } 694t [0 ]= t1 ; 695t [1 ]= t2 - t1 ; 696t [2 ]= t3 - t2 ; 697t [3 ]= t4 - t3 ; 698t [4 ]= t5 - t4 ; 699stage_ms .assign (t ,t + 5 ); 700return true; 701} 702catch (sycl::exception const & exc ) { 703 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 704 <<", line:" <<__LINE__ << std::endl ; 705 std::exit (1 ); 706} 707 708void session_graphs_free (SessionGraphs & gr ) { 709if (gr .execs ) { 710for (int64_t i = 0 ;i < gr .n ;++ i )delete (gr .execs [i ]); 711delete []gr .execs ; 712 } 713if (gr .posts ) { 714for (int64_t i = 0 ;i < gr .n ;++ i ) 715if (gr .posts [i ]!= nullptr )delete (gr .posts [i ]); 716delete []gr .posts ; 717 } 718if (gr .preA ) { 719for (int64_t i = 0 ;i < gr .n ;++ i ) 720if (gr .preA [i ]!= nullptr )delete (gr .preA [i ]); 721delete []gr .preA ; 722 } 723if (gr .preB ) { 724for (int64_t i = 0 ;i < gr .n ;++ i ) 725if (gr .preB [i ]!= nullptr )delete (gr .preB [i ]); 726delete []gr .preB ; 727 } 728for (int k = 0 ;k < 5 ;++ k ) { 729if (gr .preP [k ]== nullptr )continue ; 730for (int64_t i = 0 ;i < gr .n ;++ i ) 731if (gr .preP [k ][i ]!= nullptr )delete (gr .preP [k ][i ]); 732delete []gr .preP [k ]; 733gr .preP [k ]= nullptr ; 734 } 735gr .preA = nullptr ; 736gr .preB = nullptr ; 737gr .split_captured = false; 738gr .posts = nullptr ; 739gr .execs = nullptr ; 740gr .parts_dev = nullptr ; 741gr .n = 0 ; 742gr .captured = false; 743} 744 745bool SessionLoopScratch ::init (size_t parts_bytes_in , std::string & err )try { 746if (y_miss != nullptr || probe != nullptr ) { 747err = "SessionLoopScratch::init: already initialised" ; 748return false; 749 } 750parts_bytes = parts_bytes_in ; 751// MAPPED as well as pinned: the token graph's handoff kernel reads it through its device pointer. 752/* 753DPCT1048: The original value cudaHostAllocMapped is not meaningful in the 754migrated code and was removed or replaced with 0. You may need to check the 755migrated code. 756*/ 757/* 758DPCT1048: The original value cudaHostAllocPortable is not meaningful in 759the migrated code and was removed or replaced with 0. You may need to check 760the migrated code. 761*/ 762if (DPCT_CHECK_ERROR (y_miss = (float * )strata::host_malloc_polled ( 763parts_bytes , dpct::get_in_order_queue ()))!= 0 || y_miss == nullptr ) { 764err = "SessionLoopScratch: cudaHostAlloc for the pool's staging failed" ; 765return false; 766 } 767 std::memset (y_miss ,0 ,parts_bytes ); 768if (DPCT_CHECK_ERROR (probe = new sycl::event ())!= 0 ) { 769err = "SessionLoopScratch: cudaEventCreate failed" ; 770free (); 771return false; 772 } 773// **PIN THE HOST ONCE, NOT ONCE PER TOKEN.** `ExpertPool` builds its workers from `physical_cores(true)`, 774// which drops the first physical core so the host loop can spin without taking a worker's cycles - and 775// nothing in the pool can pin the host, so if this does not happen the spin is free to land on a worker's 776// core or its SMT sibling. The symptom is not an error: it is a CPU path at 26.9 GB/s where the same pool 777// runs at 36.32. It was being done and undone on EVERY token, which is a syscall pair on the critical path 778// for a property that wants to hold for the whole session. 779// The host's core is the pool's reserved one: the first physical core, or the last with --host-core last (F12). 780const int host_core = strata::kernels::cpu::planned_host_core (); 781if (host_core >=0 ) { 782pinned_core = strata::kernels::cpu::pin_current_thread (host_core ); 783pinned = pinned_core .valid ; 784 }else { 785const std::vector < int > cores = strata::kernels::cpu::physical_cores (false); 786if (!cores .empty ()) { 787pinned_core = strata::kernels::cpu::pin_current_thread (cores [0 ]); 788pinned = pinned_core .valid ; 789 } 790 } 791return true; 792} 793catch (sycl::exception const & exc ) { 794 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 795 <<", line:" <<__LINE__ << std::endl ; 796 std::exit (1 ); 797} 798 799void SessionLoopScratch ::free () { 800// Restores the caller's affinity on every path, including teardown: a library that silently leaves its 801// caller's thread nailed to one core is worse than one that never pinned at all. 802if (pinned ) { 803 strata::kernels::cpu::restore_thread_affinity (pinned_core ); 804pinned = false; 805pinned_core = {}; 806 } 807if (probe != nullptr ) { dpct::destroy_event (probe );probe = nullptr ; } 808if (y_miss != nullptr ) { 809 strata::host_free_polled (y_miss , dpct::get_in_order_queue ());y_miss = nullptr ; 810 } 811parts_bytes = 0 ; 812} 813 814bool session_loop (const ModelGeometry & g ,int64_t pos ,int32_t pos_base , 815SessionState & s ,SessionGraphs & gr ,PoolFn pool ,HitFn hits , 816void * user ,bool overlap ,void * stream , std::string & err , 817float * dump_layers ,SessionLoopScratch * scratch )try { 818if (!gr .captured || gr .n != g .n_layers ) {err = "session_loop: not captured" ;return false; } 819if (gr .parts_dev == nullptr ) {err = "session_loop: the graphs were captured without a parts buffer" ;return false; } 820if (s .db == nullptr ) {err = "session_loop: no doorbell; the loop has nothing to poll" ;return false; } 821 822 dpct::queue_ptr cs = strata::q_of (stream ); 823const int64_t k = s .k ; 824const size_t parts_bytes = (size_t )k * g .n_embd * 4 ; 825++ gr .calls_total ; 826 827// ================================ THE POSITION, WHICH THIS LOOP NEVER STAGED ================================ 828// 829// **EVERY TOKEN AFTER THE FIRST USED TO REPLAY POSITION 0.** The QSA layers read their per-token counts from 830// `st.step` and `st.pos_dev`, which are DEVICE buffers filled by an H2D copy captured INTO each graph. A 831// graph bakes the SOURCE POINTER, not the value - so the copy re-reads the pinned host buffers on every 832// replay, and those hold whatever was last written there. `session_capture` left them at position 0. 833// 834// `layer.hpp` documents the requirement this loop was missing: "The per-token staging every QSA layer's 835// captured H2D reads FROM. Must run before each replay: the graphs captured the SOURCE POINTER, not the 836// value, and that is exactly why the buffers are pinned and fixed." `session_replay` calls `stage_token`; 837// `session_loop` did not. **A single-token test cannot see a position that never advances** - which is why 838// the whole suite passed while a 20-token prompt rotated every token at position 0. 839stage_token (g ,pos ,pos_base ,s ); 840 841// ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).** 842// 843// Everything this loop needs on the host - the pinned staging for the pool's answer, the doorbell probe 844// event, and the host pin - lives in a `SessionLoopScratch` owned by the SESSION and passed in. It used to 845// be created here, once per token, and `cudaFreeHost` at the end of the call IMPLICITLY SYNCHRONISES THE 846// DEVICE, so every token finished with a device-wide sync that nothing had asked for. A comment here said 847// "allocated once"; once per token is not once. 848// 849// Passing `nullptr` keeps the old behaviour so existing callers and tests are unaffected: the loop builds a 850// local scratch and frees it on every exit path below, including the error returns. 851SessionLoopScratch local ; 852if (scratch == nullptr ) { 853if (!local .init (parts_bytes ,err ))return false; 854scratch = & local ; 855 } 856struct LocalFree { 857SessionLoopScratch * p ; 858 ~LocalFree () {if (p != nullptr )p -> free (); } 859 }local_free {scratch == & local ?& local :nullptr }; 860if (scratch -> parts_bytes != parts_bytes ) { 861err = "session_loop: the scratch was sized for a different k or n_embd" ; 862return false; 863 } 864 865// HOST-side staging for the pool's answer. It is copied to `gr.parts_dev` before the next launch, on the 866// same stream, so the ordering is the stream's and no captured node is needed for it. 867// 868// ---- **PINNED, BECAUSE A COPY FROM PAGEABLE MEMORY IS NOT ASYNCHRONOUS AT ALL.** 869// 870// `cudaMemcpyAsync` with a pageable source cannot DMA: the driver first memcpys the bytes into an internal 871// pinned bounce buffer, SYNCHRONOUSLY, on this thread, and only then enqueues the transfer. So the "async" 872// copy would be a blocking memcpy plus a driver round trip, on the critical path of all 48 layers. The 873// doorbell's `h_x_f` is `cudaHostAlloc(Mapped)` for exactly this reason and this buffer is the same kind of 874// object. 875float * y_miss = scratch -> y_miss ; 876 dpct::event_ptr probe = scratch -> probe ; 877 878// the first layer has no previous layer's experts: `y_miss` starts at zero, which is what "hits are empty 879// in this phase" means once every miss has been computed 880/* 881DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While 882the origin API might be synchronous, it depends on the type of operand 883memory, so you may need to call wait() on event return by memcpy API to 884ensure synchronization behavior. 885*/ 886cs -> memcpy (gr .parts_dev ,y_miss ,parts_bytes ); 887doorbell_reset (* s .db ); 888uint32_t expected = 0 ; 889 890// **`pre[0]` IS LAUNCHED BEFORE THE LOOP SO EVERY ITERATION HAS THE SAME SHAPE**: poll the ring that 891// `pre[l]` published, run the pool on it, combine, then start layer `l+1`'s `pre`. 892// 893// SLOT 0 OF THE DUMP IS THE INPUT, not a layer output. `s.R` holds the embedding broadcast to every stream 894// when this function is entered, which is the reference's `hc_init` node - so dumping it here is what splits 895// "the input to layer 0 is already wrong" from "layer 0 is wrong". 896if (dump_layers != nullptr ) { 897const size_t n = (size_t )g .hc * (size_t )g .n_embd ; 898/* 899DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 900While the origin API might be synchronous, it depends on the type of 901operand memory, so you may need to call wait() on event return by memcpy 902API to ensure synchronization behavior. 903*/ 904const dpct::err0 de = 905DPCT_CHECK_ERROR (cs -> memcpy (dump_layers ,s .R ,n * sizeof (float ))); 906/* 907DPCT1000: Error handling if-stmt was detected but could not be 908rewritten. 909*/ 910if (de != 0 ) { 911/* 912DPCT1009: SYCL reports errors using exceptions and does not use 913error codes. Please replace the "get_error_string_dummy(...)" with a 914real error-handling function. 915*/ 916/* 917DPCT1001: The statement could not be removed. 918*/ 919err = "session_loop: dump the input residual: " + 920 std::string (dpct::get_error_string_dummy (de )); 921return false; 922 } 923 } 924 { 925const auto t0 = std::chrono::steady_clock::now (); 926const dpct::err0 le = 927DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .execs [0 ])); 928/* 929DPCT1000: Error handling if-stmt was detected but could not be 930rewritten. 931*/ 932if (le != 0 ) { 933/* 934DPCT1009: SYCL reports errors using exceptions and does not use 935error codes. Please replace the "get_error_string_dummy(...)" with a 936real error-handling function. 937*/ 938/* 939DPCT1001: The statement could not be removed. 940*/ 941err = "session_loop: launch pre[0]: " + 942 std::string (dpct::get_error_string_dummy (le )); 943return false; 944 } 945 dpct::sync_barrier (probe ,cs ); 946 (void )t0 ; 947 } 948 949for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 950const auto t_launch = std::chrono::steady_clock::now (); 951 952// ---- poll for the ring. **THE DRIVER CALL IS NOW A FALLBACK, NOT THE MECHANISM.** 953const uint32_t want = ++ expected ; 954bool rang = false; 955bool mid_graph = false; 956// VOLATILE, because the device writes this through mapped pinned memory and a cached host line would 957// never see it. Read through a volatile pointer so the compiler re-issues the load every iteration - 958// otherwise this whole spin collapses into `while (true) { }`. 959volatile uint32_t * const seq = s .db -> h_seq ; 960for (;;) { 961// **THE PER-ITERATION DRIVER CALL IS REQUIRED, AND THREE EXPERIMENTS NOW SAY SO.** Round 287 962// throttled this to one call in 64 and broke tests 51 and 56; adding `__threadfence_system()` to 963// `doorbell_ring_kernel` and a volatile read here, then throttling, broke them again. So the call 964// is not merely flushing submission (round 195's reading) and it is not a missing fence either: on 965// this driver, the device's write to mapped pinned memory becomes host-visible only when the driver 966// is entered. The fence and the volatile read are kept because they are correct and cost nothing - 967// without them the ring's ordering against `x_f`/`ids`/`weights` is unstated - but they do not 968// remove the need for the call, and nothing here should be read as claiming they do. 969const dpct::err0 q = dpct::sycl_event_query (probe ); 970if (!rang && * seq >=want ) { 971rang = true; 972mid_graph = (q != 0 ); 973 } 974if (q == 0 )break ;// the graph has ended 975if (q != 1 ) { 976/* 977DPCT1009: SYCL reports errors using exceptions and does not 978use error codes. Please replace the 979"get_error_string_dummy(...)" with a real error-handling 980function. 981*/ 982err = "session_loop: query at layer " + std::to_string (l )+ 983": " + dpct::get_error_string_dummy (q ); 984return false; 985 } 986if (rang )break ;// rung, and the graph is still running: the overlap 987STRATA_SPIN_PAUSE (); 988 } 989if (mid_graph )++ gr .rings_mid_graph ; 990// the window, from just before the launch to the instant the ring was seen 991const auto t_ring = std::chrono::steady_clock::now (); 992gr .ms_to_ring += std::chrono::duration < double , std::milli > (t_ring - t_launch ).count (); 993if (!rang ) { 994// The graph finished without the ring being observed. `h_seq` is monotonic, so this is not a race 995// - it means the ring never happened, which is the failure round 199 found in a captured event. 996err = "session_loop: layer " + std::to_string (l )+ " ended without ringing" ; 997return false; 998 } 999 1000// the ring can arrive before its payload on some GPUs (elementwise.hpp): wait until it is whole, or the 1001// pool reads a partly stale payload and the answer is garbage (the A770's "!!!!") 1002if (!strata::kernels::doorbell_wait_payload (s .db -> h_seq ,s .db -> h_x_f ,g .n_embd ,s .db -> h_ids , 1003s .db -> h_weights ,k , (uint32_t )want )) { 1004err = "session_loop: layer " + std::to_string (l )+ " rang but its payload never arrived whole" ; 1005return false; 1006 } 1007 1008// ---- **THE GPU'S HALF GOES FIRST, SO IT RUNS WHILE THE CPU DOES ITS HALF.** `Launch` only enqueues: 1009// the quantize and the grouped expert kernel land on `main_cs` and the GPU starts on them immediately, 1010// while the host is still inside `pool` below. Nothing here waits. 1011if (hits != nullptr )hits (user ,cs ,HitPhase ::Launch ,s .db -> h_ids ,k ); 1012 1013// ---- the pool, on the bytes the doorbell published. **THESE ARE LAYER `l`'s EXPERTS.** 1014if (pool != nullptr )pool (user ,s .db -> h_x_f ,s .db -> h_ids ,s .db -> h_weights ,g .n_embd ,k ,y_miss ); 1015 1016// ---- **AND THEY ARE COMBINED BY LAYER `l`, NOT BY LAYER `l+1`.** 1017// 1018// This copy and the launch below are the whole of the L100 fix. `moe_combine` multiplies `parts` by 1019// THIS layer's `b.weights`, so `parts` must be THIS layer's expert outputs; the previous form copied 1020// the pool's answer into `parts_dev` for the NEXT layer, which computed 1021// `sum_j w_{l+1}[j] * expert_{ids_l,j}(x_l)` - both the selection and the input one layer stale while 1022// the weights were current. It produced finite, fluent, deterministic tokens that were not the 1023// model's, and no timing test could see it. 1024/* 1025DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 1026While the origin API might be synchronous, it depends on the type of 1027operand memory, so you may need to call wait() on event return by memcpy 1028API to ensure synchronization behavior. 1029*/ 1030cs -> memcpy (gr .parts_dev ,y_miss ,parts_bytes ); 1031// ---- **AND THEN THE COMBINE.** Stream-ordered after the copy above, so `hit_out` is added to misses 1032// that are already in `parts`, and before `post[l]`, whose `moe_combine` reads the sum. A no-op when 1033// there is no VRAM tier or nothing is resident, which is every layer until the cache warms. 1034if (hits != nullptr )hits (user ,cs ,HitPhase ::Combine ,nullptr ,0 ); 1035 { 1036const dpct::err0 pe = 1037DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .posts [l ])); 1038/* 1039DPCT1000: Error handling if-stmt was detected but could not be 1040rewritten. 1041*/ 1042if (pe != 0 ) { 1043/* 1044DPCT1009: SYCL reports errors using exceptions and does not 1045use error codes. Please replace the 1046"get_error_string_dummy(...)" with a real error-handling 1047function. 1048*/ 1049/* 1050DPCT1001: The statement could not be removed. 1051*/ 1052err = "session_loop: launch post[" + std::to_string (l )+ 1053"]: " + dpct::get_error_string_dummy (pe ); 1054return false; 1055 } 1056 } 1057// ---- the C1 oracle. `s.R` now holds layer `l`'s residual and keeps it until `post[l+1]` writes it, so 1058// a copy enqueued HERE - after `post[l]`, before `pre[l+1]` - is ordered correctly by the stream alone. 1059// Nothing is synchronised: the loop's existing final sync is what completes these. See the note on 1060// `dump_layers` in session.hpp for why this is an enqueue and not a read. 1061if (dump_layers != nullptr ) { 1062const size_t n = (size_t )g .hc * (size_t )g .n_embd ; 1063/* 1064DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 1065API. While the origin API might be synchronous, it depends on the 1066type of operand memory, so you may need to call wait() on event 1067return by memcpy API to ensure synchronization behavior. 1068*/ 1069const dpct::err0 de = DPCT_CHECK_ERROR (cs -> memcpy ( 1070dump_layers + (size_t )(l + 1 )* n ,s .R ,n * sizeof (float ))); 1071/* 1072DPCT1000: Error handling if-stmt was detected but could not be 1073rewritten. 1074*/ 1075if (de != 0 ) { 1076/* 1077DPCT1009: SYCL reports errors using exceptions and does not 1078use error codes. Please replace the 1079"get_error_string_dummy(...)" with a real error-handling 1080function. 1081*/ 1082/* 1083DPCT1001: The statement could not be removed. 1084*/ 1085err = "session_loop: dump layer " + std::to_string (l )+ ": " + 1086 dpct::get_error_string_dummy (de ); 1087return false; 1088 } 1089 } 1090if (!overlap ) { 1091// THE COMPARISON ARM. The same sequence with the pipeline removed: the CPU does not start until the 1092// layer is over, so nothing overlaps and the difference is attributable to the doorbell alone. 1093if (DPCT_CHECK_ERROR (cs -> wait ())!= 0 ) { 1094err = "session_loop: sync at layer " + std::to_string (l ); 1095return false; 1096 } 1097 } 1098// ---- and layer l+1's routing starts. `pre[l+1]` touches none of the buffers `post[l]` reads, because 1099// the two are ordered on one stream and `pre[l+1]`'s first use of `bb.mixed`/`bb.inject` is its own 1100// `gr_read`, which comes after `post[l]` has consumed them. 1101if (l + 1 < g .n_layers ) { 1102const dpct::err0 ne = 1103DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* gr .execs [l + 1 ])); 1104/* 1105DPCT1000: Error handling if-stmt was detected but could not be 1106rewritten. 1107*/ 1108if (ne != 0 ) { 1109/* 1110DPCT1009: SYCL reports errors using exceptions and does not 1111use error codes. Please replace the 1112"get_error_string_dummy(...)" with a real error-handling 1113function. 1114*/ 1115/* 1116DPCT1001: The statement could not be removed. 1117*/ 1118err = "session_loop: launch pre[" + std::to_string (l + 1 )+ 1119"]: " + dpct::get_error_string_dummy (ne ); 1120return false; 1121 } 1122 dpct::sync_barrier (probe ,cs ); 1123 } 1124// ---- **THE SECOND HALF OF THE ROUND TRIP, AND THE HALF NOTHING WAS MEASURING.** 1125// 1126// From seeing the ring to having queued the next `pre`. Everything in here is a driver call, and on 1127// the token path the GPU has nothing left to run for most of it - `pre[l]` has already rung, and 1128// `post[l]` cannot start until this code launches it. So this interval is GPU-idle time, and it is 1129// the number that decides whether the fix is R2.4 (fewer launches per layer) or a faster kernel. 1130// 1131// It INCLUDES the `!overlap` synchronisation when that arm is selected, which is deliberate: that arm 1132// exists to show what the pipeline is worth, and hiding its cost here would defeat the comparison. 1133gr .ms_host += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t_ring ).count (); 1134 } 1135if (DPCT_CHECK_ERROR (cs -> wait ())!= 0 ) { 1136err = "session_loop: final sync" ;return false; 1137 } 1138return true; 1139} 1140catch (sycl::exception const & exc ) { 1141 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1142 <<", line:" <<__LINE__ << std::endl ; 1143 std::exit (1 ); 1144} 1145 1146bool session_token (const WeightTable & tables ,const ModelGeometry & g , 1147int64_t pos ,int32_t pos_base ,SessionState & s , 1148const float * parts ,void * stream ,bool sync_every_layer , 1149 std::string & err )try { 1150 dpct::queue_ptr cs = strata::q_of (stream ); 1151int64_t qsa_index = 0 ; 1152int64_t gdn_index = 0 ; 1153 1154for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 1155// THE GDN LAYERS EACH GET THEIR OWN STATE, and `GdnBuffers` carries it - so the session points the 1156// shared scratch at the right slice before each call. Sharing one state across 36 layers would make 1157// every layer start from the previous layer's recurrence, which produces a perfectly finite answer. 1158if (!is_qsa_layer (g ,l )) { 1159s .gdn .state = s .gdn_state + (size_t )gdn_index * gdn_state_floats (g ); 1160s .gdn .conv_state = s .gdn .state + (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 1161++ gdn_index ; 1162 } 1163 1164err .clear (); 1165const bool ok = is_qsa_layer (g ,l ) 1166 ?block_layer (tables ,g ,l ,pos ,pos_base ,s .gdn ,s .qsa_states [qsa_index ],s .qsa_bufs ,s .moe ,s .k , 1167s .block ,parts ,stream ,err ,nullptr ,s .ple .ready () ?& s .ple :nullptr ) 1168 :block_layer (tables ,g ,l ,pos ,pos_base ,s .gdn ,s .qsa_states [0 ],s .qsa_bufs ,s .moe ,s .k , 1169s .block ,parts ,stream ,err ,nullptr ,s .ple .ready () ?& s .ple :nullptr ); 1170if (!ok ) { 1171err = "layer " + std::to_string (l )+ ": " + err ; 1172return false; 1173 } 1174if (is_qsa_layer (g ,l ))++ qsa_index ; 1175 1176if (sync_every_layer ) { 1177// THE DEBUG MODE, and its cost is the point: it is a real synchronisation after every layer, which 1178// P2.X3 forbids in the fast path. It exists to turn an ASYNCHRONOUS error - a kernel reading a 1179// buffer a later layer wrote, or an out-of-range launch - into a failure AT THE LAYER THAT CAUSED 1180// IT, instead of a wrong number 40 layers later or at the end of the token. 1181const dpct::err0 e = DPCT_CHECK_ERROR (cs -> wait ()); 1182/* 1183DPCT1000: Error handling if-stmt was detected but could not be 1184rewritten. 1185*/ 1186if (e != 0 ) { 1187/* 1188DPCT1009: SYCL reports errors using exceptions and does not 1189use error codes. Please replace the 1190"get_error_string_dummy(...)" with a real error-handling 1191function. 1192*/ 1193/* 1194DPCT1001: The statement could not be removed. 1195*/ 1196err = "layer " + std::to_string (l )+ ": " + 1197 dpct::get_error_string_dummy (e ); 1198return false; 1199 } 1200 } 1201 } 1202return true; 1203} 1204catch (sycl::exception const & exc ) { 1205 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1206 <<", line:" <<__LINE__ << std::endl ; 1207 std::exit (1 ); 1208} 1209 1210}// namespace strata::core 1211 1212namespace strata::core { 1213 1214bool session_capture_token (const WeightTable & tables ,const ModelGeometry & g , 1215SessionState & s ,float * parts_dev , 1216const float * y_miss_host ,size_t parts_bytes , 1217TokenGraph & tg , std::string & err , 1218const TokenHits * hits )try { 1219if (hits != nullptr && !hits -> on ()) {err = "session_capture_token: incomplete hit configuration" ;return false; } 1220if (tg .captured )return true; 1221if (s .db == nullptr || s .db -> d_flag == nullptr || s .db -> d_seq == nullptr ) { 1222err = "session_capture_token: the doorbell has no flag" ; 1223return false; 1224 } 1225if (parts_dev == nullptr || y_miss_host == nullptr || parts_bytes == 0 ) { 1226err = "session_capture_token: parts buffers are required" ; 1227return false; 1228 } 1229float * y_dev = nullptr ; 1230if (DPCT_CHECK_ERROR (* (void ** )& y_dev = 1231 (float * )const_cast < float *> (y_miss_host ))!= 0 || 1232 !y_dev ) { 1233err = "session_capture_token: the parts staging is not mapped pinned memory" ; 1234return false; 1235 } 1236 dpct::queue_ptr cs = & dpct::get_in_order_queue (); 1237if (DPCT_CHECK_ERROR (cs = dpct::get_current_device ().create_queue (true))!= 12380 ) { 1239err = "session_capture_token: stream create failed" ;return false; 1240 } 1241if (DPCT_CHECK_ERROR (dpct::experimental::begin_recording (cs ))!= 0 ) { 1242 dpct::get_current_device ().destroy_queue (cs ); 1243err = "session_capture_token: begin capture failed" ; 1244return false; 1245 } 1246int64_t qsa_index = 0 ; 1247bool ok = true; 1248for (int64_t l = 0 ;l < g .n_layers && ok ;++ l ) { 1249gdn_point_at (g ,l ,s ); 1250const bool qsa = is_qsa_layer (g ,l ); 1251QsaState & qst = qsa ?s .qsa_states [qsa_index ] :s .qsa_states [0 ]; 1252err .clear (); 1253ok = block_layer_pre (tables ,g ,l ,0 ,0 ,s .gdn ,qst ,s .qsa_bufs ,s .moe ,s .k ,s .block , (void * )cs ,err ,s .db , 1254s .ple .ready () ?& s .ple :nullptr ); 1255if (!ok ) {err = "session_capture_token: pre layer " + std::to_string (l )+ ": " + err ;break ; } 1256if (hits != nullptr ) { 1257// After the ring (and the shared expert): the GPU's experts run while the CPU computes the misses. 1258 strata::kernels::moe_hit_select (s .moe .ids ,hits -> d_res + l * hits -> n_expert , (int )s .k , 1259 (int )hits -> n_expert ,hits -> d_slot ,hits -> d_dst ,hits -> d_count , (void * )cs ); 1260 strata::kernels::quantize_q8_0_scaled (s .block .mixed ,hits -> x_q8 ,hits -> x_scale ,g .n_embd , (void * )cs ); 1261 strata::kernels::moe_hit_grouped_s2_dev (hits -> cache_base ,hits -> d_slot ,hits -> d_dst ,hits -> d_count ,s .k , 1262hits -> blob ,hits -> x_q8 ,hits -> scratch ,hits -> hit_out , (void * )cs , 1263hits -> x_scale ); 1264 } 1265 strata::kernels::doorbell_wait (s .db -> d_flag ,s .db -> d_seq , (void * )cs ); 1266// A kernel, not a memcpy node: a copy-engine node splits the WDDM submission (measured 67 flushes/token). 1267 strata::kernels::copy_from_mapped (parts_dev ,y_dev , (int64_t ) (parts_bytes /sizeof (float )), (void * )cs ); 1268if (hits != nullptr ) 1269 strata::kernels::moe_hit_add (parts_dev ,hits -> hit_out ,hits -> d_dst ,hits -> d_count ,s .k ,g .n_embd , (void * )cs ); 1270ok = block_layer_post (tables ,g ,l ,s .k ,s .moe ,s .block ,parts_dev , (void * )cs ,err ); 1271if (!ok ) {err = "session_capture_token: post layer " + std::to_string (l )+ ": " + err ;break ; } 1272if (qsa )++ qsa_index ; 1273 } 1274 dpct::experimental::command_graph_ptr graph = nullptr ; 1275const dpct::err0 ce = 1276DPCT_CHECK_ERROR (dpct::experimental::end_recording (cs ,& graph )); 1277 dpct::get_current_device ().destroy_queue (cs ); 1278if (!ok ) {if (graph )delete (graph );return false; } 1279/* 1280DPCT1000: Error handling if-stmt was detected but could not be 1281rewritten. 1282*/ 1283if (ce != 0 ) { 1284/* 1285DPCT1009: SYCL reports errors using exceptions and does not use 1286error codes. Please replace the "get_error_string_dummy(...)" with a 1287real error-handling function. 1288*/ 1289/* 1290DPCT1001: The statement could not be removed. 1291*/ 1292err = std::string ("session_capture_token: end capture: " )+ 1293 dpct::get_error_string_dummy (ce ); 1294return false; 1295 } 1296const dpct::err0 ie = DPCT_CHECK_ERROR ( 1297tg .exec = new sycl::ext::oneapi::experimental::command_graph < 1298 sycl::ext::oneapi::experimental::graph_state::executable > ( 1299graph -> finalize ())); 1300delete (graph ); 1301/* 1302DPCT1000: Error handling if-stmt was detected but could not be 1303rewritten. 1304*/ 1305if (ie != 0 ) { 1306/* 1307DPCT1009: SYCL reports errors using exceptions and does not use 1308error codes. Please replace the "get_error_string_dummy(...)" with a 1309real error-handling function. 1310*/ 1311/* 1312DPCT1001: The statement could not be removed. 1313*/ 1314err = std::string ("session_capture_token: instantiate: " )+ 1315 dpct::get_error_string_dummy (ie ); 1316return false; 1317 } 1318tg .captured = true; 1319tg .n_layers = g .n_layers ; 1320tg .y_src = y_miss_host ; 1321tg .parts_bytes = parts_bytes ; 1322return true; 1323} 1324catch (sycl::exception const & exc ) { 1325 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1326 <<", line:" <<__LINE__ << std::endl ; 1327 std::exit (1 ); 1328} 1329 1330bool session_run_token (const ModelGeometry & g ,int64_t pos ,int32_t pos_base , 1331SessionState & s ,TokenGraph & tg ,PoolFn pool ,void * user , 1332float * y_miss_host ,void * stream , std::string & err )try { 1333if (!tg .captured ) {err = "session_run_token: not captured" ;return false; } 1334if (y_miss_host != tg .y_src ) {err = "session_run_token: the staging buffer is not the captured one" ;return false; } 1335 dpct::queue_ptr cs = strata::q_of (stream ); 1336++ tg .calls ; 1337stage_token (g ,pos ,pos_base ,s ); 1338doorbell_reset (* s .db ); 1339const dpct::err0 le = DPCT_CHECK_ERROR (cs -> ext_oneapi_graph (* tg .exec )); 1340/* 1341DPCT1009: SYCL reports errors using exceptions and does not use error 1342codes. Please replace the "get_error_string_dummy(...)" with a real 1343error-handling function. 1344*/ 1345/* 1346DPCT1001: The statement could not be removed. 1347*/ 1348/* 1349DPCT1000: Error handling if-stmt was detected but could not be 1350rewritten. 1351*/ 1352if (le != 0 ) { 1353err = std::string ("session_run_token: launch: " )+ 1354 dpct::get_error_string_dummy (le ); 1355return false; 1356 } 1357 (void )DPCT_CHECK_ERROR ( 1358 (cs -> ext_oneapi_empty ()));// one flush, so WDDM submits the graph now 1359static const int flush_us = [] { 1360const char * e = std::getenv ("STRATA_TG_FLUSH_US" ); 1361return e ? std::atoi (e ) :2000 ;// 24 Sep: 0 flushes run as fast as 5 us ones; this only notices faults 1362 }(); 1363volatile uint32_t * const seq = s .db -> h_seq ; 1364volatile uint32_t * const flag = s .db -> h_flag ; 1365using Clock = std::chrono::steady_clock ; 1366for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 1367const uint32_t want = (uint32_t ) (l + 1 ); 1368const auto t0 = Clock ::now (); 1369auto last_flush = t0 ; 1370uint32_t spins = 0 ; 1371progress_at ("token: waiting for the GPU to reach layer" ,l ); 1372while (* seq < want ) { 1373STRATA_SPIN_PAUSE (); 1374if ((++ spins & 1023u )!= 0 )continue ; 1375const auto now = Clock ::now (); 1376if (now - last_flush > std::chrono::microseconds (flush_us )) { 1377// A slow ring: flush the submission queue once more, and notice a fault or a finished graph. 1378last_flush = now ; 1379++ tg .flushes ; 1380// SYCL port fix: cudaStreamQuery's answer (0 finished, 1 still running) was lost in the migration 1381// (DPCT_CHECK_ERROR of ext_oneapi_empty() is always 0), so ANY wait over 2 ms was reported as 1382// "graph finished". Layers whose GPU time exceeds 2 ms (host-mirrored experts read over PCIe) failed that way. 1383const dpct::err0 q = cs -> ext_oneapi_empty () ?0 :1 ; 1384if (q != 1 && * seq < want ) { 1385err = "session_run_token: layer " + std::to_string (l )+ 1386" never rang (" + 1387/* 1388DPCT1009: SYCL reports errors using exceptions and 1389does not use error codes. Please replace the 1390"get_error_string_dummy(...)" with a real 1391error-handling function. 1392*/ 1393 (q == 0 1394 ? std::string ("graph finished" ) 1395 : std::string (dpct::get_error_string_dummy (q )))+ 1396")" ; 1397return false; 1398 } 1399 } 1400if (now - t0 > std::chrono::seconds (20 )) { 1401err = "session_run_token: timed out waiting for layer " + std::to_string (l ); 1402return false; 1403 } 1404 } 1405const auto t1 = Clock ::now (); 1406progress_at ("token: the CPU experts of layer" ,l ); 1407if (pool != nullptr )pool (user ,s .db -> h_x_f ,s .db -> h_ids ,s .db -> h_weights ,g .n_embd ,s .k ,y_miss_host ); 1408 std::atomic_thread_fence (std::memory_order_seq_cst ); 1409_mm_sfence (); 1410* flag = want ; 1411const auto t2 = Clock ::now (); 1412tg .ms_wait += std::chrono::duration < double , std::milli > (t1 - t0 ).count (); 1413tg .ms_pool += std::chrono::duration < double , std::milli > (t2 - t1 ).count (); 1414 } 1415progress_at ("token: waiting for the GPU to finish the token" ); 1416const dpct::err0 se = DPCT_CHECK_ERROR (cs -> wait ()); 1417/* 1418DPCT1009: SYCL reports errors using exceptions and does not use error 1419codes. Please replace the "get_error_string_dummy(...)" with a real 1420error-handling function. 1421*/ 1422/* 1423DPCT1001: The statement could not be removed. 1424*/ 1425/* 1426DPCT1000: Error handling if-stmt was detected but could not be 1427rewritten. 1428*/ 1429if (se != 0 ) { 1430err = std::string ("session_run_token: " )+ 1431 dpct::get_error_string_dummy (se ); 1432return false; 1433 } 1434progress_at ("decode" ); 1435progress_beat (); 1436return true; 1437} 1438catch (sycl::exception const & exc ) { 1439 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1440 <<", line:" <<__LINE__ << std::endl ; 1441 std::exit (1 ); 1442} 1443 1444void token_graph_free (TokenGraph & tg ) { 1445if (tg .exec )delete (tg .exec ); 1446tg = TokenGraph {}; 1447} 1448 1449}// namespace strata::core