okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7fcf5307c
main
1// src/core/session.cpp - one token through all 48 layers. See the header for why the graphs are per-layer. 2#include "strata/core/session.hpp" 3#include "strata/core/pin_budget.hpp" 4#include "strata/kernels/mrope.hpp" 5#include "strata/core/progress.hpp" 6 7#include "strata/kernels/qsa.hpp" 8#include "strata/kernels/elementwise.hpp" 9#include "strata/kernels/quantize_act.hpp" 10#include "strata/kernels/s2_expert_grouped.hpp" 11#include "strata/kernels/cpu/pool.hpp" 12#include "strata/platform/aux_cpus.hpp" 13#include "strata/kernels/ngram.hpp" 14 15#include <cuda_runtime.h> 16 17#include <atomic> 18#include <chrono> 19#include <cstdio> 20#include <cstdlib> 21#include <cstring> 22#include <vector> 23 24// The doorbell spin. x86 pauses, aarch64 yields (include/strata/platform/cpu_relax.hpp). 25#include "strata/platform/cpu_relax.hpp" 26#define STRATA_SPIN_PAUSE () strata_cpu_pause() 27 28namespace strata::core { 29namespace { 30 31constexpr uint64_t SESSION_STATE_ALIGN = 256 ; 32 33uint64_t align_up (uint64_t n ,uint64_t a ) {return (n + a - 1 ) /a * a ; } 34 35/// The floats one GDN layer's recurrent + conv state needs. `gdn_buffers_bytes` carves them for ONE layer and 36/// `GdnBuffers::state`/`conv_state` point INTO that carve, so a session with 36 GDN layers has to give each one 37/// its own - they cannot share, because the recurrence is the whole point. 38uint64_t gdn_state_floats (const ModelGeometry & g ) { 39return (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 40 (uint64_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 41} 42 43}// namespace 44 45/// `NG_HIST` rows of `hc_dim` floats: the PLE conv's history, which is the ONLY PLE state that lives in the 46/// session arena. The table and the weights are model-level and the caller owns them. 47static uint64_t ple_hist_bytes () { 48return (uint64_t ) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM * sizeof (float ); 49} 50 51uint64_t session_bytes (const ModelGeometry & g ,int64_t max_cells ,int64_t k ,int64_t layer_lo ,int64_t layer_hi ) { 52if (layer_hi < 0 || layer_hi > g .n_layers )layer_hi = g .n_layers ; 53if (layer_lo < 0 )layer_lo = 0 ; 54// QSA layers are `l % interval == interval-1`, so exactly `bound / interval` of them live below `bound` 55const int64_t I = std::max < int64_t > (g .qsa_interval ,1 ); 56const int64_t q_lo = layer_lo /I ,q_hi = layer_hi /I ; 57const int64_t q_n = std::max < int64_t > (q_hi - q_lo ,g .n_qsa_layers ()> 0 ?1 :0 ); 58const int64_t gdn_n = std::max < int64_t > ((layer_hi - layer_lo )- std::max < int64_t > (q_hi - q_lo ,0 ),0 ); 59uint64_t n = 0 ; 60n += gdn_buffers_bytes (g ); 61n += (uint64_t )gdn_n * gdn_state_floats (g )* 4 ; 62// One QSA state carries the RoPE table; the others borrow it (P7: 64 MiB per layer at 262K). 63if (g .n_qsa_layers ()> 0 ) 64n += qsa_state_bytes (g ,max_cells , true)+ (uint64_t ) (q_n - 1 )* qsa_state_bytes (g ,max_cells , false); 65n += qsa_buffers_bytes (g ,max_cells ); 66n += moe_buffers_bytes (g ,k ); 67n += block_buffers_bytes (g ); 68n += ple_hist_bytes ();// the PLE's NG_HIST normalized history rows 69return align_up (n ,SESSION_STATE_ALIGN )+ 4096 ; 70} 71 72uint64_t session_init (const ModelGeometry & g ,int64_t max_cells ,int64_t k ,void * base ,SessionState & s , 73int64_t layer_lo ,int64_t layer_hi ) { 74if (layer_hi < 0 || layer_hi > g .n_layers )layer_hi = g .n_layers ; 75if (layer_lo < 0 )layer_lo = 0 ; 76uint8_t * p = (uint8_t * )base ; 77uint64_t used = 0 ; 78auto take = [& ](uint64_t bytes ) { 79uint8_t * r = p + used ; 80used = align_up (used + bytes ,SESSION_STATE_ALIGN ); 81return r ; 82 }; 83 84s .max_cells = max_cells ; 85s .k = k ; 86s .layer_lo = layer_lo ; 87s .layer_hi = layer_hi ; 88const int64_t I = std::max < int64_t > (g .qsa_interval ,1 ); 89const int64_t q_n_range = layer_hi /I - layer_lo /I ; 90s .qsa_ord0 = layer_lo /I ; 91s .qsa_alloc = std::max < int64_t > (q_n_range ,g .n_qsa_layers ()> 0 ?1 :0 ); 92s .gdn_ord0 = layer_lo - layer_lo /I ; 93s .gdn_alloc = std::max < int64_t > ((layer_hi - layer_lo )- q_n_range ,0 ); 94 95gdn_buffers_init (g ,take (gdn_buffers_bytes (g )),s .gdn ); 96s .gdn_state = (float * )take ((uint64_t )s .gdn_alloc * gdn_state_floats (g )* 4 ); 97 98// the QSA states are separate allocations carved from one arena, because `QsaState` is a struct of 99// pointers and `qsa_state_init` writes them - a contiguous array would need the arena to be laid out the 100// same way, which is a coupling with nothing to gain. Only the range's ordinals are initialized; the 101// rest stay value-initialized nulls. The FIRST ALLOCATED one (the session's primary, ordinal qsa_ord0) 102// owns the RoPE table that the others - and the prefill staging identity, and the MTP drafter - borrow. 103const uint64_t first = qsa_state_bytes (g ,max_cells , true),rest = qsa_state_bytes (g ,max_cells , false); 104s .qsa_state_arena = take (g .n_qsa_layers ()> 0 ?first + (uint64_t ) (s .qsa_alloc - 1 )* rest :0 ); 105s .qsa_states = new QsaState [(size_t )g .n_qsa_layers ()](); 106s .qsa_buf_arena = take (qsa_buffers_bytes (g ,max_cells )); 107 108uint8_t * qp = (uint8_t * )s .qsa_state_arena ; 109// a layer whose pinned RAM could not be had (KV streaming's host copy) is half-built: going on would have the 110// attention read null host pointers at the first request ("illegal memory access"), so the session fails here 111for (int64_t j = 0 ;j < s .qsa_alloc ;++ j ) 112if (qsa_state_init (g ,max_cells ,qp + (j == 0 ?0 :first + (uint64_t ) (j - 1 )* rest ), 113s .qsa_states [s .qsa_ord0 + j ],j == 0 ?nullptr :& s .qsa_states [s .qsa_ord0 ])== 0 ) 114return 0 ; 115qsa_buffers_init (g ,max_cells ,s .qsa_buf_arena ,s .qsa_bufs ); 116 117s .moe_arena = take (moe_buffers_bytes (g ,k )); 118moe_buffers_init (g ,k ,s .moe_arena ,s .moe ); 119s .block_arena = take (block_buffers_bytes (g )); 120block_buffers_init (g ,s .block_arena ,s .block ); 121// THE PLE HISTORY: NG_HIST rows of hc_dim floats, row-fastest. Sequence state, carved here and zeroed by 122// `session_zero`; it survives every token, which is the whole point of a conv history. 123s .ple_hist = (float * )take (ple_hist_bytes ()); 124s .R = s .block .R ; 125return used ; 126} 127 128void session_release (SessionState & s ) { 129for (int64_t j = 0 ;s .qsa_states != nullptr && j < s .qsa_alloc ;++ j ) 130if (s .qsa_states [j ].owns_rope ) { 131 strata::kernels::rope_table_release (s .qsa_states [j ].cos_tab ); 132s .qsa_states [j ].owns_rope = false; 133 } 134} 135 136#if defined(STRATA_GPU_METAL ) 137}// namespace strata::core 138namespace strata::metal_engine { 139void window_reset (const strata::core::SessionState * ss );// metal/src/engine/window.cpp: that session's running state (the main one or a batch slot's) back to a new sequence's 140}// namespace strata::metal_engine 141namespace strata::core { 142#endif 143 144void session_zero (SessionState & s ,const ModelGeometry & g ,const float * R_init ,void * stream ) { 145session_zero_running (s ,g ,R_init ,stream , false); 146} 147 148void session_zero_running (SessionState & s ,const ModelGeometry & g ,const float * R_init ,void * stream ,bool keep_kv ) { 149#if defined(STRATA_GPU_METAL ) 150// the running state lives in the Metal decode window; the session's own device buffers are not read there 151 (void )g ; (void )R_init ; (void )stream ; 152 strata::metal_engine::window_reset (& s ); 153s .ple_prev [0 ]= -1 ; 154s .ple_prev [1 ]= -1 ; 155s .ple_token = -1 ; 156return ; 157#endif 158cudaStream_t cs = (cudaStream_t )stream ; 159// the residual: `hc` copies of the one vector a caller hands in. A real sequence's first token is the 160// embedding broadcast to every stream, which is the reference's own initial condition. 161if (R_init != nullptr ) { 162for (int64_t c = 0 ;c < g .hc ;++ c ) 163cudaMemcpyAsync (s .block .R + (size_t )c * g .n_embd ,R_init , (size_t )g .n_embd * 4 , 164cudaMemcpyDeviceToDevice ,cs ); 165 }else { 166cudaMemsetAsync (s .block .R ,0 , (size_t )g .hc * g .n_embd * 4 ,cs ); 167 } 168// every owned GDN layer's recurrence and conv history 169cudaMemsetAsync (s .gdn_state ,0 , (size_t )s .gdn_alloc * gdn_state_floats (g )* 4 ,cs ); 170// and every owned QSA layer's cache and indexer 171if (!keep_kv ) 172for (int64_t j = 0 ;j < s .qsa_alloc ;++ j )qsa_state_zero (s .qsa_states [s .qsa_ord0 + j ],g ,stream ); 173// **AND THE PLE'S CONV HISTORY AND TOKEN WINDOW.** A sequence that started with a warm history would 174// convolve over rows belonging to a different sequence - the conv reads NG_HIST previous NORMALIZED rows, 175// so a stale one is a real contribution and not a zero. The token window resets to `NG_HIST`-many nulls 176// for the same reason: `ngram_rows` treats a missing predecessor as the EOS cut, which is what a sequence 177// boundary IS. 178cudaMemsetAsync (s .ple_hist ,0 , (size_t )ple_hist_bytes (),cs ); 179s .ple_prev [0 ]= -1 ; 180s .ple_prev [1 ]= -1 ; 181s .ple_token = -1 ; 182} 183 184/// Sets `s.gdn.state`/`conv_state` for `layer`, which is what makes one layer's GDN state its own. Shared by 185/// the direct and captured paths so the two cannot disagree about which slice a layer owns. 186void gdn_point_at (const ModelGeometry & g ,int64_t layer ,SessionState & s ) { 187if (is_qsa_layer (g ,layer ))return ; 188int64_t gdn_index = 0 ; 189for (int64_t l = 0 ;l < layer ;++ l )if (!is_qsa_layer (g ,l ))++ gdn_index ; 190s .gdn .state = s .gdn_state + (size_t ) (gdn_index - s .gdn_ord0 )* gdn_state_floats (g ); 191s .gdn .conv_state = s .gdn .state + (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 192} 193 194/// The per-token staging every QSA layer's captured H2D reads FROM. Must run before each replay: the graphs 195/// captured the SOURCE POINTER, not the value, and that is exactly why the buffers are pinned and fixed. 196void stage_token (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s ) { 197const strata::kernels::QsaShapes sh = qsa_shapes (g ); 198for (int64_t j = 0 ;j < s .qsa_alloc ;++ j ) { 199QsaState & q = s .qsa_states [s .qsa_ord0 + j ]; 200qsa_step_fill (q .host_step ,pos ,sh ); 201for (int64_t h = 0 ;h < g .n_head ;++ h )q .host_pos [h ]= (int32_t ) (pos_base + pos ); 202 } 203} 204 205bool session_capture (const WeightTable & tables ,const ModelGeometry & g ,SessionState & s ,const float * parts , 206SessionGraphs & gr , std::string & err ,bool split ,int64_t layer_lo ,int64_t layer_hi ) { 207if (gr .captured )return true; 208if (layer_hi < 0 || layer_hi > g .n_layers )layer_hi = g .n_layers ; 209if (layer_lo < 0 )layer_lo = 0 ; 210gr .execs = new cudaGraphExec_t [(size_t )g .n_layers ](); 211gr .posts = new cudaGraphExec_t [(size_t )g .n_layers ](); 212for (int64_t i = 0 ;i < g .n_layers ;++ i )gr .posts [i ]= nullptr ; 213if (split ) { 214gr .preA = new cudaGraphExec_t [(size_t )g .n_layers ](); 215gr .preB = new cudaGraphExec_t [(size_t )g .n_layers ](); 216for (int64_t i = 0 ;i < g .n_layers ;++ i ) {gr .preA [i ]= nullptr ;gr .preB [i ]= nullptr ; } 217for (int k = 0 ;k < 5 ;++ k ) { 218gr .preP [k ]= new cudaGraphExec_t [(size_t )g .n_layers ](); 219for (int64_t i = 0 ;i < g .n_layers ;++ i )gr .preP [k ][i ]= nullptr ; 220 } 221 } 222gr .split_captured = split ; 223gr .n = 0 ; 224 225int64_t qsa_index = s .qsa_ord0 ; 226for (int64_t l = layer_lo ;l < layer_hi ;++ l ) { 227gdn_point_at (g ,l ,s ); 228const bool qsa = is_qsa_layer (g ,l ); 229QsaState & qst = qsa ?s .qsa_states [qsa_index ] :s .qsa_states [s .qsa_primary ()]; 230 231// **TWO GRAPHS PER LAYER, SPLIT AT THE ROUTER.** `pre` ends with the doorbell rung; the host then runs 232// the CPU pool on what it published; `post` combines those experts with THIS layer's weights. Capturing 233// them together is what the old single graph could not do, and the reason it could not is that 234// `moe_combine` needs the pool's answer and the pool needs the router's. 235auto capture = [& ](bool post ,cudaGraphExec_t * out ,const char * what ,int half = 0 , 236int stage_prefix = 0 )-> bool { 237cudaStream_t cs = nullptr ; 238if (cudaStreamCreate (& cs )!= cudaSuccess ) { 239err = std::string ("session_capture: stream create failed" ); 240return false; 241 } 242if (cudaStreamBeginCapture (cs ,cudaStreamCaptureModeThreadLocal )!= cudaSuccess ) { 243err = "session_capture: begin failed at layer " + std::to_string (l ); 244return false; 245 } 246err .clear (); 247// R0.9: `half` is 0 for every mode except the split capture, where it selects a prefix of the 248// stages so the mixer and the FFN-front-plus-router can be timed separately. 249const bool ok = post 250 ?block_layer_post (tables ,g ,l ,s .k ,s .moe ,s .block ,parts , (void * )cs ,err ) 251 :block_layer_pre (tables ,g ,l ,0 ,0 ,s .gdn ,qst ,s .qsa_bufs ,s .moe ,s .k , 252s .block , (void * )cs ,err ,s .db ,s .ple .ready () ?& s .ple :nullptr , 253half ,stage_prefix ); 254if (!ok ) { 255err = "session_capture: " + std::string (what )+ " layer " + std::to_string (l )+ ": " + err ; 256return false; 257 } 258cudaGraph_t graph = nullptr ; 259const cudaError_t ce = cudaStreamEndCapture (cs ,& graph ); 260cudaStreamDestroy (cs ); 261if (ce != cudaSuccess ) { 262err = "session_capture: " + std::string (what )+ " layer " + std::to_string (l )+ ": " + 263cudaGetErrorString (ce )+ " (a synchronous call in the layer?)" ; 264return false; 265 } 266if (cudaGraphInstantiate (out ,graph ,0 )!= cudaSuccess ) { 267err = "session_capture: instantiate failed at layer " + std::to_string (l ); 268return false; 269 } 270cudaGraphDestroy (graph ); 271return true; 272 }; 273if (!capture (/*post=*/ false,& gr .execs [l ],"pre" ))return false; 274if (!capture (/*post=*/ true,& gr .posts [l ],"post" ))return false; 275if (split ) { 276if (!capture (/*post=*/ false,& gr .preA [l ],"preA" ,/*half=*/ 1 ))return false; 277if (!capture (/*post=*/ false,& gr .preB [l ],"preB" ,/*half=*/ 2 ))return false; 278// Prefixes 1..5, ALL through the new parameter - including the fifth, so that it and the fourth 279// differ only in the one stage between them and not in how many nodes their graphs carry. 280for (int k = 1 ;k <=5 ;++ k ) 281if (!capture (/*post=*/ false,& gr .preP [k - 1 ][l ],"preP" ,/*half=*/ 0 ,/*stage_prefix=*/ k )) 282return false; 283 } 284++ gr .n ; 285if (qsa )++ qsa_index ; 286 } 287gr .captured = true; 288gr .parts_dev = const_cast < float *> (parts );// the address the graphs baked in; the loop copies here 289return true; 290} 291 292bool session_replay (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s ,SessionGraphs & gr , 293void * stream , std::string & err ) { 294if (!gr .captured || gr .n != g .n_layers ) {err = "session_replay: not captured" ;return false; } 295cudaStream_t cs = (cudaStream_t )stream ; 296stage_token (g ,pos ,pos_base ,s ); 297for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 298const cudaError_t e = cudaGraphLaunch (gr .execs [l ],cs ); 299if (e != cudaSuccess ) { 300err = "session_replay: layer " + std::to_string (l )+ ": " + cudaGetErrorString (e ); 301return false; 302 } 303 } 304return true; 305} 306 307bool session_replay_full (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s , 308SessionGraphs & gr ,void * stream , std::string & err ) { 309if (!gr .captured || gr .n != g .n_layers || gr .posts == nullptr ) { 310err = "session_replay_full: not captured with post graphs" ; 311return false; 312 } 313cudaStream_t cs = (cudaStream_t )stream ; 314stage_token (g ,pos ,pos_base ,s ); 315for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 316// `pre[l]` then `post[l]`, in the order `session_loop` uses. The two are ordered on one stream, and 317// `post[l]` reads what `pre[l]` wrote, so they cannot be reordered or run concurrently. 318cudaError_t e = cudaGraphLaunch (gr .execs [l ],cs ); 319if (e != cudaSuccess ) { 320err = "session_replay_full: pre[" + std::to_string (l )+ "]: " + cudaGetErrorString (e ); 321return false; 322 } 323e = cudaGraphLaunch (gr .posts [l ],cs ); 324if (e != cudaSuccess ) { 325err = "session_replay_full: post[" + std::to_string (l )+ "]: " + cudaGetErrorString (e ); 326return false; 327 } 328 } 329return true; 330} 331 332bool session_replay_stages_per_layer (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s , 333SessionGraphs & gr ,void * stream , std::vector < double >& mixer_per_layer , 334double & ms_ffn ,double & ms_post , std::string & err ) { 335if (!gr .split_captured || gr .preA == nullptr || gr .preB == nullptr ) { 336err = "session_replay_stages: not captured with the split" ; 337return false; 338 } 339cudaStream_t cs = (cudaStream_t )stream ; 340stage_token (g ,pos ,pos_base ,s ); 341 342// Four events PER LAYER rather than four reused ones: reusing them would need a synchronisation after 343// every layer to read them before the next launch overwrote them, and a per-layer sync would report the 344// serialised time rather than the graph's. 345const int64_t n = g .n_layers ; 346 std::vector < cudaEvent_t > ev ((size_t ) (n * 4 )); 347for (auto & e :ev ) { 348if (cudaEventCreate (& e )!= cudaSuccess ) {err = "session_replay_stages: event create" ;return false; } 349 } 350struct Free { 351 std::vector < cudaEvent_t >* v ; 352 ~Free () {for (auto & e :* v )cudaEventDestroy (e ); } 353 }frees {& ev }; 354 355for (int64_t l = 0 ;l < n ;++ l ) { 356cudaEventRecord (ev [(size_t ) (l * 4 + 0 )],cs ); 357if (cudaGraphLaunch (gr .preA [l ],cs )!= cudaSuccess ) {err = "stages: preA" ;return false; } 358cudaEventRecord (ev [(size_t ) (l * 4 + 1 )],cs ); 359if (cudaGraphLaunch (gr .preB [l ],cs )!= cudaSuccess ) {err = "stages: preB" ;return false; } 360cudaEventRecord (ev [(size_t ) (l * 4 + 2 )],cs ); 361if (cudaGraphLaunch (gr .posts [l ],cs )!= cudaSuccess ) {err = "stages: post" ;return false; } 362cudaEventRecord (ev [(size_t ) (l * 4 + 3 )],cs ); 363 } 364if (cudaStreamSynchronize (cs )!= cudaSuccess ) {err = "stages: final sync" ;return false; } 365 366mixer_per_layer .assign ((size_t )n ,0.0 ); 367ms_ffn = 0 ;ms_post = 0 ; 368for (int64_t l = 0 ;l < n ;++ l ) { 369float a = 0 ,b = 0 ,c = 0 ; 370cudaEventElapsedTime (& a ,ev [(size_t ) (l * 4 + 0 )],ev [(size_t ) (l * 4 + 1 )]); 371cudaEventElapsedTime (& b ,ev [(size_t ) (l * 4 + 1 )],ev [(size_t ) (l * 4 + 2 )]); 372cudaEventElapsedTime (& c ,ev [(size_t ) (l * 4 + 2 )],ev [(size_t ) (l * 4 + 3 )]); 373mixer_per_layer [(size_t )l ]= (double )a ; 374ms_ffn += b ;ms_post += c ; 375 } 376return true; 377} 378 379bool session_replay_stages (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s , 380SessionGraphs & gr ,void * stream ,double & ms_mixer ,double & ms_ffn ,double & ms_post , 381 std::string & err ) { 382 std::vector < double > per ; 383if (!session_replay_stages_per_layer (g ,pos ,pos_base ,s ,gr ,stream ,per ,ms_ffn ,ms_post ,err ))return false; 384ms_mixer = 0 ; 385for (double v :per )ms_mixer += v ; 386return true; 387} 388 389bool session_replay_stage_sweep (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s , 390SessionGraphs & gr ,void * stream ,int k ,double & ms , std::string & err ) { 391if (!gr .split_captured || gr .preP [0 ]== nullptr ) { 392err = "session_replay_stage_sweep: not captured with the split" ; 393return false; 394 } 395if (k < 1 || k > 5 ) {err = "session_replay_stage_sweep: k must be 1..5" ;return false; } 396cudaStream_t cs = (cudaStream_t )stream ; 397stage_token (g ,pos ,pos_base ,s ); 398 399cudaEvent_t a ,b ; 400if (cudaEventCreate (& a )!= cudaSuccess || cudaEventCreate (& b )!= cudaSuccess ) { 401err = "session_replay_stage_sweep: event create" ; 402return false; 403 } 404cudaEventRecord (a ,cs ); 405for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 406const cudaError_t e = cudaGraphLaunch (gr .preP [k - 1 ][l ],cs ); 407if (e != cudaSuccess ) { 408cudaEventDestroy (a ); 409cudaEventDestroy (b ); 410err = std::string ("session_replay_stage_sweep: launch: " )+ cudaGetErrorString (e ); 411return false; 412 } 413 } 414cudaEventRecord (b ,cs ); 415if (cudaStreamSynchronize (cs )!= cudaSuccess ) { 416cudaEventDestroy (a ); 417cudaEventDestroy (b ); 418err = "session_replay_stage_sweep: sync" ; 419return false; 420 } 421float v = 0 ; 422cudaEventElapsedTime (& v ,a ,b ); 423cudaEventDestroy (a ); 424cudaEventDestroy (b ); 425ms = (double )v ; 426return true; 427} 428 429bool session_replay_stage_prefixes (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s , 430SessionGraphs & gr ,void * stream , std::vector < double >& stage_ms , 431 std::vector < double >& mixer_per_layer , std::string & err ) { 432if (!gr .split_captured || gr .preP [0 ]== nullptr ) { 433err = "session_replay_stage_prefixes: not captured with the split" ; 434return false; 435 } 436cudaStream_t cs = (cudaStream_t )stream ; 437stage_token (g ,pos ,pos_base ,s ); 438const int64_t n = g .n_layers ; 439const size_t r_floats = (size_t )g .hc * (size_t )g .n_embd ; 440 441float * saved = nullptr ; 442if (cudaMalloc ((void ** )& saved ,r_floats * sizeof (float ))!= cudaSuccess ) { 443err = "session_replay_stage_prefixes: could not save the residual" ; 444return false; 445 } 446 std::vector < cudaEvent_t > ev ((size_t ) (n * 6 )); 447bool ev_ok = true; 448for (auto & e :ev )if (cudaEventCreate (& e )!= cudaSuccess ) {ev_ok = false;break ; } 449if (!ev_ok ) { 450for (auto & e :ev )cudaEventDestroy (e ); 451cudaFree (saved ); 452err = "session_replay_stage_prefixes: event create" ; 453return false; 454 } 455struct Cleanup { 456 std::vector < cudaEvent_t >* v ; 457float * p ; 458 ~Cleanup () {for (auto & e :* v )cudaEventDestroy (e );cudaFree (p ); } 459 }cleanup {& ev ,saved }; 460 461double t [5 ]= {0 ,0 ,0 ,0 ,0 }; 462mixer_per_layer .assign ((size_t )n ,0.0 ); 463for (int64_t l = 0 ;l < n ;++ l ) { 464// The residual as this layer receives it, before any prefix has advanced it. 465cudaMemcpyAsync (saved ,s .block .R ,r_floats * sizeof (float ),cudaMemcpyDeviceToDevice ,cs ); 466for (int k = 1 ;k <=5 ;++ k ) { 467if (k > 1 )cudaMemcpyAsync (s .block .R ,saved ,r_floats * sizeof (float ),cudaMemcpyDeviceToDevice ,cs ); 468cudaEventRecord (ev [(size_t ) (l * 6 + k - 1 )],cs ); 469const cudaGraphExec_t ge = (k == 5 ) ?gr .execs [l ] :gr .preP [k - 1 ][l ]; 470const cudaError_t e = cudaGraphLaunch (ge ,cs ); 471if (e != cudaSuccess ) { 472err = std::string ("session_replay_stage_prefixes: launch prefix " )+ std::to_string (k )+ ": " + 473cudaGetErrorString (e ); 474return false; 475 } 476 } 477cudaEventRecord (ev [(size_t ) (l * 6 + 5 )],cs ); 478 } 479if (cudaStreamSynchronize (cs )!= cudaSuccess ) {err = "prefixes: final sync" ;return false; } 480 481float t1 = 0 ,t2 = 0 ,t3 = 0 ,t4 = 0 ,t5 = 0 ; 482for (int64_t l = 0 ;l < n ;++ l ) { 483float a = 0 ,b = 0 ,c = 0 ,d = 0 ,e = 0 ; 484cudaEventElapsedTime (& a ,ev [(size_t ) (l * 6 + 0 )],ev [(size_t ) (l * 6 + 1 )]); 485cudaEventElapsedTime (& b ,ev [(size_t ) (l * 6 + 1 )],ev [(size_t ) (l * 6 + 2 )]); 486cudaEventElapsedTime (& c ,ev [(size_t ) (l * 6 + 2 )],ev [(size_t ) (l * 6 + 3 )]); 487cudaEventElapsedTime (& d ,ev [(size_t ) (l * 6 + 3 )],ev [(size_t ) (l * 6 + 4 )]); 488cudaEventElapsedTime (& e ,ev [(size_t ) (l * 6 + 4 )],ev [(size_t ) (l * 6 + 5 )]); 489t1 += a ;t2 += b ;t3 += c ;t4 += d ;t5 += e ; 490mixer_per_layer [(size_t )l ]= (double )c ;// prefix 3 IS the mixer: stages 0..2 491 } 492t [0 ]= t1 ; 493t [1 ]= t2 - t1 ; 494t [2 ]= t3 - t2 ; 495t [3 ]= t4 - t3 ; 496t [4 ]= t5 - t4 ; 497stage_ms .assign (t ,t + 5 ); 498return true; 499} 500 501void session_graphs_free (SessionGraphs & gr ) { 502if (gr .execs ) { 503for (int64_t i = 0 ;i < gr .n ;++ i )cudaGraphExecDestroy (gr .execs [i ]); 504delete []gr .execs ; 505 } 506if (gr .posts ) { 507for (int64_t i = 0 ;i < gr .n ;++ i ) 508if (gr .posts [i ]!= nullptr )cudaGraphExecDestroy (gr .posts [i ]); 509delete []gr .posts ; 510 } 511if (gr .preA ) { 512for (int64_t i = 0 ;i < gr .n ;++ i ) 513if (gr .preA [i ]!= nullptr )cudaGraphExecDestroy (gr .preA [i ]); 514delete []gr .preA ; 515 } 516if (gr .preB ) { 517for (int64_t i = 0 ;i < gr .n ;++ i ) 518if (gr .preB [i ]!= nullptr )cudaGraphExecDestroy (gr .preB [i ]); 519delete []gr .preB ; 520 } 521for (int k = 0 ;k < 5 ;++ k ) { 522if (gr .preP [k ]== nullptr )continue ; 523for (int64_t i = 0 ;i < gr .n ;++ i ) 524if (gr .preP [k ][i ]!= nullptr )cudaGraphExecDestroy (gr .preP [k ][i ]); 525delete []gr .preP [k ]; 526gr .preP [k ]= nullptr ; 527 } 528gr .preA = nullptr ; 529gr .preB = nullptr ; 530gr .split_captured = false; 531gr .posts = nullptr ; 532gr .execs = nullptr ; 533gr .parts_dev = nullptr ; 534gr .n = 0 ; 535gr .captured = false; 536} 537 538bool SessionLoopScratch ::init (size_t parts_bytes_in , std::string & err ) { 539if (y_miss != nullptr || probe != nullptr ) { 540err = "SessionLoopScratch::init: already initialised" ; 541return false; 542 } 543parts_bytes = parts_bytes_in ; 544// MAPPED as well as pinned: the token graph's handoff kernel reads it through its device pointer. 545if (strata::core::host_alloc_guarded ((void ** )& y_miss ,parts_bytes ,cudaHostAllocMapped |cudaHostAllocPortable )!= cudaSuccess ) { 546err = "SessionLoopScratch: cudaHostAlloc for the pool's staging failed" ; 547return false; 548 } 549 std::memset (y_miss ,0 ,parts_bytes ); 550if (cudaEventCreate (& probe )!= cudaSuccess ) { 551err = "SessionLoopScratch: cudaEventCreate failed" ; 552free (); 553return false; 554 } 555// **PIN THE HOST ONCE, NOT ONCE PER TOKEN.** `ExpertPool` builds its workers from `physical_cores(true)`, 556// which drops the first physical core so the host loop can spin without taking a worker's cycles - and 557// nothing in the pool can pin the host, so if this does not happen the spin is free to land on a worker's 558// 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 559// runs at 36.32. It was being done and undone on EVERY token, which is a syscall pair on the critical path 560// for a property that wants to hold for the whole session. 561// The host's core is the pool's reserved one: the first physical core, or the last with --host-core last (F12), 562// or the first core's SMT sibling with --host-core sibling. 563const int host_core = strata::kernels::cpu::planned_host_core (); 564if (host_core >=0 ) { 565pinned_core = strata::kernels::cpu::pin_current_thread (host_core ); 566pinned = pinned_core .valid ; 567 }else { 568const std::vector < int > cores = strata::kernels::cpu::physical_cores (false); 569if (!cores .empty ()) { 570pinned_core = strata::kernels::cpu::pin_current_thread (cores [0 ]); 571pinned = pinned_core .valid ; 572 } 573 } 574 strata::platform::name_this_thread ("strata-host" ); 575 strata::aux_cpus::note_owned_thread ();// the host: --aux-cpus leaves it where it is 576return true; 577} 578 579void SessionLoopScratch ::free () { 580// Restores the caller's affinity on every path, including teardown: a library that silently leaves its 581// caller's thread nailed to one core is worse than one that never pinned at all. 582if (pinned ) { 583 strata::kernels::cpu::restore_thread_affinity (pinned_core ); 584pinned = false; 585pinned_core = {}; 586 } 587if (probe != nullptr ) {cudaEventDestroy (probe );probe = nullptr ; } 588if (y_miss != nullptr ) {cudaFreeHost (y_miss );y_miss = nullptr ; } 589parts_bytes = 0 ; 590} 591 592bool session_loop (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s ,SessionGraphs & gr , 593PoolFn pool ,HitFn hits ,void * user ,bool overlap ,void * stream , std::string & err , 594float * dump_layers ,SessionLoopScratch * scratch ) { 595if (!gr .captured || gr .n != g .n_layers ) {err = "session_loop: not captured" ;return false; } 596if (gr .parts_dev == nullptr ) {err = "session_loop: the graphs were captured without a parts buffer" ;return false; } 597if (s .db == nullptr ) {err = "session_loop: no doorbell; the loop has nothing to poll" ;return false; } 598 599cudaStream_t cs = (cudaStream_t )stream ; 600const int64_t k = s .k ; 601const size_t parts_bytes = (size_t )k * g .n_embd * 4 ; 602++ gr .calls_total ; 603 604// ================================ THE POSITION, WHICH THIS LOOP NEVER STAGED ================================ 605// 606// **EVERY TOKEN AFTER THE FIRST USED TO REPLAY POSITION 0.** The QSA layers read their per-token counts from 607// `st.step` and `st.pos_dev`, which are DEVICE buffers filled by an H2D copy captured INTO each graph. A 608// graph bakes the SOURCE POINTER, not the value - so the copy re-reads the pinned host buffers on every 609// replay, and those hold whatever was last written there. `session_capture` left them at position 0. 610// 611// `layer.hpp` documents the requirement this loop was missing: "The per-token staging every QSA layer's 612// captured H2D reads FROM. Must run before each replay: the graphs captured the SOURCE POINTER, not the 613// value, and that is exactly why the buffers are pinned and fixed." `session_replay` calls `stage_token`; 614// `session_loop` did not. **A single-token test cannot see a position that never advances** - which is why 615// the whole suite passed while a 20-token prompt rotated every token at position 0. 616stage_token (g ,pos ,pos_base ,s ); 617 618// ---- **THE TOKEN PATH ALLOCATES NOTHING (P2.T10, review finding H3).** 619// 620// Everything this loop needs on the host - the pinned staging for the pool's answer, the doorbell probe 621// event, and the host pin - lives in a `SessionLoopScratch` owned by the SESSION and passed in. It used to 622// be created here, once per token, and `cudaFreeHost` at the end of the call IMPLICITLY SYNCHRONISES THE 623// DEVICE, so every token finished with a device-wide sync that nothing had asked for. A comment here said 624// "allocated once"; once per token is not once. 625// 626// Passing `nullptr` keeps the old behaviour so existing callers and tests are unaffected: the loop builds a 627// local scratch and frees it on every exit path below, including the error returns. 628SessionLoopScratch local ; 629if (scratch == nullptr ) { 630if (!local .init (parts_bytes ,err ))return false; 631scratch = & local ; 632 } 633struct LocalFree { 634SessionLoopScratch * p ; 635 ~LocalFree () {if (p != nullptr )p -> free (); } 636 }local_free {scratch == & local ?& local :nullptr }; 637if (scratch -> parts_bytes != parts_bytes ) { 638err = "session_loop: the scratch was sized for a different k or n_embd" ; 639return false; 640 } 641 642// HOST-side staging for the pool's answer. It is copied to `gr.parts_dev` before the next launch, on the 643// same stream, so the ordering is the stream's and no captured node is needed for it. 644// 645// ---- **PINNED, BECAUSE A COPY FROM PAGEABLE MEMORY IS NOT ASYNCHRONOUS AT ALL.** 646// 647// `cudaMemcpyAsync` with a pageable source cannot DMA: the driver first memcpys the bytes into an internal 648// pinned bounce buffer, SYNCHRONOUSLY, on this thread, and only then enqueues the transfer. So the "async" 649// copy would be a blocking memcpy plus a driver round trip, on the critical path of all 48 layers. The 650// doorbell's `h_x_f` is `cudaHostAlloc(Mapped)` for exactly this reason and this buffer is the same kind of 651// object. 652float * y_miss = scratch -> y_miss ; 653cudaEvent_t probe = scratch -> probe ; 654 655// the first layer has no previous layer's experts: `y_miss` starts at zero, which is what "hits are empty 656// in this phase" means once every miss has been computed 657cudaMemcpyAsync (gr .parts_dev ,y_miss ,parts_bytes ,cudaMemcpyHostToDevice ,cs ); 658doorbell_reset (* s .db ); 659uint32_t expected = 0 ; 660 661// **`pre[0]` IS LAUNCHED BEFORE THE LOOP SO EVERY ITERATION HAS THE SAME SHAPE**: poll the ring that 662// `pre[l]` published, run the pool on it, combine, then start layer `l+1`'s `pre`. 663// 664// SLOT 0 OF THE DUMP IS THE INPUT, not a layer output. `s.R` holds the embedding broadcast to every stream 665// when this function is entered, which is the reference's `hc_init` node - so dumping it here is what splits 666// "the input to layer 0 is already wrong" from "layer 0 is wrong". 667if (dump_layers != nullptr ) { 668const size_t n = (size_t )g .hc * (size_t )g .n_embd ; 669const cudaError_t de = cudaMemcpyAsync (dump_layers ,s .R ,n * sizeof (float ),cudaMemcpyDeviceToHost ,cs ); 670if (de != cudaSuccess ) { 671err = "session_loop: dump the input residual: " + std::string (cudaGetErrorString (de )); 672return false; 673 } 674 } 675 { 676const auto t0 = std::chrono::steady_clock::now (); 677const cudaError_t le = cudaGraphLaunch (gr .execs [0 ],cs ); 678if (le != cudaSuccess ) { 679err = "session_loop: launch pre[0]: " + std::string (cudaGetErrorString (le )); 680return false; 681 } 682cudaEventRecord (probe ,cs ); 683 (void )t0 ; 684 } 685 686for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 687const auto t_launch = std::chrono::steady_clock::now (); 688 689// ---- poll for the ring. **THE DRIVER CALL IS NOW A FALLBACK, NOT THE MECHANISM.** 690const uint32_t want = ++ expected ; 691bool rang = false; 692bool mid_graph = false; 693// VOLATILE, because the device writes this through mapped pinned memory and a cached host line would 694// never see it. Read through a volatile pointer so the compiler re-issues the load every iteration - 695// otherwise this whole spin collapses into `while (true) { }`. 696volatile uint32_t * const seq = s .db -> h_seq ; 697for (;;) { 698// **THE PER-ITERATION DRIVER CALL IS REQUIRED, AND THREE EXPERIMENTS NOW SAY SO.** Round 287 699// throttled this to one call in 64 and broke tests 51 and 56; adding `__threadfence_system()` to 700// `doorbell_ring_kernel` and a volatile read here, then throttling, broke them again. So the call 701// is not merely flushing submission (round 195's reading) and it is not a missing fence either: on 702// this driver, the device's write to mapped pinned memory becomes host-visible only when the driver 703// is entered. The fence and the volatile read are kept because they are correct and cost nothing - 704// without them the ring's ordering against `x_f`/`ids`/`weights` is unstated - but they do not 705// remove the need for the call, and nothing here should be read as claiming they do. 706const cudaError_t q = cudaEventQuery (probe ); 707if (!rang && * seq >=want ) { 708rang = true; 709mid_graph = (q != cudaSuccess ); 710 } 711if (q == cudaSuccess )break ;// the graph has ended 712if (q != cudaErrorNotReady ) { 713err = "session_loop: query at layer " + std::to_string (l )+ ": " + cudaGetErrorString (q ); 714return false; 715 } 716if (rang )break ;// rung, and the graph is still running: the overlap 717STRATA_SPIN_PAUSE (); 718 } 719strata_load_fence ();// the ring was seen: the GPU's x_f / ids / weights are read after it (a no-op on x86) 720if (mid_graph )++ gr .rings_mid_graph ; 721// the window, from just before the launch to the instant the ring was seen 722const auto t_ring = std::chrono::steady_clock::now (); 723gr .ms_to_ring += std::chrono::duration < double , std::milli > (t_ring - t_launch ).count (); 724if (!rang ) { 725// The graph finished without the ring being observed. `h_seq` is monotonic, so this is not a race 726// - it means the ring never happened, which is the failure round 199 found in a captured event. 727err = "session_loop: layer " + std::to_string (l )+ " ended without ringing" ; 728return false; 729 } 730 731// ---- **THE GPU'S HALF GOES FIRST, SO IT RUNS WHILE THE CPU DOES ITS HALF.** `Launch` only enqueues: 732// the quantize and the grouped expert kernel land on `main_cs` and the GPU starts on them immediately, 733// while the host is still inside `pool` below. Nothing here waits. 734if (hits != nullptr )hits (user ,cs ,HitPhase ::Launch ,s .db -> h_ids ,k ); 735 736// ---- the pool, on the bytes the doorbell published. **THESE ARE LAYER `l`'s EXPERTS.** 737if (pool != nullptr )pool (user ,s .db -> h_x_f ,s .db -> h_ids ,s .db -> h_weights ,g .n_embd ,k ,y_miss ); 738 739// ---- **AND THEY ARE COMBINED BY LAYER `l`, NOT BY LAYER `l+1`.** 740// 741// This copy and the launch below are the whole of the L100 fix. `moe_combine` multiplies `parts` by 742// THIS layer's `b.weights`, so `parts` must be THIS layer's expert outputs; the previous form copied 743// the pool's answer into `parts_dev` for the NEXT layer, which computed 744// `sum_j w_{l+1}[j] * expert_{ids_l,j}(x_l)` - both the selection and the input one layer stale while 745// the weights were current. It produced finite, fluent, deterministic tokens that were not the 746// model's, and no timing test could see it. 747cudaMemcpyAsync (gr .parts_dev ,y_miss ,parts_bytes ,cudaMemcpyHostToDevice ,cs ); 748// ---- **AND THEN THE COMBINE.** Stream-ordered after the copy above, so `hit_out` is added to misses 749// that are already in `parts`, and before `post[l]`, whose `moe_combine` reads the sum. A no-op when 750// there is no VRAM tier or nothing is resident, which is every layer until the cache warms. 751if (hits != nullptr )hits (user ,cs ,HitPhase ::Combine ,nullptr ,0 ); 752 { 753const cudaError_t pe = cudaGraphLaunch (gr .posts [l ],cs ); 754if (pe != cudaSuccess ) { 755err = "session_loop: launch post[" + std::to_string (l )+ "]: " + cudaGetErrorString (pe ); 756return false; 757 } 758 } 759// ---- the C1 oracle. `s.R` now holds layer `l`'s residual and keeps it until `post[l+1]` writes it, so 760// a copy enqueued HERE - after `post[l]`, before `pre[l+1]` - is ordered correctly by the stream alone. 761// Nothing is synchronised: the loop's existing final sync is what completes these. See the note on 762// `dump_layers` in session.hpp for why this is an enqueue and not a read. 763if (dump_layers != nullptr ) { 764const size_t n = (size_t )g .hc * (size_t )g .n_embd ; 765const cudaError_t de = cudaMemcpyAsync (dump_layers + (size_t ) (l + 1 )* n ,s .R ,n * sizeof (float ), 766cudaMemcpyDeviceToHost ,cs ); 767if (de != cudaSuccess ) { 768err = "session_loop: dump layer " + std::to_string (l )+ ": " + cudaGetErrorString (de ); 769return false; 770 } 771 } 772if (!overlap ) { 773// THE COMPARISON ARM. The same sequence with the pipeline removed: the CPU does not start until the 774// layer is over, so nothing overlaps and the difference is attributable to the doorbell alone. 775if (cudaStreamSynchronize (cs )!= cudaSuccess ) { 776err = "session_loop: sync at layer " + std::to_string (l ); 777return false; 778 } 779 } 780// ---- and layer l+1's routing starts. `pre[l+1]` touches none of the buffers `post[l]` reads, because 781// the two are ordered on one stream and `pre[l+1]`'s first use of `bb.mixed`/`bb.inject` is its own 782// `gr_read`, which comes after `post[l]` has consumed them. 783if (l + 1 < g .n_layers ) { 784const cudaError_t ne = cudaGraphLaunch (gr .execs [l + 1 ],cs ); 785if (ne != cudaSuccess ) { 786err = "session_loop: launch pre[" + std::to_string (l + 1 )+ "]: " + cudaGetErrorString (ne ); 787return false; 788 } 789cudaEventRecord (probe ,cs ); 790 } 791// ---- **THE SECOND HALF OF THE ROUND TRIP, AND THE HALF NOTHING WAS MEASURING.** 792// 793// From seeing the ring to having queued the next `pre`. Everything in here is a driver call, and on 794// the token path the GPU has nothing left to run for most of it - `pre[l]` has already rung, and 795// `post[l]` cannot start until this code launches it. So this interval is GPU-idle time, and it is 796// the number that decides whether the fix is R2.4 (fewer launches per layer) or a faster kernel. 797// 798// It INCLUDES the `!overlap` synchronisation when that arm is selected, which is deliberate: that arm 799// exists to show what the pipeline is worth, and hiding its cost here would defeat the comparison. 800gr .ms_host += std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ()- t_ring ).count (); 801 } 802if (cudaStreamSynchronize (cs )!= cudaSuccess ) {err = "session_loop: final sync" ;return false; } 803return true; 804} 805 806bool session_token (const WeightTable & tables ,const ModelGeometry & g ,int64_t pos ,int32_t pos_base , 807SessionState & s ,const float * parts ,void * stream ,bool sync_every_layer , 808 std::string & err ) { 809cudaStream_t cs = (cudaStream_t )stream ; 810int64_t qsa_index = 0 ; 811int64_t gdn_index = 0 ; 812 813for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 814// THE GDN LAYERS EACH GET THEIR OWN STATE, and `GdnBuffers` carries it - so the session points the 815// shared scratch at the right slice before each call. Sharing one state across 36 layers would make 816// every layer start from the previous layer's recurrence, which produces a perfectly finite answer. 817if (!is_qsa_layer (g ,l )) { 818s .gdn .state = s .gdn_state + (size_t )gdn_index * gdn_state_floats (g ); 819s .gdn .conv_state = s .gdn .state + (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 820++ gdn_index ; 821 } 822 823err .clear (); 824const bool ok = is_qsa_layer (g ,l ) 825 ?block_layer (tables ,g ,l ,pos ,pos_base ,s .gdn ,s .qsa_states [qsa_index ],s .qsa_bufs ,s .moe ,s .k , 826s .block ,parts ,stream ,err ,nullptr ,s .ple .ready () ?& s .ple :nullptr ) 827 :block_layer (tables ,g ,l ,pos ,pos_base ,s .gdn ,s .qsa_states [0 ],s .qsa_bufs ,s .moe ,s .k , 828s .block ,parts ,stream ,err ,nullptr ,s .ple .ready () ?& s .ple :nullptr ); 829if (!ok ) { 830err = "layer " + std::to_string (l )+ ": " + err ; 831return false; 832 } 833if (is_qsa_layer (g ,l ))++ qsa_index ; 834 835if (sync_every_layer ) { 836// THE DEBUG MODE, and its cost is the point: it is a real synchronisation after every layer, which 837// P2.X3 forbids in the fast path. It exists to turn an ASYNCHRONOUS error - a kernel reading a 838// buffer a later layer wrote, or an out-of-range launch - into a failure AT THE LAYER THAT CAUSED 839// IT, instead of a wrong number 40 layers later or at the end of the token. 840const cudaError_t e = cudaStreamSynchronize (cs ); 841if (e != cudaSuccess ) { 842err = "layer " + std::to_string (l )+ ": " + cudaGetErrorString (e ); 843return false; 844 } 845 } 846 } 847return true; 848} 849 850}// namespace strata::core 851 852namespace strata::core { 853 854bool session_capture_token (const WeightTable & tables ,const ModelGeometry & g ,SessionState & s ,float * parts_dev , 855const float * y_miss_host ,size_t parts_bytes ,TokenGraph & tg , std::string & err , 856const TokenHits * hits ) { 857if (hits != nullptr && !hits -> on ()) {err = "session_capture_token: incomplete hit configuration" ;return false; } 858if (tg .captured )return true; 859if (s .db == nullptr || s .db -> d_flag == nullptr || s .db -> d_seq == nullptr ) { 860err = "session_capture_token: the doorbell has no flag" ; 861return false; 862 } 863if (parts_dev == nullptr || y_miss_host == nullptr || parts_bytes == 0 ) { 864err = "session_capture_token: parts buffers are required" ; 865return false; 866 } 867float * y_dev = nullptr ; 868if (cudaHostGetDevicePointer ((void ** )& y_dev ,const_cast < float *> (y_miss_host ),0 )!= cudaSuccess || !y_dev ) { 869err = "session_capture_token: the parts staging is not mapped pinned memory" ; 870return false; 871 } 872cudaStream_t cs = nullptr ; 873if (cudaStreamCreate (& cs )!= cudaSuccess ) {err = "session_capture_token: stream create failed" ;return false; } 874if (cudaStreamBeginCapture (cs ,cudaStreamCaptureModeThreadLocal )!= cudaSuccess ) { 875cudaStreamDestroy (cs ); 876err = "session_capture_token: begin capture failed" ; 877return false; 878 } 879int64_t qsa_index = 0 ; 880bool ok = true; 881for (int64_t l = 0 ;l < g .n_layers && ok ;++ l ) { 882gdn_point_at (g ,l ,s ); 883const bool qsa = is_qsa_layer (g ,l ); 884QsaState & qst = qsa ?s .qsa_states [qsa_index ] :s .qsa_states [0 ]; 885err .clear (); 886ok = 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 , 887s .ple .ready () ?& s .ple :nullptr ); 888if (!ok ) {err = "session_capture_token: pre layer " + std::to_string (l )+ ": " + err ;break ; } 889if (hits != nullptr ) { 890// After the ring (and the shared expert): the GPU's experts run while the CPU computes the misses. 891 strata::kernels::moe_hit_select (s .moe .ids ,hits -> d_res + l * hits -> n_expert , (int )s .k , 892 (int )hits -> n_expert ,hits -> d_slot ,hits -> d_dst ,hits -> d_count , (void * )cs ); 893 strata::kernels::quantize_q8_0_scaled (s .block .mixed ,hits -> x_q8 ,hits -> x_scale ,g .n_embd , (void * )cs ); 894 strata::kernels::moe_hit_grouped_s2_dev (hits -> cache_base ,hits -> d_slot ,hits -> d_dst ,hits -> d_count ,s .k , 895hits -> blob ,hits -> x_q8 ,hits -> scratch ,hits -> hit_out , (void * )cs , 896hits -> x_scale ); 897 } 898 strata::kernels::doorbell_wait (s .db -> d_flag ,s .db -> d_seq , (void * )cs ); 899// A kernel, not a memcpy node: a copy-engine node splits the WDDM submission (measured 67 flushes/token). 900 strata::kernels::copy_from_mapped (parts_dev ,y_dev , (int64_t ) (parts_bytes /sizeof (float )), (void * )cs ); 901if (hits != nullptr ) 902 strata::kernels::moe_hit_add (parts_dev ,hits -> hit_out ,hits -> d_dst ,hits -> d_count ,s .k ,g .n_embd , (void * )cs ); 903ok = block_layer_post (tables ,g ,l ,s .k ,s .moe ,s .block ,parts_dev , (void * )cs ,err ); 904if (!ok ) {err = "session_capture_token: post layer " + std::to_string (l )+ ": " + err ;break ; } 905if (qsa )++ qsa_index ; 906 } 907cudaGraph_t graph = nullptr ; 908const cudaError_t ce = cudaStreamEndCapture (cs ,& graph ); 909cudaStreamDestroy (cs ); 910if (!ok ) {if (graph )cudaGraphDestroy (graph );return false; } 911if (ce != cudaSuccess ) { 912err = std::string ("session_capture_token: end capture: " )+ cudaGetErrorString (ce ); 913return false; 914 } 915const cudaError_t ie = cudaGraphInstantiate (& tg .exec ,graph ,0 ); 916cudaGraphDestroy (graph ); 917if (ie != cudaSuccess ) { 918err = std::string ("session_capture_token: instantiate: " )+ cudaGetErrorString (ie ); 919return false; 920 } 921tg .captured = true; 922tg .n_layers = g .n_layers ; 923tg .y_src = y_miss_host ; 924tg .parts_bytes = parts_bytes ; 925return true; 926} 927 928bool session_run_token (const ModelGeometry & g ,int64_t pos ,int32_t pos_base ,SessionState & s ,TokenGraph & tg , 929PoolFn pool ,void * user ,float * y_miss_host ,void * stream , std::string & err ) { 930if (!tg .captured ) {err = "session_run_token: not captured" ;return false; } 931if (y_miss_host != tg .y_src ) {err = "session_run_token: the staging buffer is not the captured one" ;return false; } 932cudaStream_t cs = (cudaStream_t )stream ; 933++ tg .calls ; 934stage_token (g ,pos ,pos_base ,s ); 935doorbell_reset (* s .db ); 936const cudaError_t le = cudaGraphLaunch (tg .exec ,cs ); 937if (le != cudaSuccess ) {err = std::string ("session_run_token: launch: " )+ cudaGetErrorString (le );return false; } 938 (void )cudaStreamQuery (cs );// one flush, so WDDM submits the graph now 939static const int flush_us = [] { 940const char * e = std::getenv ("STRATA_TG_FLUSH_US" ); 941return e ? std::atoi (e ) :2000 ;// 24 Sep: 0 flushes run as fast as 5 us ones; this only notices faults 942 }(); 943volatile uint32_t * const seq = s .db -> h_seq ; 944volatile uint32_t * const flag = s .db -> h_flag ; 945using Clock = std::chrono::steady_clock ; 946for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 947const uint32_t want = (uint32_t ) (l + 1 ); 948const auto t0 = Clock ::now (); 949auto last_flush = t0 ; 950uint32_t spins = 0 ; 951progress_at ("token: waiting for the GPU to reach layer" ,l ); 952while (* seq < want ) { 953STRATA_SPIN_PAUSE (); 954if ((++ spins & 1023u )!= 0 )continue ; 955const auto now = Clock ::now (); 956if (now - last_flush > std::chrono::microseconds (flush_us )) { 957// A slow ring: flush the submission queue once more, and notice a fault or a finished graph. 958last_flush = now ; 959++ tg .flushes ; 960const cudaError_t q = cudaStreamQuery (cs ); 961if (q != cudaErrorNotReady && * seq < want ) { 962err = "session_run_token: layer " + std::to_string (l )+ " never rang (" + 963 (q == cudaSuccess ? std::string ("graph finished" ) : std::string (cudaGetErrorString (q )))+ ")" ; 964return false; 965 } 966 } 967if (now - t0 > std::chrono::seconds (20 )) { 968err = "session_run_token: timed out waiting for layer " + std::to_string (l ); 969return false; 970 } 971 } 972strata_load_fence ();// as above, for the token loop's wait 973const auto t1 = Clock ::now (); 974progress_at ("token: the CPU experts of layer" ,l ); 975if (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 ); 976 std::atomic_thread_fence (std::memory_order_seq_cst ); 977strata_store_fence (); 978* flag = want ; 979const auto t2 = Clock ::now (); 980tg .ms_wait += std::chrono::duration < double , std::milli > (t1 - t0 ).count (); 981tg .ms_pool += std::chrono::duration < double , std::milli > (t2 - t1 ).count (); 982 } 983progress_at ("token: waiting for the GPU to finish the token" ); 984const cudaError_t se = cudaStreamSynchronize (cs ); 985if (se != cudaSuccess ) {err = std::string ("session_run_token: " )+ cudaGetErrorString (se );return false; } 986progress_at ("decode" ); 987progress_beat (); 988return true; 989} 990 991void token_graph_free (TokenGraph & tg ) { 992if (tg .exec )cudaGraphExecDestroy (tg .exec ); 993tg = TokenGraph {}; 994} 995 996}// namespace strata::core