okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
d510921bc
main
1// src/core/verify.cpp - see include/strata/core/verify.hpp. 2// HostGraphLaunch (the graph launched by the calling thread, or by a helper thread so this one can serve the doorbells): CUDA builds, 3// and the Windows HIP build (STRATA_VERIFY_ASYNC_LAUNCH=1 launches from a helper thread; STRATA_LAUNCH_PROBE=1 logs the launch timing). 4#if (!defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 ))|| (defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 )&& defined(_WIN32 )) 5#define STRATA_VERIFY_HGL 1 6#endif 7#include "strata/core/batch_rows.hpp" 8#include "strata/core/sm75_series.hpp" 9#include "strata/core/sm120_series.hpp" 10#include "strata/core/defaults_026.hpp" 11#include "strata/kernels/gfx_arch.hpp" 12#include "strata/core/verify.hpp" 13#include "strata/core/latent_share.hpp" 14#include "strata/core/window_evict.hpp" 15#include "strata/core/expert_nibble.hpp" 16#include "strata/latent/latent_moe.hpp" 17#include "strata/kernels/latent.hpp" 18#include "strata/core/pin_budget.hpp" 19#if defined(STRATA_VERIFY_HGL ) 20#include "strata/core/host_graph_launch.hpp" 21#endif 22#include "strata/core/remote_expert_opt.hpp" 23#include "strata/core/dma_batch.hpp" 24#include "strata/core/spec_prob.hpp" 25#include "strata/core/spec_proposal.hpp" 26#if defined(_WIN32 ) 27#ifndef NOMINMAX 28#define NOMINMAX 29#endif 30#include <windows.h> 31#include <intrin.h> 32#endif 33 34#include "strata/core/native_head.hpp" 35#include "strata/core/on_device.hpp" 36#include "strata/core/peer_experts.hpp" 37#include "strata/kernels/iq_kernels.hpp" 38#include "strata/kernels/cpu/expert_layout.hpp" 39#include "strata/kernels/cpu/hadamard.hpp" 40#include "strata/kernels/bf16_gemv.hpp" 41#include "strata/kernels/native_router.hpp" 42#include "strata/kernels/native_moe.hpp" 43#include "strata/kernels/cpu/expert.hpp" 44#include "strata/kernels/elementwise.hpp" 45#include "strata/kernels/qsa_prompt_attn.hpp" 46#include "strata/kernels/fused_gr.hpp" 47#include "strata/kernels/route_prior.hpp" 48#include "strata/kernels/cvec.hpp" 49#include "strata/kernels/gr.hpp" 50#include "strata/kernels/kv_q4.hpp" 51#include "strata/kernels/kv_q8.hpp" 52#include "strata/kernels/native_mmvq.hpp" 53#include "strata/core/dispatch_stats.hpp" 54#include "strata/kernels/native_gr_postops.hpp" 55#include "strata/kernels/native_ple_postops.hpp" 56#include "strata/kernels/native_qsa.hpp" 57#include "strata/kernels/native_qsa_indexer.hpp" 58#include "strata/kernels/native_rope.hpp" 59#include "strata/kernels/ngram.hpp" 60#include "strata/kernels/pdl.hpp" 61#include "strata/kernels/ple.hpp" 62#include "strata/kernels/qsa.hpp" 63#include "strata/kernels/qsa_decode_attn.hpp" 64#include "strata/kernels/qsa_select.hpp" 65#include "strata/kernels/quantize_act.hpp" 66#include "strata/kernels/rope.hpp" 67#include "strata/kernels/s2_expert_grouped.hpp" 68#include "strata/kernels/sampler.hpp" 69#include "strata/core/progress.hpp" 70#include "strata/kernels/shared_expert.hpp" 71#include "strata/kernels/verify_kernels.hpp" 72#if defined(STRATA_HAVE_DFLASH2 ) 73#include "strata/kernels/dflash2.hpp" 74#endif 75 76#include <algorithm> 77#include <atomic> 78#include <map> 79#include <set> 80#include <mutex> 81#include <string> 82#include <optional> 83#include <thread> 84#include <vector> 85#include <chrono> 86#include <cmath> 87#include <cstdio> 88#include <cstdlib> 89#include <cstring> 90#include <exception> 91#include "strata/platform/cpu_relax.hpp" 92 93#if defined(STRATA_GPU_METAL ) 94// The Metal backend's decode window (metal/src/engine/window.cpp): this file's init/run/commit hand over to it. 95namespace strata::metal_engine { 96void window_destroy (void * w ); 97void * window_create (); 98bool window_init (void * w ,const strata::core::ModelGeometry & g , strata::core::SessionState & ss ,int max_t ,int64_t max_cells , 99int64_t * n_vocab , std::string & err ); 100bool window_run (void * w ,int T ,const int32_t * tokens ,int64_t pos0 ,bool head ,int32_t * out , std::string & err ); 101bool window_commit (void * w ,int n_keep , std::string & err ); 102bool window_copy_logits (void * w ,int t ,float * host ); 103void window_set_sampling (void * w ,const strata::kernels::SamplerParams * sp ,const int32_t * hist ,int hist_len ); 104bool window_sample_slot_row (void * w ,int row ,const strata::kernels::SamplerParams & sp ,const int32_t * hist ,int hist_len ,int32_t * tok , std::string & err ); 105bool window_init_slots (void * w ,const std::vector < strata::core::SessionState *>& slots , std::string & err ); 106bool window_run_slots (void * w ,const int * rows ,int S ,const int32_t * tokens ,const int64_t * pos ,int32_t * out , std::string & err ); 107bool window_taps (void * w ,const std::vector < int >& layers ,const float ** tap_dev , std::string & err );// dflash2.inc 108}// namespace strata::metal_engine 109#endif 110 111namespace strata::core { 112namespace { 113 114constexpr float EPS = 1e-6f ; 115using Clock = std::chrono::steady_clock ; 116double ms_since (Clock ::time_point t ) {return std::chrono::duration < double , std::milli > (Clock ::now ()- t ).count (); } 117const bool g_dbg = std::getenv ("STRATA_VERIFY_DEBUG" )!= nullptr ; 118inline bool g_lfuse () {static const bool on = [] {const char * v = std::getenv ("STRATA_LFUSE" );return v != nullptr && v [0 ]== '1' ; }();return on ; } 119// STRATA_ROUTE_RESIDENT=<margin logits> (+ STRATA_ROUTE_RESIDENT_RANKS=lo-hi, default 6-9): residency-biased routing. 120struct RouteResidentCfg ; 121RouteResidentCfg & route_resident_cfg (); 122struct RouteResidentCfg { 123float margin = 0.0f ; 124int lo = 6 ,hi = 9 ; 125// #1578: one counter block per GPU. A layer split inits a verifier per stage; a block allocated on whichever device 126// was current at the first init is unreachable from the other stage's kernels without P2P (illegal memory access). 127// The Verifier asks for its device's block in init (outside graph capture) and keeps the pointer: a launch never 128// picks the block by the host thread's current device. nullptr (the allocation failed): the kernel runs without counters. 129 std::mutex mu ; 130 std::map < int ,unsigned long long *> blocks ; 131unsigned long long * stats_on (int dev ) { 132if (margin <=0.0f || dev < 0 )return nullptr ; 133 std::lock_guard < std::mutex > lk (mu ); 134const auto it = blocks .find (dev ); 135if (it != blocks .end ())return it -> second ; 136unsigned long long * p = nullptr ; 137 { 138const OnDevice on (dev ); 139if (cudaMalloc ((void ** )& p ,8 * sizeof (unsigned long long ))!= cudaSuccess || 140cudaMemset (p ,0 ,8 * sizeof (unsigned long long ))!= cudaSuccess ) { 141 (void )cudaGetLastError (); 142if (p != nullptr )cudaFree (p ); 143p = nullptr ; 144 std::fprintf (stderr ,"route-resident: the counters could not be allocated on GPU %d; it runs without them\n" ,dev ); 145 } 146 } 147if (blocks .empty ()) { 148 std::atexit ([] { 149RouteResidentCfg & c = route_resident_cfg (); 150for (const auto & kv :c .blocks ) { 151if (kv .second == nullptr )continue ; 152unsigned long long h [8 ]= {};// (the counter block allocated above: 8 words) 153if (cudaSetDevice (kv .first )!= cudaSuccess || cudaDeviceSynchronize ()!= cudaSuccess || 154cudaMemcpy (h ,kv .second ,sizeof (h ),cudaMemcpyDeviceToHost )!= cudaSuccess ) { 155 (void )cudaGetLastError (); 156continue ; 157 } 158char who [32 ]= "" ; 159if (c .blocks .size ()> 1 ) std::snprintf (who ,sizeof who ," (GPU %d)" ,kv .first ); 160 std::fprintf (stderr ,"route-resident%s: margin=%g ranks=%d-%d windows T>8 (prompt reads): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n" , 161who ,c .margin ,c .lo ,c .hi ,h [0 ],h [1 ],h [0 ] ?100.0 * h [1 ] /h [0 ] :0.0 ,h [2 ],h [3 ]); 162 std::fprintf (stderr ,"route-resident%s: margin=%g ranks=%d-%d windows T<=8 (decode): tail_nonres=%llu swaps=%llu (%.1f%%) nonres_entries before=%llu after=%llu\n" , 163who ,c .margin ,c .lo ,c .hi ,h [4 ],h [5 ],h [4 ] ?100.0 * h [5 ] /h [4 ] :0.0 ,h [6 ],h [7 ]); 164 } 165 }); 166 } 167blocks [dev ]= p ; 168return p ; 169 } 170}; 171RouteResidentCfg & route_resident_cfg () { 172static RouteResidentCfg c ; 173static const bool parsed = [] { 174if (const char * v = std::getenv ("STRATA_ROUTE_RESIDENT" ))c .margin = (float ) std::atof (v ); 175if (const char * v = std::getenv ("STRATA_ROUTE_RESIDENT_RANKS" )) std::sscanf (v ,"%d-%d" ,& c .lo ,& c .hi ); 176return true; 177 }(); 178 (void )parsed ; 179return c ; 180} 181inline bool g_lfuse_gate () {static const bool on = [] {const char * v = std::getenv ("STRATA_LFUSE_GATE" );return v == nullptr || v [0 ]!= '0' ; }();return on ; } 182inline bool g_lfuse_pair () {static const bool on = [] {const char * v = std::getenv ("STRATA_LFUSE_PAIR" );return v == nullptr || v [0 ]!= '0' ; }();return on ; } 183inline bool g_qdedup () {static const bool on = [] {const char * v = std::getenv ("STRATA_VERIFY_QDEDUP" );return v != nullptr && std::atoi (v )!= 0 ; }();return on ; } 184// S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes 185// fork F4 (Eddoursul): 2-4 token dense projections read an interleaved copy of the q8_1 activations (bitwise the same 186// outputs); STRATA_MMVQ_IL=0 keeps native_mmvq's multi-column kernels 187inline bool g_mmvq_il () {static const bool on = [] {const char * v = std::getenv ("STRATA_MMVQ_IL" );return v == nullptr || v [0 ]!= '0' ; }();return on ; } 188// STRATA_SELECT_LONG=1 (opt-in): a window graph past select_long_at() cells takes the long-context QSA select 189// (qsa_block_topk_long's multi-CTA top-k through topk_scratch_, qsa_block_scores_long's shuffle-free decode scorer; 190// both compute capability 6.x by default, the same ids and score bits). Each costs ~6 more kernels a call, which only 191// a longer context pays back (4x GP100: 0.5 ms a window more at 1K, even at 30K, 4.0-4.7 ms less at 300K), so the 192// verifier keeps a second set of window graphs for it. Off: no scratch, no second graphs. 193inline bool select_long_on () { 194static const bool on = [] { 195const char * v = std::getenv ("STRATA_SELECT_LONG" ); 196if (v == nullptr || v [0 ]!= '1' )return false; 197if (strata::kernels::qsa_topk_multi_scratch_ints (1 ) <=0 ) {// a build without the multi-CTA kernels: no second graphs 198 std::fprintf (stderr ,"strata verify: STRATA_SELECT_LONG=1 needs the CUDA build with STRATA_EXPERIMENTAL_SM60; " 199"ignored\n" ); 200return false; 201 } 202return true; 203 }(); 204return on ; 205} 206// STRATA_SELECT_LONG_AT: the threshold in cells (default 65536; 0: always) 207inline int64_t select_long_at () { 208static const int64_t at = [] { 209const char * v = std::getenv ("STRATA_SELECT_LONG_AT" ); 210return v != nullptr && v [0 ]!= 0 ? (int64_t ) std::atoll (v ) : (int64_t )65536 ; 211 }(); 212return at ; 213} 214// 143-amdk: STRATA_QFUSE_HC - only the hyper-connection read writes its consumer's q8_1 image (not the GDN recurrence): gfx12 default (=0 / 1 forces off / on) 215inline bool g_qfuse_hc () { 216#if defined(STRATA_USE_HIP ) 217static const bool on = [] { 218const char * v = std::getenv ("STRATA_QFUSE_HC" ); 219if (v != nullptr )return std::atoi (v )!= 0 ; 220int dev = 0 ; 221cudaDeviceProp p ; 222return cudaGetDevice (& dev )== cudaSuccess && cudaGetDeviceProperties (& p ,dev )== cudaSuccess && 223 strata::kernels::gfx_arch_is_gfx12 (p .gcnArchName ); 224 }(); 225return on ; 226#else 227return false; 228#endif 229} 230// STRATA_GRAPH_PRIO=1 (opt-in): the window graph's kernel nodes keep their capturing stream's 231// priority (side_ high, sh_cs_ low). Unset / 0: every node at the launch stream's priority, as before. 232[[maybe_unused ]]inline bool graph_prio_on () {// (every HIP caller is guarded off) 233#if defined(STRATA_USE_HIP )|| defined(STRATA_HIP_GFX906 )|| defined(STRATA_GPU_METAL ) 234return false; 235#else 236static const bool on = [] {const char * v = std::getenv ("STRATA_GRAPH_PRIO" );return v != nullptr && std::atoi (v )!= 0 ; }(); 237return on ; 238#endif 239} 240// STRATA_GRAPH_PRIO: the capture and graph queries by CUDA version (13 renamed the edge-data forms: the same split as 241// verify_kernels.cu's and the PDL edge check above). Nothing is returned for the edge data. 242#if !defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 )&& !defined(STRATA_GPU_METAL ) 243inline cudaError_t prio_capture_deps (cudaStream_t s ,cudaStreamCaptureStatus * st ,const cudaGraphNode_t ** deps ,size_t * n ) { 244#if CUDART_VERSION >=13000 245return cudaStreamGetCaptureInfo (s ,st ,nullptr ,nullptr ,deps ,nullptr ,n ); 246#elif CUDART_VERSION >=12030 247return cudaStreamGetCaptureInfo_v3 (s ,st ,nullptr ,nullptr ,deps ,nullptr ,n ); 248#else 249return cudaStreamGetCaptureInfo_v2 (s ,st ,nullptr ,nullptr ,deps ,n ); 250#endif 251} 252inline cudaError_t prio_node_deps (cudaGraphNode_t node ,cudaGraphNode_t * deps ,size_t * n ) { 253#if CUDART_VERSION >=13000 254return cudaGraphNodeGetDependencies (node ,deps ,nullptr ,n ); 255#elif CUDART_VERSION >=12030 256return cudaGraphNodeGetDependencies_v2 (node ,deps ,nullptr ,n ); 257#else 258return cudaGraphNodeGetDependencies (node ,deps ,n ); 259#endif 260} 261#endif 262// fork 34a35db + b063c13 (Eddoursul), STRATA_SIDE_MIXER=1 / =2: the mixer's work that reads only the layer's input on 263// branches of the window's graph (bitwise the same outputs); 0 = in line, and no branch stream is created. Unset: 2 on a 264// compute capability 12.0 card (sm120_series.hpp; STRATA_SM120_PERF=0 turns it off), 0 elsewhere. 265inline int g_side_mixer () { 266static const int env = [] {const char * v = std::getenv ("STRATA_SIDE_MIXER" );return v ? std::max (0 , std::min (2 , std::atoi (v ))) :-1 ; }(); 267if (env >=0 )return env ; 268#if defined(STRATA_USE_HIP )|| defined(STRATA_GPU_METAL ) 269return 0 ; 270#else 271static int per_dev [64 ];// 0 unknown, else mode + 1 272int dev = 0 ; 273if (cudaGetDevice (& dev )!= cudaSuccess || dev < 0 || dev >=64 ) {cudaGetLastError ();return 0 ; } 274if (!per_dev [dev ]) { 275int maj = 0 ,mnr = 0 ; 276const bool ok = cudaDeviceGetAttribute (& maj ,cudaDevAttrComputeCapabilityMajor ,dev )== cudaSuccess && 277cudaDeviceGetAttribute (& mnr ,cudaDevAttrComputeCapabilityMinor ,dev )== cudaSuccess ; 278if (!ok )cudaGetLastError (); 279per_dev [dev ]= 1 + (ok && strata::sm120_default (maj ,mnr ) ?2 :0 ); 280 } 281return per_dev [dev ]- 1 ; 282#endif 283} 284// STRATA_ROUTE_PRIOR=lambda: residency-biased routing (the top-10 picked again with a logit bonus for the resident 285// experts; route_prior.cu). OFF unless asked for (STRATA_ROUTE_PRIOR=1.5, strata::kRoutePriorSmallCard in sm120_series.hpp, is the value the 286// app's Expert-settings row writes): 0.2.7 turned 1.5 on by itself on a discrete NVIDIA card of 13 GiB or less, and the owner took that default 287// back on 2026-10-29 (#4402: repetition loops and weaker results in long agent sessions). With nothing set this is 0.2.6's behaviour, exactly. 288// Measured on an RTX 3060 12 GB only (IQ3_XXS; at 1.5 story +15%, code +37% decode against off). Any value in the variable wins on every card. 289// The value is read once. 290inline float g_route_prior () { 291static const char * const env_s = std::getenv ("STRATA_ROUTE_PRIOR" ); 292static const float lambda = strata::route_prior_resolve (env_s , false, false,0.0 ); 293return lambda ; 294} 295inline bool g_qfuse () {static const bool on = [] {const char * v = std::getenv ("STRATA_QFUSE" );return v != nullptr && std::atoi (v )!= 0 ; }();return on ; } 296#define VDBG (...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) 297 298struct Bump { 299uint8_t * base = nullptr ; 300uint64_t used = 0 ; 301template < typename T > T * take (uint64_t n ) { 302T * p = base ? (T * ) (base + used ) :nullptr ; 303used += (n * sizeof (T )+ 255 )& ~255ull ; 304return p ; 305 } 306}; 307 308// #649 (HIP, opt-in A/Bs for the gfx1030 verify timeouts; CUDA never reads them) 309// STRATA_VERIFY_COHERENT=1 the handshake words and rows in explicitly coherent (fine-grained) host memory 310// STRATA_DOORBELL_STORE=1 the GPU stores each step's ring instead of read-modify-writing it over PCIe 311bool env_on (const char * name ) { 312const char * e = std::getenv (name ); 313return e != nullptr && e [0 ]!= 0 && e [0 ]!= '0' ; 314} 315#if defined(STRATA_USE_HIP ) 316const bool g_coherent = env_on ("STRATA_VERIFY_COHERENT" ); 317const bool g_doorbell_store = env_on ("STRATA_DOORBELL_STORE" ); 318#endif 319const bool g_trace = env_on ("STRATA_VERIFY_TRACE" ); 320// STRATA_LAUNCH_PROBE (STRIX-TDR): process start, and the first windows' launch timing 321const Clock ::time_point g_proc_t0 = Clock ::now (); 322Clock ::time_point probe_proc_t0 () {return g_proc_t0 ; } 323const bool g_no_multi_gr = env_on ("STRATA_NO_MULTI_GR" );// #783 PR-g: per-token GR reads/writes and generic-T kernels again 324const bool g_no_batch_kv = env_on ("STRATA_NO_BATCH_KV_STEP" );// #783 PR-d: per-token K/V and indexer appends again 325// STRATA_BATCH_SELF_COMMIT=1 (opt-in): a batch window whose rows are each another slot's one token keeps them itself, 326// as a one-token window does (record_window): the GDN conv histories and states advance inside the window graph, and 327// no commit graph runs after it. Such a window's commit is unconditional (each slot keeps its one row), and the rest 328// of the commit graph only repeats what the window wrote: the indexer tails are put back and appended again from the 329// same rows, the PLE histories are put back to the window's own snapshot. 330// Read at the first use, not at program start: the engine sets the Windows gfx1151 parallel-request defaults (arch_defaults.cpp) in main(), 331// after namespace-scope constants are initialised, so a constant here would never see them. 332bool batch_self_commit_on () {static const bool v = env_on ("STRATA_BATCH_SELF_COMMIT" );return v ; } 333#define g_batch_self_commit (batch_self_commit_on()) 334// STRATA_QSA_SLOTS=1 (opt-in): in a batch window, a QSA layer's block scores, top-k and attention run as one launch 335// each over the window's rows (up to 8 per launch, each row reading its own slot's indexer keys and K/V) instead of 336// one call per row; every row is computed by the same kernel with the same arithmetic as its own call. Not with a 337// streamed KV cache (a row's block resolve could evict the blocks an earlier row of the same slot selected). 338bool qsa_slots_on () {static const bool v = env_on ("STRATA_QSA_SLOTS" );return v ; } 339#define g_qsa_slots (qsa_slots_on()) 340 341// every row of a batch window is another slot's (no slot has proposal rows) 342bool one_row_per_slot (const int * rows ,int S ) { 343for (int i = 0 ;i < S ;++ i ) 344for (int j = i + 1 ;j < S ;++ j ) 345if (rows [i ]== rows [j ])return false; 346return S >=1 ; 347} 348bool batch_self_commits (const int * rows ,int S ) {return g_batch_self_commit && one_row_per_slot (rows ,S ); } 349 350// The shared expert runs on its own stream, forked off and joined back per layer (`sh_fork` in record_window). The 351// overlap pays off on CUDA, where it was added (cfd3b72). On HIP a cross-stream event dependency costs more than the 352// shared expert takes to run, so there the fork starts off: same binary, same 48,067-token prompt, three runs each on a 353// Radeon AI PRO R9700 (gfx1201, ROCm 6.4.3), the fork off decodes at 62.9 t/s against 43.4 t/s with it on. The 354// profiler turns the fork off to time the stages, so a profiled run never showed that. #816 reports the same fall on a 355// gfx1030 (RX 6800, Windows, 42.5 -> 56.4 t/s). STRATA_SH_STREAM overrides either default: `=1` forks, `=0` does not. 356// Strix Halo (gfx1151, unified memory) is the exception: the fork pays there (+1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL decode 357// at 8K, ids identical), so the gfx1151 arch table sets STRATA_SH_STREAM=1 on Linux. On Windows gfx1151 the fork is slower (0.2.7, 358// Qwen IQ3_S: decode -6.4% with it, ids identical), so there the table leaves it out and this default (off on HIP) applies. 359// Read on first use, after that table ran. 360bool sh_stream_on () { 361static const bool on = [] { 362if (const char * v = std::getenv ("STRATA_SH_STREAM" ))return v [0 ]!= '0' ; 363#if defined(STRATA_USE_HIP ) 364return false; 365#else 366return true; 367#endif 368 }(); 369return on ; 370} 371 372// 0.2.2: the zero-doorbell window graph has one host wait, the PLE flag (layer 1's wait kernel spins until the host has read 373// the window's PLE rows). Raised after the launch returns, it can deadlock HIP on the very first launch of a graph: the 374// stall report of a hung first window (gfx1151, 910-token prompt, about 1 run in 6) shows the host inside hipGraphLaunch 375// waiting for a runtime lock while the runtime's worker waits for the GPU, which is spinning on this flag; the raise that 376// would free it sits behind the launch. So the first launch of each window graph reads the rows and raises the flag BEFORE 377// the launch (the wait then passes at once); later launches keep the order that overlaps the read with layer 0 (reading 378// first costs about 1.4% decode on gfx1151). Mode 0: never, 1: every launch, 2: the first launch of each graph. Default: 379// 2 on HIP, 0 elsewhere (the CUDA path is unchanged). STRATA_VERIFY_EARLY_PLE_FLAG=0 / 1 / 2 forces a mode. 380int early_ple_flag_mode () { 381static const int mode = [] { 382if (const char * v = std::getenv ("STRATA_VERIFY_EARLY_PLE_FLAG" ))return std::atoi (v )< 0 ?0 : std::min (2 , std::atoi (v )); 383#if defined(STRATA_USE_HIP ) 384return 2 ; 385#else 386return 0 ; 387#endif 388 }(); 389return mode ; 390} 391 392// A one-token window always keeps its token, so its graph advances the sequence state itself (the GDN conv history 393// and recurrence state) and Verifier::commit launches no commit graph after it (eddoursul's fork, F7). CUDA only: 394// HIP keeps the commit graph after every window (STRATA_ONE_TOKEN_COMMIT=0 does too). 395// The head's hyper-connection read for the window's tokens in one launch set (CUDA; HIP: opt-in STRATA_HEAD_MIX_MULTI=1, which the 396// gfx12 table sets; =0 keeps gr_read per token): bitwise the same sums. 397bool head_mix_multi_enabled () { 398#if defined(STRATA_USE_HIP ) 399static const bool on = [] { 400const char * v = std::getenv ("STRATA_HEAD_MIX_MULTI" ); 401return v != nullptr && std::atoi (v )!= 0 ; 402 }(); 403return on ; 404#else 405static const bool on = [] { 406const char * v = std::getenv ("STRATA_HEAD_MIX_MULTI" ); 407return v == nullptr || std::atoi (v )!= 0 ; 408 }(); 409return on ; 410#endif 411} 412 413// 143-amdk: the wait for a host flag folded into the copy that follows it (wait_copy_i32_from_mapped, 414// copy_rows_from_mapped_after): same reads, same values, one kernel node fewer each. A dependent kernel costs ~2.4 us in a 415// gfx1201 graph whatever it does; measured on gfx12 only, so it is on there by default. STRATA_FUSE_WAIT=0 / 1 forces it 416// off / on (HIP builds; a CUDA build never fuses). 417// the Turing series (STRATA_SM75_PERF=1, sm75_series.hpp) defaults of the CUDA build's switches below, read per device 418bool device_is_sm75 () { 419#if defined(STRATA_USE_HIP ) 420return false; 421#else 422static int per_dev [64 ];// 0 unknown, 1 no, 2 yes 423int dev = 0 ; 424if (cudaGetDevice (& dev )!= cudaSuccess || dev < 0 || dev >=64 )return false; 425if (!per_dev [dev ]) { 426int maj = 0 ,mnr = 0 ; 427const bool ok = cudaDeviceGetAttribute (& maj ,cudaDevAttrComputeCapabilityMajor ,dev )== cudaSuccess && 428cudaDeviceGetAttribute (& mnr ,cudaDevAttrComputeCapabilityMinor ,dev )== cudaSuccess ; 429if (!ok )cudaGetLastError (); 430per_dev [dev ]= ok && strata::sm75_default (maj ,mnr ) ?2 :1 ;// a Turing card with STRATA_SM75_PERF=1 431 } 432return per_dev [dev ]== 2 ; 433#endif 434} 435 436bool fuse_wait_on () { 437#if defined(STRATA_USE_HIP ) 438static const int env = [] { 439const char * v = std::getenv ("STRATA_FUSE_WAIT" ); 440return v != nullptr ? (std::atoi (v )!= 0 ?1 :0 ) :-1 ; 441 }(); 442if (env >=0 )return env != 0 ; 443static int per_dev [64 ];// 0 unknown, 1 no, 2 yes 444int dev = 0 ; 445if (cudaGetDevice (& dev )!= cudaSuccess || dev < 0 || dev >=64 )return false; 446if (!per_dev [dev ]) { 447cudaDeviceProp p ; 448per_dev [dev ]= cudaGetDeviceProperties (& p ,dev )== cudaSuccess && strata::kernels::gfx_arch_is_gfx12 (p .gcnArchName ) ?2 :1 ; 449 } 450return per_dev [dev ]== 2 ; 451#else 452// CUDA: STRATA_FUSE_WAIT=1 folds both waits (the plan's and the CPU rows'), =2 only the plan's, =0 neither. Turing 453// default 2 (RTX 2080 Ti, Flash-Next Q2_0, two runs each: +0.6..+1.4 % decode); the rows' version makes every row 454// block of the copy poll the flag over PCIe and was -1.5 % there, so it stays opt-in. 455static const int env = [] {const char * v = std::getenv ("STRATA_FUSE_WAIT" );return v != nullptr ? std::atoi (v ) :-1 ; }(); 456if (env >=0 )return env == 1 || env == 2 ; 457return device_is_sm75 (); 458#endif 459} 460// 143-amdk's rows version of the folded wait (copy_rows_from_mapped_after): HIP with fuse_wait_on, CUDA STRATA_FUSE_WAIT=1 461bool fuse_rows_on () { 462#if defined(STRATA_USE_HIP ) 463return fuse_wait_on (); 464#else 465static const bool on = [] {const char * v = std::getenv ("STRATA_FUSE_WAIT" );return v != nullptr && std::atoi (v )== 1 ; }(); 466return on ; 467#endif 468} 469 470// 143-amdk: STRATA_FUSE_CONVAB=1 - the GDN conv and the a/b projections in one launch. Opt-in: measured -0.3% on gfx1201 (the a/b dot chain is the longer one). 471bool fuse_convab_on () { 472#if defined(STRATA_USE_HIP ) 473static const bool on = [] {const char * v = std::getenv ("STRATA_FUSE_CONVAB" );return v != nullptr && std::atoi (v )!= 0 ; }(); 474return on ; 475#else 476return false; 477#endif 478} 479 480// 143-amdk: STRATA_FUSE_HITS - moe_hit_add folded into the combine (gfx12 default; =0 / 1 forces off / on) 481bool fuse_hits_on () { 482#if defined(STRATA_USE_HIP ) 483static const int env = [] {const char * v = std::getenv ("STRATA_FUSE_HITS" );return v != nullptr ? (std::atoi (v )!= 0 ?1 :0 ) :-1 ; }(); 484if (env >=0 )return env != 0 ; 485static int per_dev [64 ];// 0 unknown, 1 no, 2 yes 486int dev = 0 ; 487if (cudaGetDevice (& dev )!= cudaSuccess || dev < 0 || dev >=64 )return false; 488if (!per_dev [dev ]) { 489cudaDeviceProp p ; 490per_dev [dev ]= cudaGetDeviceProperties (& p ,dev )== cudaSuccess && strata::kernels::gfx_arch_is_gfx12 (p .gcnArchName ) ?2 :1 ; 491 } 492return per_dev [dev ]== 2 ; 493#else 494return false; 495#endif 496} 497 498bool one_token_self_commit () { 499#if defined(STRATA_USE_HIP ) 500static const bool on = [] { 501const char * v = std::getenv ("STRATA_ONE_TOKEN_COMMIT" );// HIP: opt-in (=1) 502return v != nullptr && std::atoi (v )!= 0 ; 503 }(); 504return on ; 505#else 506static const bool on = [] { 507const char * v = std::getenv ("STRATA_ONE_TOKEN_COMMIT" ); 508return v == nullptr || std::atoi (v )!= 0 ; 509 }(); 510return on ; 511#endif 512} 513 514bool mapped (size_t bytes ,void ** h ,void ** d ) { 515#if defined(STRATA_USE_HIP ) 516if (g_coherent ) { 517if (hipHostMalloc (h ,bytes ,hipHostMallocMapped |hipHostMallocCoherent | 518 (peer_portable () ?hipHostMallocPortable :0 ))!= hipSuccess ) 519return false; 520 std::memset (* h ,0 ,bytes ); 521return cudaHostGetDevicePointer (d ,* h ,0 )== cudaSuccess ; 522 } 523#endif 524if (strata::core::host_alloc_guarded (h ,bytes ,cudaHostAllocMapped | (peer_portable () ?cudaHostAllocPortable :0 ))!= cudaSuccess )return false;// multi-GPU: portable only with a peer - the peer card writes its rows into them 525 std::memset (* h ,0 ,bytes ); 526return cudaHostGetDevicePointer (d ,* h ,0 )== cudaSuccess ; 527} 528 529strata::kernels::QsaShapes shapes_of (const ModelGeometry & g ) {return qsa_shapes (g ); } 530 531const WeightRef * need (const LayerView & v ,const char * suffix , std::string & err ) { 532const WeightRef * r = v .get (suffix ); 533if (r == nullptr && err .empty ())err = v .name (suffix )+ " is missing" ; 534return r ; 535} 536 537bool native_of (const WeightRef * w ,const std::string & name , std::string & err ) { 538if (w == nullptr )return false; 539if (w -> native_data == nullptr ) { 540err = "verify: " + name + " is not served natively (run with --native)" ; 541return false; 542 } 543return true; 544} 545 546}// namespace 547 548namespace { 549std::atomic < const Verifier *> g_diag_verifier {nullptr }; 550void diag_active_verifier (std::FILE * f ) { 551if (const Verifier * v = g_diag_verifier .load ())v -> diag (f ); 552} 553// #267: every live verifier (a layer split has one per stage), for the release before the engine ends 554constexpr int kLiveMax = 16 ; 555std::atomic < Verifier *> g_live [kLiveMax ]; 556void release_live_verifiers (std::FILE * f ) { 557for (auto & slot :g_live ) 558if (Verifier * v = slot .load ()) { 559const Clock ::time_point t0 = Clock ::now (); 560const bool done = v -> release_gpu_waits (5000 ); 561if (f != nullptr ) 562 std::fprintf (f ,"strata: released the verify window's GPU waits (#267): the GPU %s\n" , 563done ? ("finished in " + std::to_string ((long long )ms_since (t0 ))+ " ms" ).c_str () 564 :"did not finish within 5 s" ); 565 } 566if (f != nullptr ) std::fflush (f ); 567} 568// the same, silent, with one bound for all of them (kfd_quiet.hpp, EXIT: an integrated gfx11's stop on a signal) 569bool release_live_verifiers_within (int ms ) { 570const Clock ::time_point t0 = Clock ::now (); 571bool all = true; 572for (auto & slot :g_live ) 573if (Verifier * v = slot .load ()) { 574const int64_t left = (int64_t )ms - (int64_t )ms_since (t0 ); 575if (!v -> release_gpu_waits (left > 0 ? (int )left :0 ))all = false; 576 } 577return all ; 578} 579// #649: the host side of STRATA_VERIFY_TRACE - a ring of the last kTraceN handshake events of every verifier 580struct TraceEv { 581int64_t t_ns ; 582const void * who ; 583int64_t window ,step ,layer ,aux ; 584uint32_t seq ,flag ,a ,b ; 585const char * what ; 586}; 587constexpr uint64_t kTraceN = 4096 ; 588TraceEv g_trace_ring [kTraceN ]; 589std::atomic < uint64_t > g_trace_next {0 }; 590int64_t trace_now_ns () { 591return std::chrono::duration_cast < std::chrono::nanoseconds > (Clock ::now ().time_since_epoch ()).count (); 592} 593std::string released_note (bool drained ) { 594return drained ?"; its GPU waits were released and the GPU finished (#267)" 595 :"; its GPU waits were released but the GPU did not finish within 5 s (#267)" ; 596} 597// #267 test hook: STRATA_TEST_VERIFY_STALL=N withholds the last layer's flag in the N-th window (1-based), so the 598// GPU spins on a flag nobody raises - the bounded window wait and the release are then what ends it. Unset: never. 599const int64_t g_test_stall = [] { 600const char * e = std::getenv ("STRATA_TEST_VERIFY_STALL" ); 601return e != nullptr ? (int64_t ) std::atoll (e ) : (int64_t )0 ; 602}(); 603// The overlapped split's hand-off wait on the GPU is bounded: STRATA_SPLIT_WAIT_MS (default 30000, 0 = no bound). 604// The host's own per-layer wait (20 s, #267) normally ends a stalled window first; this bound is the backstop for 605// a host that is gone (a killed process must not leave a kernel spinning on its card). 606const unsigned long long g_split_wait_ns = [] { 607const char * e = std::getenv ("STRATA_SPLIT_WAIT_MS" ); 608return (unsigned long long ) (e != nullptr ? std::atoll (e ) :30000 )* 1000000ull ; 609}(); 610// test hook: STRATA_TEST_HANDOFF_DROP=N - the writing stage's N-th window (1-based) leaves its hand-off flag down, as 611// if the publish were lost; the reading stage's bounded wait (or the host's) must then end the window cleanly. 612const int64_t g_test_drop = [] { 613const char * e = std::getenv ("STRATA_TEST_HANDOFF_DROP" ); 614return e != nullptr ? (int64_t ) std::atoll (e ) : (int64_t )0 ; 615}(); 616}// namespace 617 618bool Verifier ::release_gpu_waits (int timeout_ms ) { 619released_ .store (true); 620trace_ev ("RELEASE" ,-1 ,-1 ,timeout_ms ); 621// the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here 622// reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but 623// wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises. 624for (uint32_t * p : {h_flag_ ,h_flagA_ ,h_flagB_ ,hflag_in_h_ })// + an overlapped split's hand-off wait 625if (p != nullptr )* (volatile uint32_t * )p = UINT32_MAX ; 626 std::atomic_thread_fence (std::memory_order_seq_cst ); 627strata_store_fence (); 628const OnDevice on_device (device_ ); 629const Clock ::time_point t0 = Clock ::now (); 630for (cudaStream_t s : {cs_ ,copy_ }) { 631if (s == nullptr )continue ; 632while (cudaStreamQuery (s )== cudaErrorNotReady ) { 633if (ms_since (t0 )> timeout_ms ) { 634trace_ev ("RELEASE-NOT-DRAINED" ,-1 ,-1 , (int64_t )ms_since (t0 )); 635return false; 636 } 637 std::this_thread::sleep_for (std::chrono::milliseconds (1 )); 638 } 639 } 640trace_ev ("RELEASE-DRAINED" ,-1 ,-1 , (int64_t )ms_since (t0 ));// aux: ms the GPU took to finish once released 641return true; 642} 643 644void Verifier ::trace_ev (const char * what ,int64_t step ,int64_t layer ,int64_t aux )const { 645if (!g_trace )return ; 646auto rd = [](const uint32_t * p ) {return p ?* (const volatile uint32_t * )p :0u ; }; 647TraceEv & e = g_trace_ring [g_trace_next .fetch_add (1 ) %kTraceN ]; 648e = {trace_now_ns (),this ,windows ,step ,layer ,aux ,rd (h_seq_ ),rd (h_flag_ ),rd (h_flagA_ ),rd (h_flagB_ ),what }; 649} 650 651void Verifier ::trace_dump (std::FILE * f )const { 652if (!g_trace || f == nullptr )return ; 653static const char * names [kProfPer ]= {"pre" ,"hc-read0" ,"qkv gemv" ,"conv" ,"ab" ,"z" ,"rec" ,"kv-idx" ,"k/v rope" ,"kv append" ,"q" ,"scores+topk" ,"kv-resolve" ,"attention" ,"gate" ,"" ,"out-proj" ,"router+ring" ,"shared" ,"waitA" ,"VRAM hits" ,"waitB" ,"PCIe grp" ,"waitCPU" ,"combine" ,"" ,"head" ,"" ,"" ,"ymWait" ,"ymCopy" ,"ymAdd" ,"" ,"" ,"" ,"" }; 654const uint64_t end = g_trace_next .load (); 655const uint64_t n = end < 160 ?end :160 ; 656 std::fprintf (f ,"strata verify trace (#649): the last %llu handshake events (host clock, us before the last; " 657"words: seq = GPU rang, flag = CPU served, A = plan, B = copies)\n" , (unsigned long long )n ); 658const int64_t t_last = n ?g_trace_ring [(end - 1 ) %kTraceN ].t_ns :0 ; 659for (uint64_t i = end - n ;i < end ;++ i ) { 660const TraceEv & e = g_trace_ring [i %kTraceN ]; 661if (e .what == nullptr )continue ; 662 std::fprintf (f ," %10.1f %-20s v%p window %lld step %lld layer %lld aux %lld | seq %u flag %u A %u B %u\n" , 663 (double ) (t_last - e .t_ns ) /1000.0 ,e .what ,e .who , (long long )e .window , (long long )e .step , 664 (long long )e .layer , (long long )e .aux ,e .seq ,e .flag ,e .a ,e .b ); 665 } 666if (trace_h_ == nullptr || g_ == nullptr )return ; 667// the breadcrumbs: every stamp point the GPU passed in this window (ns of the GPU clock after the window's first) 668unsigned long long t0 = ~0ull ; 669for (size_t i = 0 ;i < trace_n_ ;++ i ) { 670const unsigned long long t = * (const volatile unsigned long long * ) (trace_h_ + i ); 671if (t != 0 && t < t0 )t0 = t ; 672 } 673if (t0 == ~0ull ) { 674 std::fprintf (f ,"strata verify trace: no GPU breadcrumb in this window (the GPU never started it)\n" ); 675return ; 676 } 677int64_t last_l = -1 ; 678for (int64_t l = 0 ;l <=g_ -> n_layers ;++ l ) 679for (int i = 0 ;i < kProfPer ;++ i ) 680for (int grp = 0 ;grp < 2 ;++ grp ) 681if (trace_h_ [(size_t ) ((l * kProfPer + i )* 2 + grp )]!= 0 )last_l = l ; 682 std::fprintf (f ,"strata verify trace: GPU breadcrumbs (us after the window's first), the GPU got as far as layer " 683"%lld:\n" , (long long )last_l ); 684for (int64_t l = 0 ;l <=g_ -> n_layers ;++ l ) {// T-TRI: every layer's wait(33-32) + compute(34-33), grp=0 (us) 685const unsigned long long t32 = trace_h_ [((l * kProfPer + 32 )* 2 + 0 )]; 686const unsigned long long t33 = trace_h_ [((l * kProfPer + 33 )* 2 + 0 )]; 687const unsigned long long t34 = trace_h_ [((l * kProfPer + 34 )* 2 + 0 )]; 688 std::fprintf (f ," T-TRI l=%2lld wait=%.1f us compute=%.1f us (32=%llu 33=%llu 34=%llu)\n" , 689 (long long )l , (double )(t33 - t32 ) /1000.0 , (double )(t34 - t33 ) /1000.0 , 690t32 ,t33 ,t34 ); 691 } 692for (int64_t l = std::max < int64_t > (0 ,last_l - 2 );l <= std::min < int64_t > (g_ -> n_layers ,last_l + 1 );++ l ) 693for (int grp = 0 ;grp < 2 ;++ grp ) { 694 std::string line ; 695char b [64 ]; 696for (int i = 0 ;i < kProfPer ;++ i ) { 697const unsigned long long t = trace_h_ [(size_t ) ((l * kProfPer + i )* 2 + grp )]; 698if (t == 0 )continue ; 699 std::snprintf (b ,sizeof b ," %s(%d)=%.1f" ,names [i ],i , (double ) (t - t0 ) /1000.0 ); 700line += b ; 701 } 702if (!line .empty ()) 703 std::fprintf (f ," layer %lld group %d:%s\n" , (long long )l ,grp ,line .c_str ()); 704 } 705 std::fflush (f ); 706} 707 708void Verifier ::diag (std::FILE * f )const { 709auto rd = [](const uint32_t * p ) {return p ?* (const volatile uint32_t * )p :0u ; }; 710// #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's 711const char * where = progress ().where .load (); 712const bool current = where != nullptr && std::strncmp (where ,"verify window" ,13 )== 0 ; 713 std::fprintf (f ," verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: " 714"served %u, plan (A) %u, copies (B) %u\n" ,current ?"" :" (last window, not the current stage)" , 715last_t_ , (long long )last_pos0_ ,cur_layer_ + 1 ,rd (h_seq_ ),rd (h_flag_ ),rd (h_flagA_ ),rd (h_flagB_ )); 716trace_dump (f );// #649: STRATA_VERIFY_TRACE=1 only 717} 718 719 720Verifier ::~Verifier () { 721#if defined(STRATA_GPU_METAL ) 722 strata::metal_engine::window_destroy (metal_ ); 723metal_ = nullptr ; 724#endif 725const Verifier * self = this ; 726g_diag_verifier .compare_exchange_strong (self ,nullptr ); 727for (auto & slot :g_live ) { 728Verifier * me = this ; 729slot .compare_exchange_strong (me ,nullptr ); 730 } 731if (cs_ )cudaStreamSynchronize (cs_ ); 732if (sh_cs_ )cudaStreamSynchronize (sh_cs_ ); 733if (prof_on_ ) {// knife-0 A: the per-window segment table at exit (STRATA_VERIFY_PROFILE=1; no compute change) 734const std::string prof_report = profile_by_t_report (); 735if (!prof_report .empty ()) std::fprintf (stderr ,"PROF-T %s" ,prof_report .c_str ()); 736 } 737for (auto & row :exec_ ) 738for (auto & e :row ) 739if (e )cudaGraphExecDestroy (e ); 740for (auto & row :exec_nr_ ) 741for (auto & e :row ) 742if (e )cudaGraphExecDestroy (e ); 743if (commit_exec_ )cudaGraphExecDestroy (commit_exec_ ); 744for (auto & kv :exec_bm_ ) 745if (kv .second )cudaGraphExecDestroy (kv .second ); 746for (auto & kv :commit_bm_ ) 747if (kv .second )cudaGraphExecDestroy (kv .second ); 748if (arena_b_ )cudaFree (arena_b_ ); 749if (h_commitb_ )cudaFreeHost (h_commitb_ ); 750for (auto * m : {& save_bm_ ,& dcommit_bm_ }) 751for (auto & kv :* m ) 752if (kv .second )cudaGraphExecDestroy (kv .second ); 753if (dc_arena_ )cudaFree (dc_arena_ ); 754if (h_commitd_ )cudaFreeHost (h_commitd_ ); 755if (qcnt_ )cudaFree (qcnt_ ); 756if (d_spec_ )cudaFree (d_spec_ ); 757if (tap_file_ ) std::fclose (tap_file_ ); 758#if !defined(STRATA_GPU_METAL )// (on Metal tap_dev_ is the window's unified-memory buffer, not an allocation of this object) 759if (tap_dev_ )cudaFree (tap_dev_ ); 760#endif 761if (tap_scratch_ )cudaFree (tap_scratch_ ); 762if (h_tap_ )cudaFreeHost (h_tap_ ); 763if (logit_bias_device_ )cudaFree (logit_bias_device_ ); 764for (float * b :slot_bias_dev_ )if (b )cudaFree (b ); 765if (slot_hist_d_ )cudaFree (slot_hist_d_ ); 766if (cs_ && cs_ != ext_stream_ )cudaStreamDestroy (cs_ );// set_stream: the stage's stream, shared, not ours 767if (sh_cs_ )cudaStreamDestroy (sh_cs_ ); 768if (copy_ ) {cudaStreamSynchronize (copy_ );cudaStreamDestroy (copy_ ); } 769if (side_ )cudaStreamDestroy (side_ ); 770if (side2_ )cudaStreamDestroy (side2_ ); 771for (cudaEvent_t e : {mfork_ ,mjoin_ ,pfork_ ,pjoin_ }) 772if (e )cudaEventDestroy (e ); 773if (commit_done_ )cudaEventDestroy (commit_done_ ); 774if (ev_done_ )cudaEventDestroy (ev_done_ ); 775if (ev_commit_ )cudaEventDestroy (ev_commit_ ); 776if (prof_pin_ )cudaFreeHost (prof_pin_ ); 777if (ev_fork_ )cudaEventDestroy (ev_fork_ ); 778if (ev_join_ )cudaEventDestroy (ev_join_ ); 779if (ev_hq_ )cudaEventDestroy (ev_hq_ ); 780for (cudaStream_t s :df_side_ ) 781if (s )cudaStreamDestroy (s ); 782if (df_fork_ )cudaEventDestroy (df_fork_ ); 783for (cudaEvent_t e :df_join_ ) 784if (e )cudaEventDestroy (e ); 785if (arena_ )cudaFree (arena_ ); 786if (hcount_d_ )cudaFree (hcount_d_ ); 787void * hosts []= {h_tok_ ,h_step_ ,h_pos_ ,h_commit_ ,h_ple_ ,h_out_ ,h_x_ ,h_ids_ ,h_w_ ,h_seq_ ,h_flag_ ,h_ymiss_ , 788h_flagA_ ,h_plan_ ,h_flagB_ ,h_plan_err_ ,h_nf_ ,herr_h_ ,hdrop_h_ ,h_bal_ ,h_latxlq_ }; 789for (void * h :hosts ) 790if (h )cudaFreeHost (h ); 791} 792 793int Verifier ::tap_total ()const { 794int n = 0 ; 795if (g_ == nullptr )return 0 ; 796for (int l :tap_req_ )if (l >=0 && l < g_ -> n_layers - 1 )++ n ; 797return n ; 798} 799 800bool Verifier ::tapping_chain ()const { 801if (g_ == nullptr || tap_req_ .empty ())return false; 802int have = 0 ; 803for (const Verifier * v = this ;v != nullptr ;v = v -> next_ ) { 804have += (int )v -> tap_layers_ .size (); 805if (v -> tap_layers_ .size ()> 0 && !v -> tap_on_ )return false; 806if (v -> le_ >=g_ -> n_layers )break ; 807 } 808return have == tap_total (); 809} 810 811bool Verifier ::gather_taps_host (float * dst ,int row0 ,int rows , std::string & err ) { 812const int64_t N = g_ -> n_embd ; 813const int nt_all = tap_total (); 814for (Verifier * v = this ;v != nullptr ;v = v -> next_ ) { 815if (!v -> tap_layers_ .empty ()&& v -> tap_on_ ) { 816const OnDevice on_stage (v -> device_ ); 817if (v -> tap_cs_ == nullptr && 818 (cudaStreamCreateWithFlags (& v -> tap_cs_ ,cudaStreamNonBlocking )!= cudaSuccess || 819cudaEventCreateWithFlags (& v -> tap_ev_ ,cudaEventDisableTiming )!= cudaSuccess )) { 820err = "verify: the tap gather stream could not be created" ; 821return false; 822 } 823int slot0 = 0 ; 824for (int l :tap_req_ )if (l >=0 && l < g_ -> n_layers - 1 && l < v -> lb_ )++ slot0 ; 825const int64_t nv = (int64_t )v -> tap_layers_ .size (); 826for (int r = 0 ;r < rows ;++ r ) { 827const cudaError_t ce = cudaMemcpyAsync (dst + ((size_t )r * (size_t )nt_all + (size_t )slot0 )* (size_t )N , 828v -> tap_dev_ + (size_t ) (row0 + r )* (size_t ) (nv * N ), (size_t ) (nv * N )* 4 , 829cudaMemcpyDeviceToHost ,v -> tap_cs_ ); 830if (ce != cudaSuccess ) {err = std::string ("verify: the tap gather to the host: " )+ cudaGetErrorString (ce );return false; } 831 } 832if (cudaStreamSynchronize (v -> tap_cs_ )!= cudaSuccess ) {err = "verify: the tap gather to the host did not finish" ;return false; } 833 } 834if (v -> le_ >=g_ -> n_layers )break ; 835 } 836return true; 837} 838 839bool Verifier ::gather_taps (float * landing ,int landing_device ,int row0 ,int rows ,int dst_row0 ,cudaStream_t wait_stream , std::string & err ) { 840const int64_t N = g_ -> n_embd ; 841const int nt_all = tap_total (); 842for (Verifier * v = this ;v != nullptr ;v = v -> next_ ) { 843if (!v -> tap_layers_ .empty ()&& v -> tap_on_ ) { 844const OnDevice on_stage (v -> device_ ); 845if (v -> tap_cs_ == nullptr && 846 (cudaStreamCreateWithFlags (& v -> tap_cs_ ,cudaStreamNonBlocking )!= cudaSuccess || 847cudaEventCreateWithFlags (& v -> tap_ev_ ,cudaEventDisableTiming )!= cudaSuccess )) { 848err = "verify: the tap gather stream could not be created" ; 849return false; 850 } 851// this stage's first tap among all of them: the requested layers below its first layer 852int slot0 = 0 ; 853for (int l :tap_req_ )if (l >=0 && l < g_ -> n_layers - 1 && l < v -> lb_ )++ slot0 ; 854const int64_t nv = (int64_t )v -> tap_layers_ .size (); 855for (int r = 0 ;r < rows ;++ r ) { 856const float * src = v -> tap_dev_ + (size_t ) (row0 + r )* (size_t ) (nv * N ); 857float * dst = landing + ((size_t ) (dst_row0 + r )* (size_t )nt_all + (size_t )slot0 )* (size_t )N ; 858const cudaError_t ce = v -> device_ == landing_device 859 ?cudaMemcpyAsync (dst ,src , (size_t ) (nv * N )* 4 ,cudaMemcpyDeviceToDevice ,v -> tap_cs_ ) 860 :cudaMemcpyPeerAsync (dst ,landing_device ,src ,v -> device_ , (size_t ) (nv * N )* 4 ,v -> tap_cs_ ); 861if (ce != cudaSuccess ) {err = std::string ("verify: the tap gather copy: " )+ cudaGetErrorString (ce );return false; } 862 } 863if (cudaEventRecord (v -> tap_ev_ ,v -> tap_cs_ )!= cudaSuccess ) {err = "verify: the tap gather event" ;return false; } 864const OnDevice on_dst (landing_device ); 865if (cudaStreamWaitEvent (wait_stream ,v -> tap_ev_ ,0 )!= cudaSuccess ) {err = "verify: the drafter stream cannot wait on a stage's taps" ;return false; } 866 } 867if (v -> le_ >=g_ -> n_layers )break ; 868 } 869return true; 870} 871 872// STRATA_TAP_FILE: one record per row of the window: int32 position, int32 input token, then n_taps x n_embd floats 873void Verifier ::tap_write (int T ,const int32_t * tokens ,int64_t pos0 ) { 874if (tap_file_ == nullptr )return ; 875const size_t per = tap_layers_ .size ()* (size_t )g_ -> n_embd ; 876for (int t = 0 ;t < T ;++ t ) { 877const int32_t hdr [2 ]= {(int32_t ) (pos0 + t ),tokens [t ]}; 878 std::fwrite (hdr ,sizeof hdr ,1 ,tap_file_ ); 879 std::fwrite (h_tap_ + (size_t )t * per ,sizeof (float ),per ,tap_file_ ); 880 } 881 std::fflush (tap_file_ ); 882} 883 884bool Verifier ::set_logit_bias (const std::vector < float >& bias , std::string & err ) { 885if (next_ && !next_ -> set_logit_bias (bias ,err ))return false; 886if (le_ >=0 && le_ < g_ -> n_layers )return true;// (the Metal window never sets le_: -1 = the last stage) 887const OnDevice on_device (device_ ); 888if (!bias .empty ()&& bias .size ()!= (size_t )n_vocab_ ) { 889err = "logit_bias vocabulary size mismatch" ;return false; 890 } 891if (bias != logit_bias_host_ && !bias .empty ()) { 892const size_t bytes = bias .size ()* sizeof (float ); 893if ((!logit_bias_device_ && cudaMalloc ((void ** )& logit_bias_device_ ,bytes )!= cudaSuccess )|| 894cudaMemcpy (logit_bias_device_ ,bias .data (),bytes ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 895err = "cannot upload logit_bias" ;return false; 896 } 897 } 898logit_bias_host_ = bias ; 899sampling_ .logit_bias = bias .empty () ?nullptr :logit_bias_device_ ; 900return true; 901} 902 903bool Verifier ::init (const WeightTable & wt ,const ModelGeometry & g ,SessionState & ss ,const VerifyHits & hits , 904const NativeHead * head ,int max_t , std::string & err ) { 905g_diag_verifier .store (this ); 906diag_verify_fn ().store (& diag_active_verifier ); 907for (auto & slot :g_live ) { 908Verifier * none = nullptr ; 909if (slot .load ()== this || slot .compare_exchange_strong (none ,this ))break ; 910 } 911release_gpu_fn ().store (& release_live_verifiers ); 912release_gpu_within_fn ().store (& release_live_verifiers_within ); 913cudaGetDevice (& device_ );// a layer split's stage on another GPU: its streams, graphs and buffers live there 914rr_stats_ = route_resident_cfg ().stats_on (device_ );// STRATA_ROUTE_RESIDENT: this GPU's counters, outside graph capture 915 strata::kernels::fused_gr_check ();// once per card: which bitwise-equal hyper-connection read runs there 916 strata::kernels::fused_gr_persist_init ();// opt-in STRATA_HC_PERSIST=1 (HIP) 917wt_ = & wt ; 918g_ = & g ; 919ss_ = & ss ; 920hits_ = hits ; 921head_ = head ; 922max_t_ = max_t ; 923sampling_ .greedy = true;// a fresh verifier samples greedily until set_sampling says otherwise 924sampling_ .temperature = 0.0f ; 925#if defined(STRATA_GPU_METAL ) 926if (metal_ == nullptr )metal_ = strata::metal_engine::window_create (); 927if (!strata::metal_engine::window_init (metal_ ,g ,ss ,max_t ,ss .qsa_states [ss .qsa_primary ()].max_cells ,& n_vocab_ ,err ))return false; 928if (!tap_req_ .empty ()) {// DFlash2: the Metal window writes the taps itself (metal/src/engine/dflash2.inc); tap_dev() is its unified-memory buffer 929const float * tp = nullptr ; 930if (!strata::metal_engine::window_taps (metal_ ,tap_req_ ,& tp ,err ))return false; 931tap_layers_ = tap_req_ ; 932tap_dev_ = const_cast < float *> (tp ); 933tap_on_ = true; 934 } 935return true; 936#endif 937// a window past kVerifyMaxT tokens runs as two token groups of at most kVerifyMaxT (record_window): the CPU experts 938// see one group at a time (and take a wider group as jobs of at most cpu::MAXT tokens) 939if (max_t < 2 || max_t > strata::kernels::kVerifyLongT ) { 940err = "verify: the window must hold 2.." + std::to_string (strata::kernels::kVerifyLongT )+ " tokens" ; 941return false; 942 } 943if (hits .d_res == nullptr || hits .cache_base == nullptr || hits .blob <=0 ) { 944err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with " 945"--expert-cache auto, no VRAM was left for it - the 'no VRAM is left for the expert cache' line above " 946"says how much is short and what makes room (a smaller --max-context, --kv q4_0, setup --draft-vocab en, " 947"images on the CPU)" ; 948return false; 949 } 950 std::string why ; 951if (!layer_verify_compatible (why )) { 952err = "verify: " + why + " (the verify window reproduces the default native decode path)" ; 953return false; 954 } 955if (!strata::kernels::fused_gr_supported (g .n_embd ,g .hc ,g .hc_lr )|| ss .k != (int ) strata::core::kCompiledGeometry .n_expert_used || g .ssm_state_size != 128 || 956g .ssm_d_conv != 4 ) { 957err = "verify: geometry differs from the artifact's" ; 958return false; 959 } 960if (le_ < 0 )le_ = g .n_layers ; 961if (lb_ < 0 || lb_ >=le_ || le_ > g .n_layers || (lb_ > 0 && hand_in_ == nullptr )|| 962 (le_ < g .n_layers && hand_out_ == nullptr )) { 963err = "verify: the stage's layer range or its hand-off buffers are wrong" ; 964return false; 965 } 966const WeightRef * wo = wt .find ("output.weight" ); 967if (wo == nullptr ) {err = "verify: output.weight is missing" ;return false; } 968n_vocab_ = wo -> ne1 ; 969 970const strata::kernels::QsaShapes s = shapes_of (g ); 971cap_ = strata::kernels::qsa_selection_width (strata::kernels::kTopkMaxCells ,s ); 972max_blocks_ = ss .qsa_states [ss .qsa_primary ()].max_cells /s .idx_block + 2 ; 973attn_scratch_floats_ = (int64_t ) strata::kernels::qsa_decode_attn_scratch_floats (cap_ ,s ); 974 975const uint64_t T = (uint64_t )max_t ,N = (uint64_t )g .n_embd ,HC = (uint64_t )g .hc ,K = (uint64_t )ss .k ; 976const uint64_t C = (uint64_t )g .ssm_conv_channels ,ZV = (uint64_t )g .ssm_value_dim ,HV = (uint64_t )g .ssm_v_heads ; 977const uint64_t NH = (uint64_t )g .n_head ,HD = (uint64_t )g .head_dim ,NKV = (uint64_t )g .n_head_kv ; 978const uint64_t IQ = (uint64_t )g .idx_q_heads ,ID = (uint64_t )g .idx_key_dim ; 979const uint64_t nG = (uint64_t )g .n_gdn_layers (),nQ = (uint64_t )g .n_qsa_layers (); 980const uint64_t HS = (uint64_t ) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM ; 981const uint64_t TS = (uint64_t ) (s .idx_block - 1 )* ID ; 982const int max_in = (int ) std::max < uint64_t > (std::max < uint64_t > (N ,ZV ),NH * HD ); 983 984// latent MoE: the A pack's native expert rows are ELL wide instead of n_embd. 985 { 986const auto & lay0 = strata::kernels::cpu::expert_layout (); 987latent_ = lay0 .native && !lay0 .fmt .empty ()&& lay0 .fmt [0 ].n_embd != (int64_t )N ; 988if (latent_ ) { 989lat_H_ = (int64_t )N ;lat_ELL_ = lay0 .fmt [0 ].n_embd ;lat_I_ = lay0 .fmt [0 ].n_ff ; 990lat_G_ = 8 ;lat_E_ = (int )lay0 .n_expert ;lat_K_ = (int )K ; 991const char * dense = std::getenv ("STRATA_LATENT_DENSE" ); 992if (dense == nullptr || dense [0 ]== 0 ) { 993err = "verify: latent A layout needs STRATA_LATENT_DENSE=<latent_dense_q8.bin>" ; 994return false; 995 } 996if (!lat_dense_ .open (dense ,g .n_layers ,lat_G_ , (int64_t )N ,lat_ELL_ ,err )) { 997err = "verify latent dense: " + err ; 998return false; 999 } 1000lat_fmt_ = lat_dense_ .fmt ();// Q4DU: every D/U kernel call below derives from it 1001const char * apack = std::getenv ("STRATA_LATENT_A" ); 1002lat_blob_ = (int64_t )lay0 .max_blob ; 1003if (apack == nullptr || apack [0 ]== 0 ) { 1004err = "verify: latent A layout needs STRATA_LATENT_A=<latent_a_pack/experts.bin>" ; 1005return false; 1006 } 1007if (!lat_a_ .open (apack ,g .n_layers ,lat_E_ ,lat_blob_ ,err )) { 1008err = "verify latent A: " + err ; 1009return false; 1010 } 1011 {// labels.bin beside the A pack: one int32 group label per (layer, expert), rows of E 1012 std::string lp = apack ; 1013const size_t slash = lp .find_last_of ('/' ); 1014lp = slash == std::string::npos ? std::string ("labels.bin" ) :lp .substr (0 ,slash + 1 )+ "labels.bin" ; 1015 std::FILE * lf = std::fopen (lp .c_str (),"rb" ); 1016if (lf == nullptr ) {err = "verify latent: " + lp + " missing" ;return false; } 1017lat_labels_ .resize ((size_t )g .n_layers * (size_t )lat_E_ ); 1018const size_t got = std::fread (lat_labels_ .data (),sizeof (int32_t ),lat_labels_ .size (),lf ); 1019 std::fclose (lf ); 1020if (got != lat_labels_ .size ()) {err = "verify latent: " + lp + " is too small" ;return false; } 1021for (const int32_t v :lat_labels_ ) 1022if (v < 0 || v >=lat_G_ ) {err = "verify latent: bad group label " + std::to_string (v );return false; } 1023 } 1024 } 1025 } 1026 1027if (latent_ ) { 1028if (lat_d_shared_ == nullptr ) { 1029const auto & shared = strata::core::latent_shared (); 1030lat_d_shared_ = shared .d ; 1031lat_u_shared_ = shared .u ; 1032lat_first_layer_ = shared .d != nullptr ?shared .first_layer :0 ; 1033lat_end_layer_ = shared .d != nullptr ?shared .end_layer :-1 ; 1034 } 1035if (lat_d_shared_ != nullptr && (lat_u_shared_ == nullptr || lat_first_layer_ < 0 || lb_ < lat_first_layer_ || 1036le_ > (lat_end_layer_ < 0 ?g .n_layers :lat_end_layer_ ))) { 1037err = "verify: shared latent tables do not cover the stage" ; 1038return false; 1039 } 1040 } 1041 1042// ---- mapped staging 1043bool ok = mapped (T * 4 , (void ** )& h_tok_ , (void ** )& m_tok_ )&& 1044mapped (T * strata::kernels::kStepCount * 4 , (void ** )& h_step_ , (void ** )& m_step_ )&& 1045mapped (T * (NH + NKV + IQ )* 4 , (void ** )& h_pos_ , (void ** )& m_pos_ )&& 1046mapped ((2 + T )* 4 + 16 , (void ** )& h_commit_ , (void ** )& m_commit_ )&& 1047mapped (T * N * 4 , (void ** )& h_ple_ , (void ** )& m_ple_ )&& 1048mapped (T * 4 + 16 , (void ** )& h_out_ , (void ** )& m_out_ )&& 1049mapped ((size_t ) strata::kernels::kVerifyLongT * strata::kernels::kNonfiniteBlocks * 4 , (void ** )& h_nf_ , 1050 (void ** )& m_nf_ )&& 1051mapped (T * N * 4 , (void ** )& h_x_ , (void ** )& m_x_ )&& 1052mapped (T * K * 4 , (void ** )& h_ids_ , (void ** )& m_ids_ )&& 1053mapped (T * K * 4 , (void ** )& h_w_ , (void ** )& m_w_ )&& 1054mapped (64 , (void ** )& h_seq_ , (void ** )& m_seq_ )&& 1055mapped (64 , (void ** )& h_flag_ , (void ** )& m_flag_ )&& 1056mapped (64 , (void ** )& h_flagA_ , (void ** )& m_flagA_ )&& 1057mapped (64 , (void ** )& h_flagB_ , (void ** )& m_flagB_ )&& 1058mapped (64 , (void ** )& h_plan_err_ , (void ** )& m_plan_err_ )&& 1059mapped (T * K * N * 4 , (void ** )& h_ymiss_ , (void ** )& m_ymiss_ ); 1060if (!ok ) {err = "verify: mapped staging allocation failed " + strata::core::pin_exhausted_hint ();return false; } 1061// DFlash2 taps: set_taps (the drafter) or STRATA_TAP_FILE (the research dump); off, and nothing is allocated or captured, otherwise 1062const char * tap_path = std::getenv ("STRATA_TAP_FILE" ); 1063if (tap_path != nullptr && tap_path [0 ]== '\0' )tap_path = nullptr ; 1064// A layer split's stage taps the requested layers inside its own range [lb_, le_) into its own buffer [max_t][its taps][n_embd]; 1065// gather_taps() lands every stage's rows on the drafter's card. The research dump (STRATA_TAP_FILE) needs the whole model in one verifier. 1066const bool tap_whole = lb_ == 0 && le_ == g .n_layers ; 1067if (!tap_whole )tap_path = nullptr ; 1068if (tap_path != nullptr || !tap_req_ .empty ()) { 1069tap_layers_ .clear (); 1070if (tap_path == nullptr ) { 1071for (int l :tap_req_ )if (l >=lb_ && l < le_ && l < g .n_layers - 1 )tap_layers_ .push_back (l ); 1072 }else { 1073const char * tl = std::getenv ("STRATA_TAP_LAYERS" ); 1074 std::string list = tl != nullptr && tl [0 ]!= '\0' ?tl :"5,15,25,35,45" ; 1075for (size_t i = 0 ;i < list .size ();) { 1076const size_t j = list .find (',' ,i ); 1077const int l = std::atoi (list .substr (i ,j == std::string::npos ? std::string::npos :j - i ).c_str ()); 1078if (l >=0 && l < g .n_layers - 1 )tap_layers_ .push_back (l ); 1079if (j == std::string::npos )break ; 1080i = j + 1 ; 1081 } 1082 } 1083tap_slot_ .assign ((size_t )g .n_layers ,-1 ); 1084for (size_t i = 0 ;i < tap_layers_ .size ();++ i )tap_slot_ [(size_t )tap_layers_ [i ]]= (int )i ; 1085const size_t nt = tap_layers_ .size (); 1086if (nt == 0 && tap_path == nullptr ) { 1087// a stage that holds none of the tapped layers: nothing to keep, nothing captured 1088 }else 1089if (nt == 0 || cudaMalloc ((void ** )& tap_dev_ , (size_t )T * nt * N * 4 )!= cudaSuccess || 1090 (tap_path != nullptr && (cudaMalloc ((void ** )& tap_scratch_ , (size_t )HC * N * 4 )!= cudaSuccess || 1091 !mapped ((size_t )T * nt * N * 4 , (void ** )& h_tap_ , (void ** )& m_tap_ )))) { 1092err = "verify: the DFlash2 tap buffers could not be allocated" ; 1093return false; 1094 } 1095if (tap_path != nullptr ) { 1096tap_file_ = std::fopen (tap_path ,"wb" ); 1097if (tap_file_ == nullptr ) {err = std::string ("verify: cannot write STRATA_TAP_FILE " )+ tap_path ;return false; } 1098const int32_t hdr [4 ]= {0x50415453 /* 'STAP' */ ,1 , (int32_t )N , (int32_t )nt }; 1099 std::fwrite (hdr ,sizeof hdr ,1 ,tap_file_ ); 1100for (int l :tap_layers_ ) {const int32_t v = l ; std::fwrite (& v ,sizeof v ,1 ,tap_file_ ); } 1101 std::fprintf (stderr ,"strata: STRATA_TAP_FILE %s: %zu taps of %lld floats per row\n" ,tap_path ,nt , (long long )N ); 1102 } 1103tap_on_ = true; 1104 } 1105if (bal_ != nullptr ) {// set_pcie_balance: four stamp words per (layer, group) 1106if (!mapped ((size_t )g .n_layers * 2 * 4 * 8 , (void ** )& h_bal_ , (void ** )& m_bal_ )) { 1107err = "verify: mapped balance stamps allocation failed" ; 1108return false; 1109 } 1110bal_p_ .assign ((size_t )g .n_layers * 2 ,0.0 ); 1111bal_nc_ .assign ((size_t )g .n_layers * 2 ,0 ); 1112bal_np_ .assign ((size_t )g .n_layers * 2 ,0 ); 1113bal_ok_ .assign ((size_t )g .n_layers * 2 ,0 ); 1114bal_ -> on = true; 1115 } 1116// the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1) 1117// | pad | dst2(kStagingBlobs u64) 1118 { 1119const int64_t cap = (int64_t ) (T * K ); 1120const int64_t i32 = 4 + (cap + 1 )+ cap + cap ; 1121const int64_t ptr_off = (i32 + 1 )& ~1ll ; 1122dst2_off_ = (ptr_off + 4 * cap + (cap + 1 )+ 1 + 1 )& ~1ll ; 1123plan_i32_ = dst2_off_ + 2 * kStagingBlobs ; 1124if (!mapped ((size_t )plan_i32_ * 4 * 2 + 64 , (void ** )& h_plan_ , (void ** )& m_plan_ )) { 1125err = "verify: mapped plan allocation failed " + strata::core::pin_exhausted_hint (); 1126return false; 1127 } 1128sink_ .counts = h_plan_ ; 1129sink_ .start = h_plan_ + 4 ; 1130sink_ .dst = sink_ .start + cap + 1 ; 1131sink_ .tok = sink_ .dst + cap ; 1132sink_ .ptr = (unsigned long long * ) (h_plan_ + ptr_off ); 1133sink_ .ptr2 = sink_ .ptr + cap ; 1134sink_ .start2 = h_plan_ + ptr_off + 4 * cap ; 1135sink_ .dst2 = (unsigned long long * ) (h_plan_ + dst2_off_ ); 1136sink_ .cap = cap ; 1137sink_ .publish = & Verifier ::publish_plan ; 1138sink_ .fetch = & Verifier ::fetch_dma ; 1139sink_ .ctx = this ; 1140 } 1141if (latent_ ) {// edge0 CPU share: the D stage's f32 xl rows land in mapped host memory (row t*G + g); the 1142// pool quantizes them into the native Q8_0 A activation on the host. One cudaHostAlloc, OUTSIDE the 1143// carve so the count pass never touches it (running it inside ran the alloc twice and leaked the first). 1144if (!mapped ((size_t )T * (size_t )lat_G_ * (size_t )lat_ELL_ * 4 , (void ** )& h_latxlq_ , (void ** )& m_latxlq_ )|| 1145 !mapped ((size_t )T * (size_t )lat_G_ * ((size_t )lat_ELL_ /32 )* 34 , (void ** )& m_latact0_ , (void ** )& m_latact0_ )|| 1146 !mapped (64 , (void ** )& h_xlseq_ , (void ** )& m_xlseq_ )) { 1147err = "verify: the latent xl mapped buffer failed" ;return false; 1148 } 1149if (cudaMalloc (& lat_act0_dev_ , (size_t )T * (size_t )lat_G_ * ((size_t )lat_ELL_ /32 )* 34 )!= cudaSuccess ) { 1150err = "verify: the latent act0 device scratch failed" ;return false; 1151 } 1152 } 1153 1154// APR: the rotated copy of the expert input (nat_xr_, T x N floats) only where a layer's gate/up is 1155// Hadamard-folded; its one reader is that layer's f.had_gu branch in the expert-input step below 1156bool had_gu_any = false; 1157 { 1158const auto & lay = strata::kernels::cpu::expert_layout (); 1159for (size_t l = 0 ;lay .native && l < lay .fmt .size ();++ l )had_gu_any = had_gu_any || lay .fmt [l ].had_gu ; 1160 } 1161// ---- the device arena: the same sequence counted, then carved 1162auto carve = [& ](Bump & b ) { 1163tok_ = b .take < int32_t > (T );step_ = b .take < int32_t > (T * strata::kernels::kStepCount ); 1164pos_ = b .take < int32_t > (T * (NH + NKV + IQ ));commit_ = b .take < int32_t > (2 + T ); 1165ple_ = b .take < float > (T * N );emb_ = b .take < float > (T * N );R_ = b .take < float > (T * HC * N ); 1166mixed_ = b .take < float > (T * N );bo_ = b .take < float > (T * N ); 1167inj_ = b .take < float > (T * HC );inj2_ = b .take < float > (T * HC ); 1168lo_ = b .take < float > (T * (uint64_t )g .hc_lr );rs_ = b .take < float > (T * HC );xn_ = b .take < float > (T * HC * N ); 1169// the q8_1 activations of one token group (or one column chunk of the head): at most kVerifyMaxT columns 1170const int qcols = (int ) std::min < uint64_t > (T , (uint64_t ) strata::kernels::kVerifyMaxT ); 1171xq_ = b .take < uint8_t > (strata::kernels::native_q8_1_bytes (max_in ,qcols )); 1172sh_xq_ = b .take < uint8_t > (strata::kernels::native_q8_1_bytes (max_in ,qcols )); 1173xil_ = b .take < uint8_t > (strata::kernels::native_q8_1_il_bytes (max_in , std::max (4 ,qcols )));// 147-verify: 5-8 columns too 1174qkv_L_ = b .take < float > (nG * T * C );h_L_ = b .take < float > (nG * T * C ); 1175gate_L_ = b .take < float > (nG * T * HV );beta_L_ = b .take < float > (nG * T * HV ); 1176z_ = b .take < float > (T * ZV );y_ = b .take < float > (T * ZV );y_dummy_ = b .take < float > (T * ZV ); 1177qfull_ = b .take < float > (T * NH * 2 * HD );qcur_ = b .take < float > (T * NH * HD ); 1178kcur_ = b .take < float > (T * NKV * HD );vcur_ = b .take < float > (T * NKV * HD ); 1179idx_raw_L_ = b .take < float > (nQ * T * ID );qidx_ = b .take < float > (T * IQ * ID ); 1180scores_ = b .take < float > (T * (uint64_t )max_blocks_ );sel_ = b .take < int32_t > (T * (uint64_t )cap_ ); 1181if (select_long_on ()&& strata::kernels::qsa_topk_multi_scratch_ints (T )> 0 )// STRATA_SELECT_LONG only 1182topk_scratch_ = b .take < int32_t > ((uint64_t ) strata::kernels::qsa_topk_multi_scratch_ints (T )); 1183attn_ = b .take < float > (T * NH * HD );attn32_ = b .take < float > (T * NH * HD ); 1184attn_scratch_ = b .take < float > (T * (uint64_t )attn_scratch_floats_ ); 1185tail_snap_ = b .take < float > (nQ * TS ); 1186logits_ = b .take < float > (T * (uint64_t )g .n_expert );w_ = b .take < float > (T * K );ids_ = b .take < int32_t > (T * K ); 1187shared_ = b .take < float > (T * N );parts_ = b .take < float > (T * K * N );hit_out_ = b .take < float > (T * K * N ); 1188hit_slot_ = b .take < int32_t > (T * K );hit_dst_ = b .take < int32_t > (T * K );hit_count_ = b .take < int32_t > (4 ); 1189plan_ = b .take < int32_t > (2 * ((uint64_t )plan_i32_ + 16 )); 1190staging_ = b .take < uint8_t > ((uint64_t ) (latent_ ?8 :1 )* kStagingBlobs * strata::kernels::cpu::expert_layout ().max_blob ); 1191hit_xq_ = b .take < uint8_t > (T * (N /32 )* 34 );hit_xs_ = b .take < float > (T * (N /32 )); 1192nat_xq_ = b .take < uint8_t > (T * (N /32 )* 36 ); 1193nat_xr_ = had_gu_any ?b .take < float > (T * N ) :nullptr ; 1194hit_scratch_ = b .take < uint8_t > (std::max < uint64_t > ( 1195 strata::kernels::moe_hit_grouped_scratch_bytes ((int64_t ) (T * K ),g .n_embd ,g .n_ff ), 1196 strata::kernels::native_expert_scratch_bytes ((int64_t ) (T * K ),g .n_ff ))); 1197head_mixed_ = b .take < float > (T * N );head_inj_ = b .take < float > (HC ); 1198sh_bf16_ = b .take < uint16_t > (T * N );sh_gate_ = b .take < float > (T * (uint64_t )g .n_ff ); 1199sh_up_ = b .take < float > (T * (uint64_t )g .n_ff );sh_g_ = b .take < float > (T + 4 ); 1200head_logits_ = b .take < float > (T * (uint64_t )n_vocab_ ); 1201arg_scratch_ = b .take < uint8_t > (strata::kernels::argmax_rows_scratch_bytes ((int )T )); 1202one_ = b .take < int32_t > (4 ); 1203hist_snap_ = b .take < float > (T * HS ); 1204ple_key_ = b .take < float > (T * (uint64_t ) strata::kernels::NG_HC_DIM );ple_val_ = b .take < float > (T * N ); 1205if (latent_ ) { 1206const uint64_t LG = (uint64_t )lat_G_ ,LELL = (uint64_t )lat_ELL_ ; 1207lat_xq_ = b .take < uint8_t > (T * (N /32 )* 36 ); 1208lat_xlq_ = b .take < uint8_t > (T * LG * (LELL /32 )* 36 ); 1209lat_uq_ = b .take < uint8_t > (T * K * (LELL /32 )* 36 ); 1210hq_dev_ = b .take < uint8_t > (T * K * (LELL /32 )* 36 ); 1211lat_xl_ = b .take < float > (T * LG * LELL ); 1212lat_yl_ = b .take < float > (T * K * LELL ); 1213// Shared tables cover this stage; the standalone arena keeps the full layer-major layout. 1214if (lat_d_shared_ == nullptr ) { 1215lat_d_ = b .take < uint8_t > ((uint64_t )g .n_layers * lat_dense_ .d_bytes ()); 1216lat_u_ = b .take < uint8_t > ((uint64_t )g .n_layers * lat_dense_ .u_bytes ()); 1217 }else { 1218lat_d_ = const_cast < uint8_t *> (lat_d_shared_ ); 1219lat_u_ = const_cast < uint8_t *> (lat_u_shared_ ); 1220 } 1221// Q3_K colscale: allocate every layer's device 1/s vector NOW, in plain stream 1222// context - the D stage's first call can otherwise land inside the verify 1223// window's CUDA graph capture, and cudaMalloc is not permitted while capturing 1224// (the serve-mode failure that killed engine instance 1 on 2026-11-07). 1225for (int64_t l = 0 ;l < g .n_layers ;++ l ) 1226if (strata::kernels::lat_gu_colscale_dev ((int )l , (int )lat_ELL_ )== nullptr && 1227 strata::kernels::lat_gu_colscale_host (l )!= nullptr ) 1228throw std::runtime_error ("the column-scale vectors could not be uploaded" ); 1229 } 1230 }; 1231Bump count ; 1232carve (count ); 1233if (cudaMalloc (& arena_ ,count .used )!= cudaSuccess ) { 1234err = "verify: the device arena (" + std::to_string (count .used >>20 )+ " MiB) does not fit" ; 1235return false; 1236 } 1237cudaMemset (arena_ ,0 ,count .used ); 1238if (hflag_out_d_ != nullptr && hcount_d_ == nullptr ) {// the overlapped split's hand-off counter 1239if (cudaMalloc ((void ** )& hcount_d_ ,64 )!= cudaSuccess ) {err = "verify: hand-off counter allocation failed" ;return false; } 1240cudaMemset (hcount_d_ ,0 ,64 ); 1241if (!mapped (64 , (void ** )& hdrop_h_ , (void ** )& hdrop_d_ )) {err = "verify: hand-off test word allocation failed" ;return false; } 1242 } 1243if (hflag_in_d_ != nullptr && herr_h_ == nullptr && 1244 !mapped (64 , (void ** )& herr_h_ , (void ** )& herr_d_ )) {err = "verify: hand-off error word allocation failed" ;return false; } 1245if (g_trace && trace_h_ == nullptr ) {// #649: the breadcrumbs, mapped so they read while the GPU hangs 1246trace_n_ = (size_t ) (g .n_layers + 1 )* kProfPer * 2 ; 1247if (!mapped (trace_n_ * 8 , (void ** )& trace_h_ , (void ** )& trace_m_ )) { 1248 (void )cudaGetLastError (); 1249trace_h_ = trace_m_ = nullptr ; 1250trace_n_ = 0 ; 1251 } 1252#if defined(STRATA_USE_HIP ) 1253 std::fprintf (stderr ,"strata verify trace (#649): on; coherent words %s, doorbell %s, HIP_HOST_COHERENT=%s " 1254"HSA_ENABLE_SDMA=%s GPU_MAX_HW_QUEUES=%s\n" ,g_coherent ?"explicit" :"default" , 1255g_doorbell_store ?"stored" :"incremented" , std::getenv ("HIP_HOST_COHERENT" ) ? std::getenv ("HIP_HOST_COHERENT" ) :"-" , 1256 std::getenv ("HSA_ENABLE_SDMA" ) ? std::getenv ("HSA_ENABLE_SDMA" ) :"-" , 1257 std::getenv ("GPU_MAX_HW_QUEUES" ) ? std::getenv ("GPU_MAX_HW_QUEUES" ) :"-" ); 1258#else 1259 std::fprintf (stderr ,"strata verify trace (#649): on\n" ); 1260#endif 1261 } 1262prof_on_ = std::getenv ("STRATA_VERIFY_PROFILE" )!= nullptr ; 1263if (const char * rs = std::getenv ("STRATA_ROUTE_STATS" );rs != nullptr && rs [0 ]== '1' ) { 1264const size_t nrs = (size_t )17 * (size_t )g .n_layers * 16 ;// [T 0..16][layer][row 0..15] 1265if (cudaMalloc ((void ** )& rs_dev_ ,nrs * 8 )== cudaSuccess ) { 1266cudaMemset (rs_dev_ ,0 ,nrs * 8 ); 1267rs_on_ = true; 1268 }else { 1269rs_dev_ = nullptr ; 1270cudaGetLastError (); 1271 } 1272 } 1273if (prof_on_ ) { 1274const size_t np = (size_t )g .n_layers * kProfPer + 4 ; 1275if (cudaMalloc ((void ** )& prof_ ,np * 8 )!= cudaSuccess ) {prof_on_ = false;prof_ = nullptr ;cudaGetLastError (); } 1276else {cudaMemset (prof_ ,0 ,np * 8 );prof_h_ .assign (np ,0 ); } 1277 } 1278Bump real ; 1279real .base = (uint8_t * )arena_ ; 1280carve (real ); 1281if (latent_ && lat_d_shared_ == nullptr ) {// the carved pointers are real now: one blocking init-time 1282// upload, before any graph capture (with a shared pair there is nothing to upload) 1283for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 1284const cudaError_t cd = cudaMemcpy (lat_d_ + (size_t )l * lat_dense_ .d_bytes (),lat_dense_ .d (l ), 1285lat_dense_ .d_bytes (),cudaMemcpyHostToDevice ); 1286const cudaError_t cu = cd == cudaSuccess ?cudaMemcpy (lat_u_ + (size_t )l * lat_dense_ .u_bytes (), 1287lat_dense_ .u (l ),lat_dense_ .u_bytes (), 1288cudaMemcpyHostToDevice ) :cd ; 1289if (cu != cudaSuccess ) { 1290err = "verify latent: the D/U upload failed at layer " + std::to_string (l )+ " (" + 1291 std::string (cudaGetErrorString (cu ))+ ")" ; 1292return false; 1293 } 1294 } 1295 } 1296// the labels upload must not ride on the shared D/U pair: serve hands the pair to every verifier 1297// (set_shared_latent), in which case lat_d_shared_ != nullptr and the block above is skipped - 1298// the labels device copy is still required by latent_plan_rows / latent_u_grouped 1299if (latent_ ) { 1300const size_t lb = lat_labels_ .size ()* sizeof (int32_t ); 1301if (cudaMalloc ((void ** )& lat_labels_dev_ ,lb )!= cudaSuccess || 1302cudaMemcpy (lat_labels_dev_ ,lat_labels_ .data (),lb ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 1303err = "verify latent: the labels upload failed" ; 1304return false; 1305 } 1306 } 1307 { 1308const int32_t one = 1 ; 1309if (cudaMemcpy (one_ ,& one ,sizeof one ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 1310err = "verify: the arena could not be set" ; 1311return false; 1312 } 1313 } 1314 {// APR (prism.hadamard, hadamard.txt): the sign vectors on this device, before any graph capture 1315had_sx_ = strata::kernels::hadamard_device_signs (strata::kernels::cpu::hadamard_signs ((int )g .n_embd ), (int )g .n_embd ); 1316had_sh_ = strata::kernels::hadamard_device_signs (strata::kernels::cpu::hadamard_signs ((int )g .n_ff ), (int )g .n_ff ); 1317 } 1318sink_ .staging = (unsigned long long )staging_ ; 1319sink_ .staging_cap = kStagingBlobs ; 1320 (void )TS ; 1321// STRATA_GRAPH_PRIO=1 (opt-in): the window's streams carry priorities that their captured kernel 1322// nodes keep (the window graph is instantiated with cudaGraphInstantiateFlagUseNodePriority): the GDN gates / QSA 1323// indexer branch (side_) at the device's highest, cs_ and side2_ in the middle, the shared expert (sh_cs_) at the 1324// lowest (= the default). The indexer chain's 1-block kernels are then dispatched ahead of the q GEMV's queued 1325// blocks, and the shared expert behind the experts. Unset: every stream at the default priority, as before. 1326int gp_lo = 0 ,gp_hi = 0 ; 1327#if !defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 ) 1328const bool gprio = graph_prio_on ()&& cudaDeviceGetStreamPriorityRange (& gp_lo ,& gp_hi )== cudaSuccess && gp_lo != gp_hi ; 1329if (graph_prio_on ()&& !gprio ) (void )cudaGetLastError ();// (only a failed range query's error: unset clears nothing) 1330#else 1331const bool gprio = false;// (HIP: the default priority, as make_stream's below) 1332#endif 1333const int gp_mid = gprio ? (gp_lo + gp_hi ) /2 :0 ; 1334if (gprio ) std::fprintf (stderr ,"strata verify: STRATA_GRAPH_PRIO: stream priorities side %d, cs / side2 %d, shared expert %d\n" , 1335gp_hi ,gp_mid ,gp_lo ); 1336// STRATA_PIPED_CONCURRENT=1 (opt-in): a prompt can run on the same GPU while the batch windows run, so the windows' 1337// streams get the device's highest priority (HIP: the default priority, as the drafter's) 1338auto make_stream = [& ](cudaStream_t * s ,int gp = 0 )-> cudaError_t { 1339#if !defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 ) 1340static const bool hi = [] {// (STRATA_PIPED_CONCURRENT_PRIO=0: the default priority) 1341const char * v = std::getenv ("STRATA_PIPED_CONCURRENT" ); 1342const char * p = std::getenv ("STRATA_PIPED_CONCURRENT_PRIO" ); 1343return v != nullptr && std::atoi (v )!= 0 && (p == nullptr || std::atoi (p )!= 0 ); 1344 }(); 1345int lo = 0 ,top = 0 ; 1346if (hi ) { 1347if (cudaDeviceGetStreamPriorityRange (& lo ,& top )== cudaSuccess && 1348cudaStreamCreateWithPriority (s ,cudaStreamNonBlocking ,top )== cudaSuccess ) 1349return cudaSuccess ; 1350cudaGetLastError ();// (only the failed priority call's error: the default path clears nothing) 1351 } 1352if (gprio ) {// STRATA_GRAPH_PRIO: this stream's own priority (gp) 1353if (cudaStreamCreateWithPriority (s ,cudaStreamNonBlocking ,gp )== cudaSuccess )return cudaSuccess ; 1354cudaGetLastError (); 1355 } 1356#else 1357 (void )gp ; 1358#endif 1359return cudaStreamCreateWithFlags (s ,cudaStreamNonBlocking ); 1360 }; 1361bool copy_made = false; 1362#if defined(STRATA_USE_HIP )&& !defined(STRATA_HIP_GFX906 ) 1363// engine-latency, STRATA_COPY_HIP_PRIO=1 (opt-in): the copy stream at high priority, so it gets a hardware queue of 1364// its own (ROCm hands queues out per priority). Sharing one with the window's stream, --pcie-mode dma's copies and 1365// their host function queue behind the window's graph, which spins on the flag they raise (a timeout at layer 1). 1366 { 1367static const bool cp = [] {const char * v = std::getenv ("STRATA_COPY_HIP_PRIO" );return v != nullptr && std::atoi (v )!= 0 ; }(); 1368int lo = 0 ,hi = 0 ; 1369if (cp && hipDeviceGetStreamPriorityRange (& lo ,& hi )== hipSuccess ) 1370copy_made = hipStreamCreateWithPriority (& copy_ ,hipStreamNonBlocking ,hi )== hipSuccess ; 1371 (void )cudaGetLastError (); 1372 } 1373#endif 1374if (!copy_made && make_stream (& copy_ )!= cudaSuccess ) { 1375err = "verify: copy stream create failed" ; 1376return false; 1377 } 1378if (ext_stream_ != nullptr )cs_ = ext_stream_ ;// set_stream (pipelined windows): the stage's shared stream 1379else if (make_stream (& cs_ ,gp_mid )!= cudaSuccess )cs_ = nullptr ; 1380if (cs_ == nullptr || make_stream (& sh_cs_ ,gp_lo )!= cudaSuccess ) { 1381err = "verify: stream create failed" ; 1382return false; 1383 } 1384if (cudaEventCreateWithFlags (& commit_done_ ,cudaEventDisableTiming )!= cudaSuccess || 1385cudaEventCreateWithFlags (& ev_fork_ ,cudaEventDisableTiming )!= cudaSuccess || 1386cudaEventCreateWithFlags (& ev_join_ ,cudaEventDisableTiming )!= cudaSuccess || 1387cudaEventCreateWithFlags (& ev_hq_ ,cudaEventDisableTiming )!= cudaSuccess ) { 1388err = "verify: event create failed" ; 1389return false; 1390 } 1391 {// STRATA_DF_BRANCH=1 (opt-in): the mixer's side branches. Off by default: on Linux (open modules, GSP) a 1392// stage's window with the branches stopped inside its graph when an NVML query (nvidia-smi) came between 1393// requests (2x RTX 3090 and 2x RTX 2080 Ti, #905); never seen on Windows. 0 / unset: one stream, as before 1394const char * v = std::getenv ("STRATA_DF_BRANCH" ); 1395df_branch_ = v != nullptr && std::atoi (v )!= 0 ; 1396if (df_branch_ && df_fork_ == nullptr ) { 1397bool okb = cudaEventCreateWithFlags (& df_fork_ ,cudaEventDisableTiming )== cudaSuccess ; 1398for (int i = 0 ;i < 2 && okb ;++ i ) 1399okb = cudaStreamCreateWithFlags (& df_side_ [i ],cudaStreamNonBlocking )== cudaSuccess && 1400cudaEventCreateWithFlags (& df_join_ [i ],cudaEventDisableTiming )== cudaSuccess ; 1401if (!okb ) {cudaGetLastError ();df_branch_ = false; } 1402 } 1403 } 1404// Check whether 100% of experts across [lb_, le_) are resident in this stage's VRAM cache. 1405// When true, every layer plans on device and writes directly into parts_ without any CPU doorbells, 1406// wait_flag_ge spins, PCIe empty launches, or moe_hit_add copies. 1407all_resident_ = false; 1408ar_off_ = false; 1409h_res_ = hits .h_res ; 1410if (hits .h_res == nullptr || hits .d_res == nullptr || hits .cache_base == nullptr ) 1411 strata::dispatch::note ("init: all-resident graph declined: no expert table on this device (no cache, or no residency map)" ); 1412if (h_plan_err_ != nullptr )* (volatile uint32_t * )h_plan_err_ = 0 ; 1413if (hits .h_res != nullptr && hits .d_res != nullptr && hits .cache_base != nullptr ) { 1414const char * v_ar = std::getenv ("STRATA_VERIFY_ALL_RESIDENT" ); 1415#if defined(STRATA_CPU_ARM64 ) 1416// Windows on ARM64: this all-resident (zero-doorbell) path hangs the first decode window - measured here 1417// with the q3k l1280 pack, every expert resident: "verify window: 6 tokens at position 0, host at layer 1418// step 1, the GPU rang 0", no progress for 85 s, then the watchdog's 0xC0000409. Layer 1 was reached and 1419// never returned; with STRATA_VERIFY_ALL_RESIDENT=0 the same request answers in 0.8 s. A 24 GB card never 1420// reaches this path (its experts do not all fit), which is why the Linux validation passed. Opt-in here 1421// until the path is fixed, so the default cannot take it. 1422const bool ar_enabled = v_ar != nullptr && std::atoi (v_ar )!= 0 ; 1423#else 1424const bool ar_enabled = v_ar == nullptr || std::atoi (v_ar )!= 0 ; 1425#endif 1426if (ar_enabled ) { 1427bool all_ok = true; 1428for (int64_t l = lb_ ;l < le_ && all_ok ;++ l ) { 1429for (int64_t e = 0 ;e < g .n_expert ;++ e ) { 1430if (hits .h_res [l * g .n_expert + e ]< 0 ) { 1431all_ok = false; 1432break ; 1433 } 1434 } 1435 } 1436all_resident_ = all_ok ; 1437if (all_ok ) strata::dispatch::note ("init: all-resident graph selected (every expert of this stage is in VRAM)" ); 1438else strata::dispatch::note ("init: all-resident graph declined: some expert is not resident (doorbell graph with CPU / PCIe experts)" ); 1439 }else 1440 strata::dispatch::note ("init: all-resident graph declined: STRATA_VERIFY_ALL_RESIDENT=0" ); 1441 } 1442if (g_side_mixer ()> 0 && 1443 ((gprio ?make_stream (& side_ ,gp_hi ) :cudaStreamCreateWithFlags (& side_ ,cudaStreamNonBlocking ))!= cudaSuccess || 1444cudaEventCreateWithFlags (& mfork_ ,cudaEventDisableTiming )!= cudaSuccess || 1445cudaEventCreateWithFlags (& mjoin_ ,cudaEventDisableTiming )!= cudaSuccess || 1446 (gprio ?make_stream (& side2_ ,gp_mid ) :cudaStreamCreateWithFlags (& side2_ ,cudaStreamNonBlocking ))!= cudaSuccess || 1447cudaEventCreateWithFlags (& pfork_ ,cudaEventDisableTiming )!= cudaSuccess || 1448cudaEventCreateWithFlags (& pjoin_ ,cudaEventDisableTiming )!= cudaSuccess )) { 1449err = "verify: the mixer branch's stream / events could not be created" ; 1450return false; 1451 } 1452// E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on; 1453// exact, but neutral on RIBPC 1-2 GPUs: off by default) 1454 { 1455const char * v = std::getenv ("STRATA_VERIFY_DEVICE_PLAN" ); 1456// (not with set_always_publish: the device table may lag the host's while windows are in flight) 1457device_plan_ = !all_resident_ && !always_publish_ && (v != nullptr && std::atoi (v )!= 0 ); 1458 } 1459// (halo's STRATA_VERIFY_RESIDENT=1 is this window's all_resident_ graph above, which 0.1.39 has on by default) 1460if (g_qfuse ()|| g_qfuse_hc ()) {// S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero) 1461if (cudaMalloc ((void ** )& qcnt_ ,sizeof (unsigned )* (size_t ) (g .n_embd /32 ))!= cudaSuccess || 1462cudaMemset (qcnt_ ,0 ,sizeof (unsigned )* (size_t ) (g .n_embd /32 ))!= cudaSuccess ) { 1463cudaGetLastError (); 1464if (qcnt_ )cudaFree (qcnt_ ); 1465qcnt_ = nullptr ; 1466 } 1467 } 1468if (all_resident_ || device_plan_ ) { 1469bool ok2 = true; 1470if (device_plan_ ) 1471ok2 = cudaMalloc ((void ** )& skip_ ,64 )== cudaSuccess && cudaMemset (skip_ ,0 ,64 )== cudaSuccess ; 1472if (ok2 && hits .slot_off != nullptr && hits .n_slots > 0 ) { 1473ok2 = cudaMalloc ((void ** )& slot_off_d_ , (size_t )hits .n_slots * sizeof (unsigned long long ))== cudaSuccess && 1474cudaMemcpy (slot_off_d_ ,hits .slot_off , (size_t )hits .n_slots * sizeof (unsigned long long ), 1475cudaMemcpyHostToDevice )== cudaSuccess ; 1476 } 1477if (!ok2 ) {cudaGetLastError ();all_resident_ = false;device_plan_ = false; } 1478 } 1479 std::fprintf (stderr ,"strata verify: window up to %d tokens, %.1f MiB of device buffers%s\n" ,max_t , 1480 (double )count .used /1048576.0 , 1481all_resident_ ?" (100% VRAM resident: zero-doorbell graph)" :"" ); 1482return true; 1483} 1484 1485const float * Verifier ::final_R (int t )const {return R_ + (size_t )t * (size_t ) (g_ -> hc * g_ -> n_embd ); } 1486 1487// ================================ THE WINDOW, AS CAPTURED ================================ 1488// 1489// Plan v0.3 P6 (split window): with `groups_ == 2` the window's tokens are cut into two groups A = [0, T/2 up) and 1490// B = the rest, and the stream is ordered 1491// 1492// pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B) | post(1,A) pre(2,A) | ... 1493// 1494// so the CPU computes A's experts of layer l while the GPU runs B's mixer and router of layer l, and B's experts 1495// while the GPU combines A and runs A's layer l+1. B's mixer only needs A's mixer of the same layer (K/V, GDN 1496// state), never A's experts, so nothing waits that did not wait before. Every token's arithmetic is unchanged. 1497bool Verifier ::record_window (int T ,cudaStream_t cs , std::string & err ) { 1498using namespace strata::kernels ; 1499const ModelGeometry & g = * g_ ; 1500const WeightTable & wt = * wt_ ; 1501SessionState & ss = * ss_ ; 1502const int64_t N = g .n_embd ,HC = g .hc ,K = ss .k ,C = g .ssm_conv_channels ,ZV = g .ssm_value_dim ; 1503const int64_t HV = g .ssm_v_heads ,HK = g .ssm_k_heads ,NH = g .n_head ,HD = g .head_dim ,NKV = g .n_head_kv ; 1504const int64_t IQ = g .idx_q_heads ,ID = g .idx_key_dim ,NE = g .n_expert ,MT = max_t_ ; 1505const QsaShapes s = shapes_of (g ); 1506const GrShapes gs {g .n_embd ,g .hc ,g .hc_lr }; 1507const uint64_t gdn_floats = (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 1508 (uint64_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 1509const int64_t HS = (int64_t )NG_HIST * NG_HC_DIM ; 1510const int64_t TS = (s .idx_block - 1 )* ID ; 1511const bool ple_on = ss .ple .ready ()&& ple_stage (); 1512auto Rt = [& ](int t ) {return R_ + (size_t )t * HC * N ; }; 1513// a batch window is one group; a window past kVerifyMaxT tokens is always two (--lookup-max-t: each group holds 1514// at most kVerifyMaxT, what the per-group kernels and the CPU experts take) 1515const int G = ((split_ && T >=2 )|| T > kVerifyMaxT )&& !batch_rec_ ?2 :1 ; 1516// Pipelined windows must wait for the host verdict/snapshot fence before mutating state. 1517const bool self_commit = T == 1 && !always_publish_ && !batch_rec_ && !g_qfuse ()&& one_token_self_commit ();// see Verifier::commit 1518static const bool dec_batch = [] {const char * v = std::getenv ("STRATA_DEC_BATCH" );return v == nullptr || std::atoi (v )!= 0 ; }(); 1519// fork 34a35db: the GDN gates and the QSA indexer beside the projections (STRATA_SIDE_MIXER=1; 0 / unset = in line) 1520const int side_mixer_mode = g_side_mixer (); 1521const bool side_mixer = side_mixer_mode >=1 ; 1522const bool side_proj = side_mixer_mode >=2 && !batch_rec_ ;// fork b063c13: the GDN gate projection, the QSA queries 1523auto branch = [& ](cudaEvent_t e ,cudaStream_t from ,cudaStream_t to ,const char * what ) { 1524if (to == side_ )note_prio_fork (from );// STRATA_GRAPH_PRIO: where the high-priority branch leaves cs 1525if (cudaEventRecord (e ,from )== cudaSuccess && cudaStreamWaitEvent (to ,e ,0 )== cudaSuccess )return true; 1526err = std::string ("verify: the mixer branch could not " )+ what ; 1527return false; 1528 }; 1529// a batch window's rows each read their own slot's indexer: in line there 1530const bool sidem = side_mixer && !batch_rec_ ; 1531auto stamp = [& ](int64_t l ,int i ,int grp ) { 1532if (prof_on_ && grp == 0 )gpu_stamp (prof_ , (int ) (l * kProfPer + i ),cs ); 1533if (trace_m_ != nullptr && grp == 0 )gpu_stamp (trace_m_ , (int ) ((l * kProfPer + i )* 2 ),cs );// #649: grp=0 only (buffer holds 2 groups/slot; grp 2..7 overflowed into the next slots) 1534 }; 1535const int tb_ [2 ]= {0 , (T + 1 ) /2 },te_ [2 ]= {G == 2 ? (T + 1 ) /2 :T ,T }; 1536// S26 STRATA_LFUSE=1: where the shared expert's gate / scale fusions apply (the paths they replace are the ones taken) 1537auto lfuse_on = [& ](int n ) { 1538return g_lfuse ()&& ar_on ()&& native_moe_combine_enabled ()&& dec_batch && n > 1 && n <=8 && 1539shared_expert_native_bf16_enabled (); 1540 }; 1541bool sg_gated_ [2 ]= {false, false};// per group: the combine applies the shared gate 1542if (!batch_rec_ )groups_ [T ]= G ; 1543// Programmatic dependent launch (pdl.hpp; sm_90+, opt-in: STRATA_DF_PDL=1): the window's quantizations and dense 1544// projections may start while the kernel before them finishes, loading their weights before they wait for its 1545// output. Only a launch whose predecessors in the graph are all kernels gets programmatic edges; every value is 1546// the same as without them. 1547struct PdlScope { 1548bool prev ; 1549explicit PdlScope (bool on ) :prev (pdl_scope ()) {pdl_scope ()= on ; } 1550 ~PdlScope () {pdl_scope ()= prev ; } 1551 }pdl_window (G == 1 && pdl_supported ()&& (std::getenv ("STRATA_DF_PDL" )!= nullptr || (ar_on ()&& !batch_rec_ ))); 1552// BW-MEASURE (dispatch counters, include/strata/core/dispatch_stats.hpp): the window's counts go to the bin of this T and graph kind 1553// (0 = zero-doorbell all-resident, 1 = doorbell graph with CPU / PCIe experts, 2 = batch) 1554 strata::dispatch::Scope dsp_scope (T ,batch_rec_ ?2 : (ar_on () ?0 :1 )); 1555 strata::dispatch::notef ("win groups=%ld all_resident=%ld device_plan=%ld" , (long )G , (long )ar_on (), (long )device_plan_ ); 1556 strata::dispatch::notef ("win pdl=%ld side_mixer=%ld side_proj=%ld" , (long ) (G == 1 && pdl_supported ()&& (std::getenv ("STRATA_DF_PDL" )!= nullptr || (ar_on ()&& !batch_rec_ ))), (long )side_mixer_mode , (long )side_proj ); 1557 strata::dispatch::notef ("win df_branch=%ld sh_stream=%ld prof=%ld" , (long ) (df_branch_ && G == 1 && !batch_rec_ && !prof_on_ && !side_mixer ), (long )sh_stream_on (), (long )prof_on_ ); 1558// STRATA_DF_BRANCH: mixer work that reads only the layer's input runs on a side stream inside the graph. fork(i) 1559// makes side i depend on everything captured on `cs` so far, join(i) makes `cs` depend on everything captured on 1560// side i: a branch never races with what came before its fork or after its join. Not in a split or batch window, 1561// nor under the stage profiler (whose stamps are on `cs`). 1562const bool br = df_branch_ && G == 1 && !batch_rec_ && !prof_on_ && !side_mixer ;// STRATA_SIDE_MIXER wins 1563auto fork = [& ](int i ) { 1564cudaEventRecord (df_fork_ ,cs ); 1565cudaStreamWaitEvent (df_side_ [i ],df_fork_ ,0 ); 1566 }; 1567auto join = [& ](int i ) { 1568cudaEventRecord (df_join_ [i ],df_side_ [i ]); 1569cudaStreamWaitEvent (cs ,df_join_ [i ],0 ); 1570 }; 1571const int64_t nQall = g .n_qsa_layers (); 1572// a batch window: row t is slot t, whose state lives in its own session 1573auto slot_ss = [& ](int t )-> SessionState & {return batch_rec_ ?* slots_ [(size_t )brow_ [t ]] :ss ; }; 1574const int hrow0 = batch_rec_ ?row_base_ :0 ;// a slot group's own hand-off rows 1575// STRATA_BATCH_SELF_COMMIT: the window keeps its rows (no commit graph, nothing to snapshot for one) 1576const bool keep_rows = batch_rec_ && batch_self_commits (brow_ ,T ); 1577 1578// ---- the window's inputs, from mapped staging. With branches the steps and positions (first read by the first 1579// layer's mixer) cross PCIe on side 1 beside the embedding and the first hyper-connection read. 1580copy_i32_from_mapped (tok_ ,m_tok_ ,T ,cs ); 1581bool inputs_pending = false; 1582cudaStream_t in_s = cs ; 1583if (br ) { 1584fork (1 ); 1585in_s = df_side_ [1 ]; 1586inputs_pending = true; 1587 } 1588copy_i32_from_mapped (step_ ,m_step_ , (int64_t )T * kStepCount ,in_s ); 1589copy_i32_from_mapped (pos_ ,m_pos_ , (int64_t )MT * (NH + NKV + IQ ),in_s ); 1590// per-ROW positions of the K rows [t][NKV] and the indexer query rows [t][IQ] (for batched RoPE) 1591const int32_t * pos_k = pos_ + MT * NH ; 1592const int32_t * pos_i = pos_ + MT * (NH + NKV ); 1593 1594// ---- the embeddings, broadcast to the hc streams - or, in a later stage of a layer split, the previous stage's 1595// residual, pending write and inject (see set_stage) 1596const int64_t HB = Verifier ::handoff_floats (g ); 1597if (lb_ > 0 ) { 1598const float * hin = hand_in_ + (size_t )hrow0 * HB ;// the group's rows: [R][bo][inj] contiguous 1599// the overlapped split: this graph was launched before the previous stage finished - wait for its hand-off 1600if (hflag_in_d_ != nullptr && !batch_rec_ )wait_handoff (hflag_in_d_ ,1u ,herr_d_ ,g_split_wait_ns ,cs ); 1601copy_from_mapped (R_ ,hin , (int64_t )T * HC * N ,cs ); 1602copy_from_mapped (bo_ ,hin + (size_t )T * HC * N , (int64_t )T * N ,cs ); 1603copy_from_mapped (inj2_ ,hin + (size_t )T * (HC + 1 )* N , (int64_t )T * HC ,cs ); 1604 }else if (const NativeEmbed * ne = native_embed ()) {// plan v0.3 P6: the GGUF-form table 1605ne -> gather_dev (tok_ ,T ,emb_ ,cs ); 1606broadcast_streams (emb_ ,R_ ,N , (int )HC ,T ,cs ); 1607 }else { 1608const WeightRef * w = wt .find ("token_embd.weight" ); 1609if (w == nullptr || w -> codebook_iq4nl || (w -> code_bits != 2 && w -> code_bits != 4 && w -> code_bits != 8 )) { 1610err = "verify: token_embd.weight is missing or not an S2/S4/S8 tensor" ; 1611return false; 1612 } 1613const auto * codes = (const uint8_t * )w -> data ; 1614const auto * scales = (const float * ) (codes + w -> codes_bytes ); 1615const auto * offsets = w -> has_offset ? (const float * ) (codes + w -> codes_bytes + w -> scales_bytes ) :nullptr ; 1616const uint64_t row_codes = (uint64_t ) (w -> ne0 / (8 /w -> code_bits )); 1617const uint64_t row_groups = (uint64_t ) (w -> ne0 /w -> group_elems ); 1618embedding_gather_dev (codes ,scales ,offsets ,tok_ ,T ,w -> ne0 ,w -> code_bits ,w -> code_bias ,w -> group_elems , 1619row_codes ,row_groups ,emb_ ,cs ); 1620broadcast_streams (emb_ ,R_ ,N , (int )HC ,T ,cs ); 1621 } 1622 1623// per-layer state indices (GDN and QSA layers are numbered separately) 1624 std::vector < int64_t > gdn_idx ((size_t )g .n_layers ,-1 ),qsa_idx ((size_t )g .n_layers ,-1 ); 1625 { 1626int64_t qi = 0 ,gi = 0 ; 1627for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 1628if (is_qsa_layer (g ,l ))qsa_idx [(size_t )l ]= qi ++ ; 1629else gdn_idx [(size_t )l ]= gi ++ ; 1630 } 1631 } 1632 1633// ---------------------------------------------------------------- pre(l, group): up to the ring 1634auto pre = [& ](int64_t l ,int grp )-> bool { 1635const int tb = tb_ [grp ],te = te_ [grp ],n = te - tb ; 1636stamp (l ,0 ,grp ); 1637const LayerView v (wt ,l ); 1638const char * pfx [2 ]= {"hc_attn_" ,"hc_ffn_" }; 1639const WeightRef * wn [2 ],* wd [2 ],* wu [2 ],* wi [2 ]; 1640for (int h = 0 ;h < 2 ;++ h ) { 1641wn [h ]= need (v , (std::string (pfx [h ])+ "norm.weight" ).c_str (),err ); 1642wd [h ]= need (v , (std::string (pfx [h ])+ "down.weight" ).c_str (),err ); 1643wu [h ]= need (v , (std::string (pfx [h ])+ "up.weight" ).c_str (),err ); 1644wi [h ]= need (v , (std::string (pfx [h ])+ "inject.weight" ).c_str (),err ); 1645if (!wn [h ]|| !wd [h ]|| !wu [h ]|| !wi [h ])return false; 1646 } 1647// the previous layer's FFN write, folded into this layer's first read (a control vector after it has 1648// already applied it) 1649bool pending = l > 0 && !cvec ().covers (l - 1 ); 1650if (l == 1 && ple_on ) { 1651if (grp == 0 ) { 1652if (ar_on ())wait_flag_ge (m_flag_ ,1 ,cs ); 1653copy_from_mapped (ple_ ,m_ple_ , (int64_t )T * N ,cs ); 1654 } 1655float * normalized = (float * ) ((uint8_t * )ss .ple .scratch + ple_block_scratch_bytes ()); 1656static const bool ple_batch_env = [] { 1657const char * e = std::getenv ("STRATA_PLE_BATCH" ); 1658return !e || e [0 ]!= '0' ; 1659 }(); 1660const bool ple_batch_kv = ple_batch_env && dec_batch && n > 1 && ss .ple .w .key_bf16 != nullptr && 1661ss .ple .w .value_bf16 != nullptr && ple_native_bf16_enabled ()&& 1662ple_native_postops_enabled (); 1663// S25 (STRATA_PLE_BATCH=1): the key and value projections depend only on each row's n-gram embedding, so 1664// the group's rows run through the multi-row forms of the same kernels (the weights read once); every 1665// row's arithmetic is the single-row call's. The history-dependent rest stays row by row. 1666static const bool ple_batch = [] {const char * e = std::getenv ("STRATA_PLE_BATCH" );return e && e [0 ]== '1' ; }(); 1667PleWeights pw = ss .ple .w ; 1668const bool nkey = pw .key_native_data != nullptr && pw .key_bf16 == nullptr ; 1669const bool batched = !ple_batch_kv && ple_batch && n > 1 && (pw .key_bf16 != nullptr || nkey )&& ple_native_bf16_enabled (); 1670if (ple_batch_kv ) { 1671try { 1672bf16_gemv_fp32_mmvf_multi (ple_ + (size_t )tb * N ,N ,ss .ple .w .key_bf16 , 1673xn_ + (size_t )tb * HC * N ,HC * N ,N ,HC * N ,n ,cs ); 1674bf16_gemv_fp32_mmvf_multi (ple_ + (size_t )tb * N ,N ,ss .ple .w .value_bf16 , 1675z_ + (size_t )tb * N ,N ,N ,N ,n ,cs ); 1676 }catch (const std::exception & e ) { 1677err = std::string ("verify PLE multi: " )+ e .what (); 1678return false; 1679 } 1680 }else if (batched ) { 1681try { 1682if (pw .key_bf16 != nullptr ) 1683bf16_gemv_fp32_mmvf_multi (ple_ + tb * N ,N ,pw .key_bf16 ,ple_key_ + (size_t )tb * NG_HC_DIM , 1684NG_HC_DIM ,N ,NG_HC_DIM ,n ,cs ); 1685else { 1686native_quantize_q8_1 (ple_ + tb * N ,xq_ , (int )N ,n ,cs ); 1687native_mmvq (pw .key_native_type ,pw .key_native_data ,xq_ ,ple_key_ + (size_t )tb * NG_HC_DIM , 1688 (int )N ,NG_HC_DIM ,n ,cs ); 1689 } 1690bf16_gemv_fp32_mmvf_multi (ple_ + tb * N ,N ,pw .value_bf16 ,ple_val_ + tb * N ,N ,N ,N ,n ,cs ); 1691 }catch (const std::exception & e ) { 1692err = std::string ("verify PLE batch: " )+ e .what (); 1693return false; 1694 } 1695 } 1696// STRATA_DF_PLE (opt-in: STRATA_DF_PLE=1): the window's post-projection steps in one pass, bitwise the per-token loop 1697// below (the norms divide at run time as its norms do; the history advances token by token), which also 1698// writes the commit's history snapshots. Scratch: layer 0's expert rows, combined by now, and the 1699// hyper-connection read's `lo_`, which the read below rewrites. 1700static const bool ple_post_env = [] { 1701const char * e = std::getenv ("STRATA_DF_PLE" ); 1702return e != nullptr && std::atoi (e )!= 0 ; 1703 }(); 1704const bool ple_post = ple_batch_kv && ple_post_env && !batch_rec_ ; 1705// #783 PR-g (stuchapin909): the window's residual writes in one launch (STRATA_NO_MULTI_GR=1: per token) 1706const bool multi_write = !ple_post && dec_batch && !g_no_multi_gr && n > 1 ; 1707if (multi_write )gr_write_multi (Rt (tb ),bo_ + tb * N ,inj2_ + tb * HC ,gs ,Rt (tb ),n ,cs ); 1708if (ple_post ) { 1709float * qn = parts_ + (size_t )tb * K * N ;// n x 10240 (K * N = 25600 per row) 1710float * gated = hit_out_ + (size_t )tb * K * N ;// n x 10240 1711float * pgate = lo_ + (size_t )tb * g .hc_lr ;// n x 4 1712try { 1713if (gr_native_mmvf_enabled ())// gr_write's native write for the n rows in one launch 1714native_gr_post_multi (Rt (tb ),bo_ + tb * N ,inj2_ + tb * HC ,Rt (tb ), (int )N , (int )HC ,n ,HC * N , 1715N ,HC ,cs ); 1716else 1717for (int t = tb ;t < te ;++ t )gr_write (Rt (t ),bo_ + t * N ,inj2_ + t * HC ,gs ,Rt (t ),cs ); 1718native_ple_postops_batch_snap (xn_ + (size_t )tb * HC * N ,Rt (tb ),z_ + (size_t )tb * N ,ss .ple .hist , 1719ss .ple .w ,qn ,gated ,pgate ,n ,hist_snap_ + (size_t )tb * HS ,cs ); 1720 }catch (const std::exception & e ) { 1721err = std::string ("verify PLE (window): " )+ e .what (); 1722return false; 1723 } 1724 }else 1725for (int t = tb ;t < te ;++ t ) { 1726if (batched ) {pw .pre_key = ple_key_ + (size_t )t * NG_HC_DIM ;pw .pre_value = ple_val_ + t * N ; } 1727if (!multi_write )gr_write (Rt (t ),bo_ + t * N ,inj2_ + t * HC ,gs ,Rt (t ),cs ); 1728PleOut po ; 1729po .normalized = normalized ; 1730po .result = Rt (t ); 1731float * hist = batch_rec_ ?slot_ss (t ).ple_hist :ss .ple .hist ;// the row's own history 1732try { 1733if (ple_batch_kv ) { 1734ple_block_projected (xn_ + (size_t )t * HC * N ,z_ + (size_t )t * N ,Rt (t ),hist , 1735ss .ple .w ,po ,ss .ple .scratch ,cs ); 1736 }else { 1737ple_block (ple_ + t * N ,Rt (t ),hist ,pw ,po ,ss .ple .scratch ,cs ); 1738 } 1739ple_history_advance (hist ,normalized ,cs ); 1740 }catch (const std::exception & e ) { 1741err = std::string ("verify PLE: " )+ e .what (); 1742return false; 1743 } 1744if (!keep_rows )copy_from_mapped (hist_snap_ + (size_t )t * HS ,hist ,HS ,cs ); 1745 } 1746pending = false; 1747 } 1748auto gr_read_group = [& ](int half ,bool apply ,float * inj_prev ,float * inj_out ) { 1749 strata::dispatch::notef ("hc read: weights Q8_0 copies=%ld (0 = bf16 rows), half=%ld, qfuse=%ld" , (long ) (wd [half ]-> hc_q8 != nullptr ), (long )half , (long ) (qcnt_ != nullptr )); 1750FusedGrArgs fa [kFusedGrWideT ]; 1751for (int t = tb ;t < te ;++ t ) { 1752FusedGrArgs & a = fa [t - tb ]; 1753a .R = Rt (t );a .R_out = Rt (t );a .apply = apply ; 1754a .bo_prev = bo_ + t * N ;a .inj_prev = inj_prev + t * HC ; 1755a .w_norm = (const float * )wn [half ]-> data ;a .w_down = (const uint16_t * )wd [half ]-> data ; 1756a .w_up = (const uint16_t * )wu [half ]-> data ;a .w_inject = (const uint16_t * )wi [half ]-> data ; 1757a .q8_down = (const uint8_t * )wd [half ]-> hc_q8 ;a .q8_up = (const uint8_t * )wu [half ]-> hc_q8 ; 1758a .q8_inject = (const uint8_t * )wi [half ]-> hc_q8 ; 1759a .s_down = wd [half ]-> q8_scale ;a .s_up = wu [half ]-> q8_scale ; 1760a .eps = EPS ;a .lo = lo_ + t * g .hc_lr ;a .rs = rs_ + t * HC ; 1761a .inject_out = inj_out + t * HC ;a .mixed = mixed_ + t * N ; 1762if (qcnt_ != nullptr ) {// S26 STRATA_QFUSE: the consumer's q8_1 image written by the read itself 1763a .q8_cnt = qcnt_ ; 1764if (half == 0 )a .q8_mixed = xq_ + (size_t ) (t - tb )* (N /32 )* 36 ; 1765else if (strata::kernels::cpu::expert_layout ().native )a .q8_mixed = nat_xq_ + (size_t )t * (N /32 )* 36 ; 1766 } 1767 } 1768if (strata::kernels::fused_gr_read_persist (fa ,n ,cs ))return false;// STRATA_HC_PERSIST=1; q8_mixed is never set there 1769return fused_gr_read_multi (fa ,n ,xn_ + (size_t )tb * HC * N ,cs , (prof_on_ && grp == 0 ) ?prof_ :nullptr , 1770 (int ) (l * kProfPer + (half == 0 ?27 :30 ))); 1771 }; 1772const bool q8_attn = gr_read_group (0 ,pending ,inj2_ ,inj_ );// true: xq_ holds mixed's q8_1 (STRATA_QFUSE) 1773 {// measurement only: STRATA_DUMMY_NODES=k adds k empty kernel nodes per layer (what one node costs in a window) 1774static const int dummy = [] {const char * e = std::getenv ("STRATA_DUMMY_NODES" );return e != nullptr ? std::atoi (e ) :0 ; }(); 1775for (int d = 0 ;d < dummy ;++ d )gpu_noop (cs ); 1776 } 1777if (inputs_pending ) {// the window's steps and positions, before the first mixer reads them 1778join (1 ); 1779inputs_pending = false; 1780 } 1781stamp (l ,1 ,grp ); 1782float * xm = mixed_ + tb * N ; 1783bool il_ready = false;// xil_ holds xq_'s interleaved copy (reset whenever xq_ is rewritten) 1784// a projection input's q8_1 blocks and their interleaved copy in one launch (native_quantize_q8_1_il, the same 1785// bytes): Turing default (+0.5..+1 % decode, two launches fewer per GDN layer and per QSA layer); STRATA_QIL=0 / 1 1786// forces it off / on 1787auto quant_in = [& ](const float * x ,int n_in ) { 1788#if !defined(STRATA_USE_HIP ) 1789static const int qil_env = [] {const char * v = std::getenv ("STRATA_QIL" );return v != nullptr ? std::atoi (v ) :-1 ; }(); 1790const bool qil = qil_env >=0 ?qil_env != 0 :device_is_sm75 (); 1791if (qil && n >=2 && n <=4 && g_mmvq_il ()) { 1792 strata::kernels::native_quantize_q8_1_il (x ,xq_ ,xil_ ,n_in ,n ,cs ); 1793il_ready = true; 1794return ; 1795 } 1796#endif 1797native_quantize_q8_1 (x ,xq_ ,n_in ,n ,cs ); 1798il_ready = false; 1799 }; 1800auto mm = [& ](const WeightRef * w ,float * out ,int n_in ,int n_out ) { 1801if (g_mmvq_il ()&& strata::kernels::native_mmvq_il_supported (w -> native_type ,n ,n_out )) { 1802if (!il_ready && n >=2 ) {// one column reads the plain q8_1 blocks 1803 strata::kernels::native_q8_1_interleave (xq_ ,xil_ ,n_in ,n ,cs ); 1804il_ready = true; 1805 } 1806 strata::kernels::native_mmvq_il (w -> native_type ,w -> native_data ,xq_ ,xil_ ,out ,n_in ,n_out ,n ,cs ); 1807 }else { 1808native_mmvq (w -> native_type ,w -> native_data ,xq_ ,out ,n_in ,n_out ,n ,cs ); 1809 } 1810 }; 1811try { 1812if (!is_qsa_layer (g ,l )) { 1813// ======================= GDN ======================= 1814const WeightRef * wqkv = need (v ,"attn_qkv.weight" ,err ),* wg = need (v ,"attn_gate.weight" ,err ), 1815* wout = need (v ,"ssm_out.weight" ,err ),* wa = need (v ,"ssm_alpha.weight" ,err ), 1816* wb = need (v ,"ssm_beta.weight" ,err ),* wc = need (v ,"ssm_conv1d.weight" ,err ), 1817* wnm = need (v ,"ssm_norm.weight" ,err ),* wdt = need (v ,"ssm_dt.bias" ,err ), 1818* wsa = need (v ,"ssm_a" ,err ); 1819if (!wqkv || !wg || !wout || !wa || !wb || !wc || !wnm || !wdt || !wsa )return false; 1820if (!native_of (wqkv ,v .name ("attn_qkv.weight" ),err )|| !native_of (wg ,v .name ("attn_gate.weight" ),err )|| 1821 !native_of (wout ,v .name ("ssm_out.weight" ),err )) 1822return false; 1823const int64_t gi = gdn_idx [(size_t )l ]; 1824float * state = ss .gdn_state + (size_t ) (gi - ss .gdn_ord0 )* gdn_floats ; 1825float * conv = state + (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 1826float * qkv = qkv_L_ + (size_t )gi * MT * C ; 1827float * hb = h_L_ + (size_t )gi * MT * C ; 1828float * gate = gate_L_ + (size_t )gi * MT * HV ; 1829float * beta = beta_L_ + (size_t )gi * MT * HV ; 1830if (sidem ) {// the gates (a few blocks, latency-bound) beside the projections, joined below 1831if (!branch (mfork_ ,cs ,side_ ,"fork" ))return false; 1832gdn_ab_multi (xm , (const uint16_t * )wa -> data , (const uint16_t * )wb -> data , (const float * )wdt -> data , 1833 (const float * )wsa -> data ,gate + (size_t )tb * HV ,beta + (size_t )tb * HV , (int )N , 1834 (int )HV ,n ,side_ ); 1835note_prio_tail (side_ ,1 ); 1836if (cudaEventRecord (mjoin_ ,side_ )!= cudaSuccess ) {err = "verify: the GDN gates' branch could not join" ;return false; } 1837 } 1838if (!q8_attn )quant_in (xm , (int )N ); 1839if (side_proj ) {// the gate projection (compute-bound for i-quants) beside qkv and the conv 1840// the branch reads F4's interleaved copy too (written on cs before the fork; bitwise native_mmvq's 1841// output), and qkv is recorded before the branch's launch, so its grid is dispatched first and the 1842// conv / recurrence that wait for it start sooner (z is read only after the recurrence) 1843const bool g_il = g_mmvq_il ()&& strata::kernels::native_mmvq_il_supported (wg -> native_type ,n , (int )ZV ); 1844if (g_il && !il_ready && n >=2 ) { 1845 strata::kernels::native_q8_1_interleave (xq_ ,xil_ , (int )N ,n ,cs ); 1846il_ready = true; 1847 } 1848if (!branch (pfork_ ,cs ,side2_ ,"fork" ))return false; 1849mm (wqkv ,qkv + (size_t )tb * C , (int )N , (int )C ); 1850if (g_il ) strata::kernels::native_mmvq_il (wg -> native_type ,wg -> native_data ,xq_ ,xil_ ,z_ + (size_t )tb * ZV , 1851 (int )N , (int )ZV ,n ,side2_ ); 1852else native_mmvq (wg -> native_type ,wg -> native_data ,xq_ ,z_ + (size_t )tb * ZV , (int )N , (int )ZV ,n ,side2_ ); 1853if (cudaEventRecord (pjoin_ ,side2_ )!= cudaSuccess ) {err = "verify: the gate projection's branch could not join" ;return false; } 1854 } 1855if (br ) {// STRATA_DF_BRANCH: a/b and z beside q/k/v and the conv; all of them read only this layer's input 1856fork (0 ); 1857gdn_ab_multi (xm , (const uint16_t * )wa -> data , (const uint16_t * )wb -> data , (const float * )wdt -> data , 1858 (const float * )wsa -> data ,gate + (size_t )tb * HV ,beta + (size_t )tb * HV , (int )N , 1859 (int )HV ,n ,df_side_ [0 ]); 1860fork (1 ); 1861native_mmvq (wg -> native_type ,wg -> native_data ,xq_ ,z_ + (size_t )tb * ZV , (int )N , (int )ZV ,n , 1862df_side_ [1 ]); 1863 } 1864const bool fuse_ab = fuse_convab_on ()&& !br && !batch_rec_ && !prof_on_ && !sidem ;// the side mixer computes the gates on its branch 1865 strata::dispatch::notef ("gdn layer: side_gates=%ld side_proj=%ld df_branch=%ld" , (long )sidem , (long )side_proj , (long )br ); 1866 strata::dispatch::notef ("gdn layer: conv+ab fused=%ld batch_rows=%ld" , (long )fuse_ab , (long )batch_rec_ ); 1867if (!side_proj )mm (wqkv ,qkv + (size_t )tb * C , (int )N , (int )C );// with side_proj: above, first 1868stamp (l ,2 ,grp ); 1869if (batch_rec_ ) {// contiguous rows may be proposals for the same slot 1870for (int t = tb ;t < te ;) { 1871const int first = t ; 1872while (t < te && brow_ [t ]== brow_ [first ])++ t ; 1873SessionState & sx = slot_ss (first ); 1874const float * cx = sx .gdn_state + (size_t ) (gi - sx .gdn_ord0 )* gdn_floats + 1875 (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 1876gdn_conv_l2_multi (cx ,qkv + (size_t )first * C , (const float * )wc -> data , 1877hb + (size_t )first * C , (int )C , (int ) (2 * HK ),EPS ,t - first ,cs ,0 , 1878keep_rows ); 1879 } 1880 }else 1881// a one-token window keeps its token: it advances the conv history and the state itself (commit) 1882if (fuse_ab )// 143-amdk: the conv and the a/b projections in one launch 1883gdn_conv_ab_multi (conv ,qkv , (const float * )wc -> data ,hb , (int )C , (int ) (2 * HK ),EPS ,n ,tb ,self_commit , 1884xm , (const uint16_t * )wa -> data , (const uint16_t * )wb -> data , (const float * )wdt -> data , 1885 (const float * )wsa -> data ,gate + (size_t )tb * HV ,beta + (size_t )tb * HV , (int )N , 1886 (int )HV ,cs ); 1887else 1888gdn_conv_l2_multi (conv ,qkv , (const float * )wc -> data ,hb , (int )C , (int ) (2 * HK ),EPS ,n ,cs ,tb , 1889self_commit ); 1890stamp (l ,3 ,grp ); 1891if (br ) {// gate, beta and z, before the recurrence reads them 1892join (0 ); 1893join (1 ); 1894 }else { 1895if (!fuse_ab && !sidem )// the gates: the HIP fused conv kernel (143-amdk) or the side mixer's branch, else here 1896gdn_ab_multi (xm , (const uint16_t * )wa -> data , (const uint16_t * )wb -> data , (const float * )wdt -> data , 1897 (const float * )wsa -> data ,gate + (size_t )tb * HV ,beta + (size_t )tb * HV , (int )N , (int )HV , 1898n ,cs ); 1899stamp (l ,4 ,grp ); 1900if (!side_proj )mm (wg ,z_ + (size_t )tb * ZV , (int )N , (int )ZV ); 1901stamp (l ,5 ,grp ); 1902if (side_proj && cudaStreamWaitEvent (cs ,pjoin_ ,0 )!= cudaSuccess ) { 1903err = "verify: the gate projection's branch could not join" ; 1904return false; 1905 } 1906if (sidem && cudaStreamWaitEvent (cs ,mjoin_ ,0 )!= cudaSuccess ) { 1907err = "verify: the GDN gates' branch could not join" ; 1908return false; 1909 } 1910 } 1911// the recurrence from the untouched state over tokens [0, te); outputs only for this group's 1912static const bool gdn_groups_on = [] {// STRATA_BATCH_GDN_GROUPS=1, all slots in one launch 1913const char * v = std::getenv ("STRATA_BATCH_GDN_GROUPS" ); 1914return v != nullptr && std::atoi (v )!= 0 ; 1915 }(); 1916if (batch_rec_ && gdn_groups_on && te - tb <=8 ) { 1917 strata::kernels::GdnGroups gg ; 1918for (int t = tb ;t < te ;) { 1919const int first = t ; 1920while (t < te && brow_ [t ]== brow_ [first ])++ t ; 1921SessionState & sx = slot_ss (first ); 1922gg .state [gg .n ]= sx .gdn_state + (size_t ) (gi - sx .gdn_ord0 )* gdn_floats ; 1923gg .first [gg .n ]= first ; 1924gg .ntok [gg .n ]= t - first ; 1925gg .keep [gg .n ]= keep_rows ?one_ :nullptr ;// STRATA_BATCH_SELF_COMMIT: the window keeps its one-row groups itself 1926++ gg .n ; 1927 } 1928 strata::kernels::gdn_step_norm_groups (gg ,hb , (int )C ,gate ,beta ,z_ , (const float * )wnm -> data ,EPS , 1929y_ , (int )HK , (int )HV ,keep_rows ,cs ); 1930 }else 1931if (batch_rec_ ) {// each slot's recurrence over its own proposed-token group 1932for (int t = tb ;t < te ;) { 1933const int first = t ; 1934while (t < te && brow_ [t ]== brow_ [first ])++ t ; 1935SessionState & sx = slot_ss (first ); 1936float * stx = sx .gdn_state + (size_t ) (gi - sx .gdn_ord0 )* gdn_floats ; 1937gdn_step_norm_multi (stx ,hb + (size_t )first * C , (int )C ,gate + (size_t )first * HV , 1938beta + (size_t )first * HV ,z_ + (size_t )first * ZV , 1939 (const float * )wnm -> data ,EPS ,y_ + (size_t )first * ZV , 1940 (int )HK , (int )HV ,t - first ,keep_rows ?one_ :nullptr ,cs ,0 ); 1941 } 1942 }else 1943gdn_step_norm_multi (state ,hb , (int )C ,gate ,beta ,z_ , (const float * )wnm -> data ,EPS ,y_ , (int )HK , 1944 (int )HV ,te ,self_commit ?one_ :nullptr ,cs ,tb ,g_qfuse () ? (void * )xq_ :nullptr ); 1945stamp (l ,6 ,grp ); 1946// STRATA_QFUSE: done above by gdn_step_norm_multi - but a batch's per-slot recurrence passes it no q8_1 1947// destination (#1139: the out-projection read stale bytes), so that case quantizes here as without it 1948if (!g_qfuse ()|| batch_rec_ )quant_in (y_ + (size_t )tb * ZV , (int )ZV ); 1949else il_ready = false; 1950mm (wout ,bo_ + tb * N , (int )ZV , (int )N ); 1951 }else { 1952// ======================= QSA ======================= 1953const int64_t qi = qsa_idx [(size_t )l ]; 1954const QsaState & st = ss .qsa_states [qi ]; 1955const WeightRef * wik = need (v ,"indexer.k_proj.weight" ,err ),* wq = need (v ,"attn_q.weight" ,err ), 1956* wk = need (v ,"attn_k.weight" ,err ),* wv = need (v ,"attn_v.weight" ,err ), 1957* wo = need (v ,"attn_output.weight" ,err ),* wiq = need (v ,"indexer.q_proj.weight" ,err ), 1958* wqn = need (v ,"attn_q_norm.weight" ,err ),* wkn = need (v ,"attn_k_norm.weight" ,err ), 1959* wiqn = need (v ,"indexer.q_norm.weight" ,err ),* wikn = need (v ,"indexer.k_norm.weight" ,err ); 1960if (!wik || !wq || !wk || !wv || !wo || !wiq || !wqn || !wkn || !wiqn || !wikn )return false; 1961if (!native_of (wq ,v .name ("attn_q.weight" ),err )|| !native_of (wk ,v .name ("attn_k.weight" ),err )|| 1962 !native_of (wv ,v .name ("attn_v.weight" ),err )|| !native_of (wo ,v .name ("attn_output.weight" ),err )) 1963return false; 1964auto norm_rope_on = [& ](float * data ,const WeightRef * norm ,int rows ,int cols ,const int32_t * pos , 1965cudaStream_t sx ) { 1966if (native_qsa_enabled ())native_qsa_rms_norm_weighted (data , (const float * )norm -> data ,data ,cols ,rows ,EPS ,sx ); 1967else rms_norm_weighted (data , (const float * )norm -> data ,rows ,cols ,EPS ,sx ); 1968if (native_rope_enabled ())native_rope_apply (data ,data ,rows ,cols , (int )s .n_rot ,rope_scaling (),pos ,sx ); 1969else rope_neox_apply (data ,data ,rows ,cols , (int )s .n_rot ,st .cos_tab ,st .sin_tab ,pos ,sx ); 1970 }; 1971// #783 PR-f (stuchapin909): the per-head RMSNorm and the rope in one launch, bit-identical to the pair 1972// (rope_parity check 6); STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes 1973const bool fuse_nr = native_qsa_enabled ()&& native_rope_enabled ()&& native_norm_rope_usable ((int )HD , (int )s .n_rot ); 1974auto norm_rope = [& ](float * data ,const WeightRef * norm ,int rows ,int cols ,const int32_t * pos ) { 1975if (fuse_nr && native_norm_rope_usable (cols , (int )s .n_rot )) { 1976native_qsa_rms_norm_rope (data ,cols , (const float * )norm -> data ,data ,rows ,cols , (int )s .n_rot ,EPS , 1977rope_scaling (),pos ,cs ); 1978return ; 1979 } 1980norm_rope_on (data ,norm ,rows ,cols ,pos ,cs ); 1981 }; 1982float * idx_raw = idx_raw_L_ + (size_t )qi * MT * ID ; 1983// the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the 1984// window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token) 1985// STRATA_DF_QB_Q4 (default on since 0.1.45; STRATA_DF_QB_Q4=0 gives the old token-by-token path): a Q4_0 KV cache 1986// takes the batched window too - its one per-token extra, the query's rotation, is row-wise and the batched 1987// path rotates (270650e). The generated ids are identical (p620 gfx1201, A4000 sm_86, P100 sm_60, short and 1988// long prompts), and the 6-token verify graph is 1950 nodes instead of 2610 (#2403: an RX 6900 XT faulted in 1989// the first verify graph launch with --kv q4_0 + KV streaming + MTP; whether the graph size is the cause is 1990// not confirmed) 1991static const bool qb_q4 = [] { 1992const char * e = std::getenv ("STRATA_DF_QB_Q4" ); 1993return e == nullptr || std::atoi (e )!= 0 ; 1994 }(); 1995const bool qb = dec_batch && n > 1 && native_qsa_enabled ()&& native_rope_enabled ()&& (!st .kv_q4 || qb_q4 ); 1996if (!q8_attn )quant_in (xm , (int )N ); 1997// STRATA_DF_BRANCH: the query side (q and its norm/RoPE/rotation on side 0, the indexer query on side 1) 1998// beside the K/V side; the indexer query joins before the block scores, the query before attention 1999const bool qbr = br && qb ; 2000if (qbr ) { 2001fork (0 ); 2002native_mmvq (wq -> native_type ,wq -> native_data ,xq_ ,qfull_ + tb * NH * 2 * HD , (int )N , 2003 (int ) (NH * 2 * HD ),n ,df_side_ [0 ]); 2004copy_rows_strided (qcur_ + tb * NH * HD ,qfull_ + tb * NH * 2 * HD , (int64_t )n * NH ,HD ,2 * HD , 2005df_side_ [0 ]); 2006norm_rope_on (qcur_ + tb * NH * HD ,wqn , (int ) (n * NH ), (int )HD ,pos_ + tb * NH ,df_side_ [0 ]); 2007if (st .kv_rot )fwht256_inplace_cuda (qcur_ + tb * NH * HD , (int64_t )n * NH ,df_side_ [0 ]);// <Hq, Hk> = <q, k> 2008fork (1 ); 2009bf16_gemv_fp32_mmvf_multi (mixed_ + tb * N ,N , (const uint16_t * )wiq -> data ,qidx_ + tb * IQ * ID , 2010IQ * ID ,N ,IQ * ID ,n ,df_side_ [1 ]); 2011norm_rope_on (qidx_ + tb * IQ * ID ,wiqn , (int ) (n * IQ ), (int )ID ,pos_i + tb * IQ ,df_side_ [1 ]); 2012 } 2013// STRATA_SIDE_MIXER=1 / =2 (fork Eddoursul 34a35db + b063c13): the indexer's key projection, 2014// the tail's snapshot, its keys appended, its query projection, norm and RoPE, the block scores and the 2015// top-k read only the mixer's input and the indexer's own state - =1 runs them on a branch beside the 2016// attention's projections; =2 also the queries' chain on a second branch. Each step below is 2017// the in-line code with its stream as a parameter; with the switch off they run on cs in the same order 2018// as before (STRATA_DF_BRANCH, the same idea for fewer of these steps, is off whenever this is on). 2019auto norm_rope_s = [& ](float * data ,const WeightRef * norm ,int rows ,int cols ,const int32_t * pos ,cudaStream_t ns ) { 2020if (fuse_nr && native_norm_rope_usable (cols , (int )s .n_rot )) { 2021native_qsa_rms_norm_rope (data ,cols , (const float * )norm -> data ,data ,rows ,cols , (int )s .n_rot ,EPS , 2022rope_scaling (),pos ,ns ); 2023return ; 2024 } 2025norm_rope_on (data ,norm ,rows ,cols ,pos ,ns ); 2026 }; 2027auto idx_key = [& ](cudaStream_t ns ) { 2028if (qb )bf16_gemv_fp32_mmvf_multi (mixed_ + tb * N ,N , (const uint16_t * )wik -> data ,idx_raw + tb * ID ,ID ,N ,ID ,n ,ns ); 2029else for (int t = tb ;t < te ;++ t ) 2030bf16_gemv_fp32_mmvf (mixed_ + t * N , (const uint16_t * )wik -> data ,idx_raw + t * ID , (int )N , (int )ID ,ns ); 2031 }; 2032auto idx_snap = [& ](cudaStream_t ns ) { 2033if (batch_rec_ ) {// snapshot each slot's indexer tail before its first proposed row 2034for (int t = tb ;t < te && !keep_rows ;++ t ) 2035if (t == tb || brow_ [t ]!= brow_ [t - 1 ]) 2036copy_from_mapped (tail_snap_b_ + ((size_t )brow_ [t ]* nQall + qi )* TS , 2037slot_ss (t ).qsa_states [qi ].idx_tail ,TS ,ns ); 2038 }else 2039if (grp == 0 )copy_from_mapped (tail_snap_ + (size_t )qi * TS ,st .idx_tail ,TS ,ns ); 2040 }; 2041auto idx_append = [& ](cudaStream_t ns ) { 2042if (dec_batch && !g_no_batch_kv && !batch_rec_ ) { 2043const QsaIndexerBuffers ib {st .idx_tail ,st .idx_dead ,st .idx_pooled ,st .idx_block_pos }; 2044native_qsa_indexer_append_steps (idx_raw + tb * ID ,step_ + tb * kStepCount + kStepPos ,kStepCount , 2045n ,0 , (const float * )wikn -> data ,EPS ,ib ,s ,st .max_cells , 2046rope_scaling (),ns ); 2047 }else { 2048for (int t = tb ;t < te ;++ t ) { 2049const QsaState & sx = slot_ss (t ).qsa_states [qi ]; 2050const QsaIndexerBuffers ib {sx .idx_tail ,sx .idx_dead ,sx .idx_pooled ,sx .idx_block_pos }; 2051native_qsa_indexer_append (idx_raw + t * ID ,step_ + t * kStepCount + kStepPos ,0 , 2052 (const float * )wikn -> data ,EPS ,ib ,s ,sx .max_cells , 2053rope_scaling (),ns ); 2054 } 2055 } 2056 }; 2057auto idx_query = [& ](cudaStream_t ns ) { 2058if (qb ) { 2059bf16_gemv_fp32_mmvf_multi (mixed_ + tb * N ,N , (const uint16_t * )wiq -> data ,qidx_ + tb * IQ * ID ,IQ * ID , 2060N ,IQ * ID ,n ,ns ); 2061norm_rope_s (qidx_ + tb * IQ * ID ,wiqn , (int ) (n * IQ ), (int )ID ,pos_i + tb * IQ ,ns ); 2062 }else 2063for (int t = tb ;t < te ;++ t ) { 2064float * qx = qidx_ + t * IQ * ID ; 2065bf16_gemv_fp32_mmvf (mixed_ + t * N , (const uint16_t * )wiq -> data ,qx , (int )N , (int ) (IQ * ID ),ns ); 2066norm_rope_s (qx ,wiqn , (int )IQ , (int )ID ,pos_ + t * NH ,ns ); 2067 } 2068 }; 2069auto idx_select = [& ](cudaStream_t ns ) { 2070if (sel_long_ ) {// STRATA_SELECT_LONG: the long-context window graphs (the same ids) 2071qsa_block_scores_long (st .idx_pooled ,st .idx_dead ,qidx_ + tb * IQ * ID ,step_ + tb * kStepCount ,n , 2072max_blocks_ ,s ,scores_ + (size_t )tb * max_blocks_ ,ns ,-1 ); 2073qsa_block_topk_long (scores_ + (size_t )tb * max_blocks_ ,step_ + tb * kStepCount ,n ,max_blocks_ , 2074cap_ ,s ,sel_ + (size_t )tb * cap_ ,ns ,-1 ,topk_scratch_ ); 2075return ; 2076 } 2077qsa_block_scores (st .idx_pooled ,st .idx_dead ,qidx_ + tb * IQ * ID ,step_ + tb * kStepCount ,n ,max_blocks_ , 2078s ,scores_ + (size_t )tb * max_blocks_ ,ns ); 2079qsa_block_topk (scores_ + (size_t )tb * max_blocks_ ,step_ + tb * kStepCount ,n ,max_blocks_ ,cap_ ,s , 2080sel_ + (size_t )tb * cap_ ,ns ); 2081 }; 2082// the attention's queries: the projection (mm on cs, which may read F4's interleaved copy; on a branch 2083// F4's kernel too, its copy written on cs before the fork - bitwise the same), the q/gate 2084// split with norm and RoPE, the rotation 2085const bool q_il = side_proj && g_mmvq_il ()&& 2086 strata::kernels::native_mmvq_il_supported (wq -> native_type ,n , (int ) (NH * 2 * HD )); 2087auto q_chain = [& ](cudaStream_t ns )-> bool { 2088if (ns == cs )mm (wq ,qfull_ + tb * NH * 2 * HD , (int )N , (int ) (NH * 2 * HD )); 2089else if (q_il ) strata::kernels::native_mmvq_il (wq -> native_type ,wq -> native_data ,xq_ ,xil_ , 2090qfull_ + tb * NH * 2 * HD , (int )N , (int ) (NH * 2 * HD ),n ,ns ); 2091else native_mmvq (wq -> native_type ,wq -> native_data ,xq_ ,qfull_ + tb * NH * 2 * HD , (int )N , 2092 (int ) (NH * 2 * HD ),n ,ns ); 2093if (qb ) { 2094if (fuse_nr ) {// the q/gate split reads q straight out of the q|gate rows (stride 2 * HD) 2095native_qsa_rms_norm_rope (qfull_ + tb * NH * 2 * HD , (int ) (2 * HD ), (const float * )wqn -> data , 2096qcur_ + tb * NH * HD , (int ) (n * NH ), (int )HD , (int )s .n_rot ,EPS , 2097rope_scaling (),pos_ + tb * NH ,ns ); 2098 }else { 2099copy_rows_strided (qcur_ + tb * NH * HD ,qfull_ + tb * NH * 2 * HD , (int64_t )n * NH ,HD ,2 * HD ,ns ); 2100norm_rope_s (qcur_ + tb * NH * HD ,wqn , (int ) (n * NH ), (int )HD ,pos_ + tb * NH ,ns ); 2101 } 2102if (st .kv_rot )fwht256_inplace_cuda (qcur_ + tb * NH * HD , (int64_t )n * NH ,ns );// <Hq, Hk> = <q, k> 2103 }else { 2104for (int t = tb ;t < te ;++ t ) { 2105float * qc = qcur_ + t * NH * HD ; 2106if (fuse_nr ) { 2107native_qsa_rms_norm_rope (qfull_ + t * NH * 2 * HD , (int ) (2 * HD ), (const float * )wqn -> data ,qc , 2108 (int )NH , (int )HD , (int )s .n_rot ,EPS ,rope_scaling (),pos_ + t * NH ,ns ); 2109 }else { 2110if (cudaMemcpy2DAsync (qc , (size_t )HD * 4 ,qfull_ + t * NH * 2 * HD , (size_t )HD * 2 * 4 , 2111 (size_t )HD * 4 , (size_t )NH ,cudaMemcpyDeviceToDevice ,ns )!= cudaSuccess ) { 2112err = "verify: the q/gate split failed" ; 2113return false; 2114 } 2115norm_rope_s (qc ,wqn , (int )NH , (int )HD ,pos_ + t * NH ,ns ); 2116 } 2117if (st .kv_rot )fwht256_inplace_cuda (qc ,NH ,ns );// <Hq, Hk> = <q, k> 2118 } 2119 } 2120return true; 2121 }; 2122if (sidem ) { 2123if (!branch (mfork_ ,cs ,side_ ,"fork" ))return false; 2124idx_key (side_ ); 2125idx_snap (side_ ); 2126idx_append (side_ ); 2127idx_query (side_ ); 2128idx_select (side_ ); 2129note_prio_tail (side_ ,1 ); 2130if (cudaEventRecord (mjoin_ ,side_ )!= cudaSuccess ) {err = "verify: the indexer's branch could not join" ;return false; } 2131 } 2132if (side_proj ) {// the queries beside the keys and values (fork b063c13) 2133if (q_il && !il_ready && n >=2 ) {// the copy before the fork (mm(wk) / mm(wv) on cs reuse it) 2134 strata::kernels::native_q8_1_interleave (xq_ ,xil_ , (int )N ,n ,cs ); 2135il_ready = true; 2136 } 2137if (!branch (pfork_ ,cs ,side2_ ,"fork" )|| !q_chain (side2_ ))return false; 2138if (cudaEventRecord (pjoin_ ,side2_ )!= cudaSuccess ) {err = "verify: the queries' branch could not join" ;return false; } 2139 } 2140if (!sidem )idx_key (cs ); 2141stamp (l ,7 ,grp ); 2142mm (wk ,kcur_ + tb * NKV * HD , (int )N , (int ) (NKV * HD )); 2143mm (wv ,vcur_ + tb * NKV * HD , (int )N , (int ) (NKV * HD )); 2144if (qb )norm_rope (kcur_ + tb * NKV * HD ,wkn , (int ) (n * NKV ), (int )HD ,pos_k + tb * NKV ); 2145else for (int t = tb ;t < te ;++ t )norm_rope (kcur_ + t * NKV * HD ,wkn , (int )NKV , (int )HD ,pos_ + t * NH ); 2146if (st .kv_rot ) {// K and V rotated before they are stored (kv_q4.hpp) 2147fwht256_inplace_cuda (kcur_ + tb * NKV * HD , (int64_t )n * NKV ,cs ); 2148fwht256_inplace_cuda (vcur_ + tb * NKV * HD , (int64_t )n * NKV ,cs ); 2149 }else if (st .kv_hybrid ) {// K8V4: only V is rotated 2150fwht256_inplace_cuda (vcur_ + tb * NKV * HD , (int64_t )n * NKV ,cs ); 2151 } 2152stamp (l ,8 ,grp ); 2153if (!sidem )idx_snap (cs ); 2154// #783 PR-d (stuchapin909): the window's K/V cells in one launch per pool instead of one per token (a 2155// batch's rows each have their own K/V, so that case keeps the loop) 2156if (dec_batch && !g_no_batch_kv && !batch_rec_ ) { 2157const int32_t * step_b = step_ + tb * kStepCount ; 2158const float * kc_b = kcur_ + tb * NKV * HD ; 2159const float * vc_b = vcur_ + tb * NKV * HD ; 2160if (st .kv_hybrid ) {// K8V4: the unused half's lanes folded onto the used pool (layer.cpp) 2161// #1188: a streamed state's host copy gets the window's cells too, as the per-token path below 2162// writes them - without it a block that was not resident when its cells were appended came 2163// back from the host copy without them, and free generation degenerated into repetition 2164const KvHostPools hk = kv_hybrid_k_half (st .host ),hv = kv_hybrid_v_half (st .host ); 2165const bool mirror = st .host .present (); 2166kv_append_q8_steps (st .k_q ,st .k_q ,st .k_scale ,st .k_scale ,st .page_table ,step_b ,kStepCount , 2167kc_b ,kc_b , (int ) (NKV * HD ),n ,s ,cs ,mirror ?& hk :nullptr ); 2168kv_append_q4_steps (st .v_q4 ,st .v_q4 ,st .page_table ,step_b ,kStepCount ,n ,vc_b ,vc_b ,s ,cs , 2169mirror ?& hv :nullptr ); 2170 }else if (st .kv_q4 ) 2171kv_append_q4_steps (st .k_q4 ,st .v_q4 ,st .page_table ,step_b ,kStepCount ,n ,kc_b ,vc_b ,s ,cs , 2172& st .host ); 2173else if (st .kv_int8 ) 2174kv_append_q8_steps (st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,st .page_table ,step_b ,kStepCount , 2175kc_b ,vc_b , (int ) (NKV * HD ),n ,s ,cs ,& st .host ); 2176else 2177for (int t = tb ;t < te ;++ t ) 2178kv_append_step (st .k_pool ,st .v_pool ,st .page_table ,step_ + t * kStepCount , 2179kcur_ + t * NKV * HD ,vcur_ + t * NKV * HD ,s ,cs ,& st .host ); 2180 }else 2181for (int t = tb ;t < te ;++ t ) { 2182const QsaState & st = slot_ss (t ).qsa_states [qi ];// the row's own K/V (ss's outside a batch) 2183const int32_t * step_t = step_ + t * kStepCount ; 2184if (st .kv_hybrid ) {// K8V4: the unused half's lanes folded onto the used pool (layer.cpp) 2185const KvHostPools hk = kv_hybrid_k_half (st .host ),hv = kv_hybrid_v_half (st .host ); 2186const bool mirror = st .host .present ();// streamed: the host copy too 2187kv_append_q8_step (st .k_q ,st .k_q ,st .k_scale ,st .k_scale ,st .page_table ,step_t , 2188kcur_ + t * NKV * HD ,kcur_ + t * NKV * HD ,s ,cs ,mirror ?& hk :nullptr ); 2189kv_append_q4_step (st .v_q4 ,st .v_q4 ,st .page_table ,step_t ,vcur_ + t * NKV * HD , 2190vcur_ + t * NKV * HD ,s ,cs ,mirror ?& hv :nullptr ); 2191 }else if (st .kv_q4 ) 2192kv_append_q4_step (st .k_q4 ,st .v_q4 ,st .page_table ,step_t ,kcur_ + t * NKV * HD , 2193vcur_ + t * NKV * HD ,s ,cs ,& st .host ); 2194else if (st .kv_int8 ) 2195kv_append_q8_step (st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,st .page_table ,step_t , 2196kcur_ + t * NKV * HD ,vcur_ + t * NKV * HD ,s ,cs ,& st .host ); 2197else 2198kv_append_step (st .k_pool ,st .v_pool ,st .page_table ,step_t ,kcur_ + t * NKV * HD , 2199vcur_ + t * NKV * HD ,s ,cs ,& st .host ); 2200 } 2201if (!sidem )idx_append (cs ); 2202stamp (l ,9 ,grp ); 2203if (qbr ) { 2204join (1 );// the indexer query, for the block scores 2205 }else { 2206if (!side_proj && !q_chain (cs ))return false; 2207if (!sidem )idx_query (cs ); 2208 } 2209stamp (l ,10 ,grp ); 2210bool streamed = false;// a streamed KV cache keeps the per-row resolve-then-attend order 2211if (batch_rec_ && g_qsa_slots ) 2212for (int t = tb ;t < te ;++ t )streamed = streamed || slot_ss (t ).qsa_states [qi ].kv_mode == 1 ; 2213// STRATA_BATCH_ATTN_ROWS=1: the window's rows in ONE launch per step - scores with each row's 2214// own indexer keys, the top-k over all rows (row-independent), attention with each row's own pools - 2215// instead of 3-4 one-row launches per row; the same per-row arithmetic. Not with KV streaming 2216// (qsa_kv_resolve has work per slot then). 2217static const bool attn_rows = [] { 2218const char * v = std::getenv ("STRATA_BATCH_ATTN_ROWS" ); 2219return v != nullptr && std::atoi (v )!= 0 ; 2220 }(); 2221bool rows_ok = batch_rec_ && attn_rows && te - tb <= strata::kernels::kAttnRowsMax ; 2222for (int t = tb ;rows_ok && t < te ;++ t )rows_ok = slot_ss (t ).qsa_states [qi ].kv_mode != 1 ; 2223if (rows_ok ) { 2224const int n_rows = te - tb ; 2225 strata::kernels::QsaScoreRows sr ; 2226 strata::kernels::QsaAttnPoolsRows pr ; 2227sr .n = pr .n = n_rows ; 2228for (int t = tb ;t < te ;++ t ) { 2229const QsaState & sx = slot_ss (t ).qsa_states [qi ]; 2230sr .pooled [t - tb ]= sx .idx_pooled ; 2231sr .dead [t - tb ]= sx .idx_dead ; 2232pr .p [t - tb ]= qsa_attn_pools (sx ); 2233 } 2234qsa_block_scores_rows (sr ,qidx_ + tb * IQ * ID ,step_ + tb * kStepCount ,n_rows ,max_blocks_ ,s , 2235scores_ + (size_t )tb * max_blocks_ ,cs ); 2236qsa_block_topk (scores_ + (size_t )tb * max_blocks_ ,step_ + tb * kStepCount ,n_rows ,max_blocks_ ,cap_ , 2237s ,sel_ + (size_t )tb * cap_ ,cs ); 2238qsa_decode_attn_batch_rows (qcur_ + tb * NH * HD ,pr ,sel_ + (size_t )tb * cap_ ,step_ + tb * kStepCount , 2239cap_ ,s ,attn_scratch_ + (size_t )tb * attn_scratch_floats_ , 2240attn_ + tb * NH * HD ,n_rows ,cs ); 2241 }else 2242if (batch_rec_ && g_qsa_slots && !streamed ) { 2243// the rows' block scores, top-k and attention, up to 8 rows per launch. The rows only read 2244// their slots' keys and K/V here and write their own scores/sel/scratch/attn rows, so running 2245// each step for all rows before the next is the per-row loop's result 2246for (int t0 = tb ;t0 < te ;t0 += kQsaAttnMaxSlots ) { 2247const int m = std::min (te - t0 ,kQsaAttnMaxSlots ); 2248const float * pooled [kQsaAttnMaxSlots ]; 2249const float * dead [kQsaAttnMaxSlots ]; 2250QsaAttnSlotPools px ; 2251for (int i = 0 ;i < m ;++ i ) { 2252const QsaState & sx = slot_ss (t0 + i ).qsa_states [qi ]; 2253pooled [i ]= sx .idx_pooled ; 2254dead [i ]= sx .idx_dead ; 2255px .p [i ]= qsa_attn_pools (sx ); 2256 } 2257// a launcher that would not run the per-row call's kernel launches nothing: per-row calls 2258if (!qsa_block_scores_slots (pooled ,dead ,qidx_ + t0 * IQ * ID ,step_ + t0 * kStepCount ,m , 2259max_blocks_ ,s ,scores_ + (size_t )t0 * max_blocks_ ,cs )) 2260for (int t = t0 ;t < t0 + m ;++ t ) 2261qsa_block_scores (pooled [t - t0 ],dead [t - t0 ],qidx_ + t * IQ * ID ,step_ + t * kStepCount , 22621 ,max_blocks_ ,s ,scores_ + (size_t )t * max_blocks_ ,cs ); 2263qsa_block_topk (scores_ + (size_t )t0 * max_blocks_ ,step_ + t0 * kStepCount ,m ,max_blocks_ , 2264cap_ ,s ,sel_ + (size_t )t0 * cap_ ,cs ); 2265if (!qsa_decode_attn_slots (qcur_ + t0 * NH * HD ,px ,sel_ + (size_t )t0 * cap_ , 2266step_ + t0 * kStepCount ,cap_ ,s , 2267attn_scratch_ + (size_t )t0 * attn_scratch_floats_ , 2268attn_ + t0 * NH * HD ,m ,cs )) 2269for (int t = t0 ;t < t0 + m ;++ t ) 2270qsa_decode_attn_batch (qcur_ + t * NH * HD ,px .p [t - t0 ],sel_ + (size_t )t * cap_ , 2271step_ + t * kStepCount ,cap_ ,s , 2272attn_scratch_ + (size_t )t * attn_scratch_floats_ , 2273attn_ + t * NH * HD ,1 ,cs ); 2274 } 2275 }else if (batch_rec_ ) {// each row selects and attends over its own slot's K/V 2276for (int t = tb ;t < te ;++ t ) { 2277const QsaState & sx = slot_ss (t ).qsa_states [qi ]; 2278qsa_block_scores (sx .idx_pooled ,sx .idx_dead ,qidx_ + t * IQ * ID ,step_ + t * kStepCount ,1 , 2279max_blocks_ ,s ,scores_ + (size_t )t * max_blocks_ ,cs ); 2280qsa_block_topk (scores_ + (size_t )t * max_blocks_ ,step_ + t * kStepCount ,1 ,max_blocks_ ,cap_ ,s , 2281sel_ + (size_t )t * cap_ ,cs ); 2282qsa_kv_resolve (sx ,* g_ ,sel_ + (size_t )t * cap_ ,step_ + t * kStepCount ,1 ,cap_ ,cs ); 2283const QsaAttnPools px = qsa_attn_pools (sx ); 2284qsa_decode_attn_batch (qcur_ + t * NH * HD ,px ,sel_ + (size_t )t * cap_ ,step_ + t * kStepCount , 2285cap_ ,s ,attn_scratch_ + (size_t )t * attn_scratch_floats_ , 2286attn_ + t * NH * HD ,1 ,cs ); 2287 } 2288 }else { 2289if (!sidem )idx_select (cs ); 2290else if (cudaStreamWaitEvent (cs ,mjoin_ ,0 )!= cudaSuccess ) { 2291err = "verify: the indexer's branch could not join" ; 2292return false; 2293 } 2294if (side_proj && cudaStreamWaitEvent (cs ,pjoin_ ,0 )!= cudaSuccess ) { 2295err = "verify: the queries' branch could not join" ; 2296return false; 2297 } 2298stamp (l ,11 ,grp ); 2299// KV streaming: the n selections' blocks resident (device-side, inside the graph) 2300qsa_kv_resolve (st ,* g_ ,sel_ + (size_t )tb * cap_ ,step_ + tb * kStepCount ,n ,cap_ ,cs ); 2301stamp (l ,12 ,grp ); 2302if (qbr )join (0 );// the query, for attention 2303const QsaAttnPools pools = qsa_attn_pools (st ); 2304// STRATA_QSA_SPLIT_ATTN=1: the split tensor-core attention where it applies (int8 KV, sm_80+) 2305static const bool split_attn = [] {const char * v = std::getenv ("STRATA_QSA_SPLIT_ATTN" );return v != nullptr && std::atoi (v )!= 0 ; }(); 2306if (!(split_attn && qsa_decode_attn_split (qcur_ + tb * NH * HD ,pools ,sel_ + (size_t )tb * cap_ , 2307step_ + tb * kStepCount ,cap_ ,s , 2308attn_scratch_ + (size_t )tb * attn_scratch_floats_ , 2309 (uint64_t )n * (uint64_t )attn_scratch_floats_ ,attn_ + tb * NH * HD ,n ,cs ))) 2310 { 2311 strata::dispatch::notef ("qsa layer: decode attention batch kernels (split tensor-core attention off or declined) kv_rot=%ld" , (long )st .kv_rot ); 2312qsa_decode_attn_batch (qcur_ + tb * NH * HD ,pools ,sel_ + (size_t )tb * cap_ ,step_ + tb * kStepCount ,cap_ , 2313s ,attn_scratch_ + (size_t )tb * attn_scratch_floats_ ,attn_ + tb * NH * HD ,n ,cs ); 2314 } 2315 } 2316stamp (l ,13 ,grp ); 2317if (st .kv_rot || st .kv_hybrid )fwht256_inplace_cuda (attn_ + tb * NH * HD , (int64_t )n * NH ,cs );// back: H^-1 = H 2318if (qb )native_qsa_gate_apply (attn_ + tb * NH * HD ,qfull_ + tb * NH * 2 * HD ,attn32_ + tb * NH * HD , 2319 (int ) (n * NH ), (int )HD ,cs ); 2320else 2321for (int t = tb ;t < te ;++ t ) { 2322if (native_qsa_enabled ()) 2323native_qsa_gate_apply (attn_ + t * NH * HD ,qfull_ + t * NH * 2 * HD ,attn32_ + t * NH * HD , 2324 (int )NH , (int )HD ,cs ); 2325else 2326qsa_gate_apply_f32 (attn_ + t * NH * HD ,qfull_ + t * NH * 2 * HD ,s ,attn32_ + t * NH * HD ,cs ); 2327 } 2328stamp (l ,14 ,grp ); 2329quant_in (attn32_ + tb * NH * HD , (int ) (NH * HD )); 2330mm (wo ,bo_ + tb * N , (int ) (NH * HD ), (int )N ); 2331 } 2332 }catch (const std::exception & e ) { 2333err = "verify layer " + std::to_string (l )+ ": " + e .what (); 2334return false; 2335 } 2336stamp (l ,16 ,grp ); 2337const bool q8_ffn = gr_read_group (1 , true,inj_ ,inj2_ );// true: nat_xq_ holds the MoE input's q8_1 (STRATA_QFUSE) 2338if (latent_ && grp == 0 && h_latxlq_ != nullptr ) {// edge0 CPU share: the D stage RIGHT HERE - mixed_ is 2339// just normed, the router/plan/doorbell still run after it, and the host's pool call (which starts at 2340// the ring this pre publishes) waits on the xl doorbell: the D stage now has the whole router+plan+bell 2341// stretch (~0.6 ms) of head start instead of starting when the pool is already waiting. 2342quantize_q8_1_rows (mixed_ ,T , (int )N ,lat_xq_ ,cs ); 2343iq_mmvq (strata::kernels::lat_dense_fmt_to_type (lat_fmt_ ), 2344lat_d_ + (size_t ) (l - lat_first_layer_ )* lat_dense_ .d_bytes (),lat_xq_ ,lat_xl_ , (int )N , 2345 (int ) (lat_G_ * lat_ELL_ ),T ,cs );// Q4DU: fmt->ggml type (8 Q8_0 / 2 Q4_0) 2346// Q3_K shared column scales: the pack's A rows are A*diag(s), so scale x by 1/s HERE - once, before 2347// every consumer below (the GPU experts' q8_1, the act0 q8_0, the CPU pool's f32 doorbell) reads 2348// lat_xl_. Packs without scales skip the launch entirely. 2349if (const float * inv = strata::kernels::lat_gu_colscale_dev ((int )l , (int )lat_ELL_ )) 2350 strata::kernels::lat_colscale_rows (lat_xl_ , (int64_t )T * (int64_t )lat_G_ , (int )lat_ELL_ ,inv ,cs ); 2351quantize_q8_1_rows (lat_xl_ ,T * lat_G_ , (int )lat_ELL_ ,lat_xlq_ ,cs ); 2352// DESIGN-4 + the write-path cut: quantize into a DEVICE buffer, then the copy engine 2353// lands it in mapped host memory (async, off the compute stream's serial chain - the 2354// same path the f32 rows take). Bit-exact to the host's from_float (probe_std); the 2355// xlseq doorbell after both copies covers it. 2356quantize_q8_0_rows (lat_xl_ , (long long )T * lat_G_ , (long long )lat_ELL_ ,lat_act0_dev_ ,cs ); 2357cudaMemcpyAsync (m_latact0_ ,lat_act0_dev_ , 2358 (size_t )T * (size_t )lat_G_ * ((size_t )lat_ELL_ /32 )* 34 , 2359cudaMemcpyDeviceToHost ,cs ); 2360cudaMemcpyAsync (m_latxlq_ ,lat_xl_ , (size_t )T * (size_t )lat_G_ * (size_t )lat_ELL_ * 4 , 2361cudaMemcpyDeviceToHost ,cs ); 2362if (trace_m_ != nullptr )gpu_stamp (trace_m_ , (l * kProfPer + 35 )* 2 ,cs );// K0-probe: D2H done 2363doorbell_publish_value (nullptr ,nullptr ,nullptr ,0 ,0 ,nullptr ,nullptr ,nullptr , 2364 (uint32_t * )m_xlseq_ , (uint32_t )l + 1 ,cs ); 2365 } 2366stamp (l ,32 ,grp );// the profile only: the FFN-side read ends here, the router starts 2367// with CPU experts in the window the shared expert forks off once the doorbell is published (it no longer 2368// competes with it for the GPU's first microseconds); STRATA_SH_FORK_LATE=0 forks at the top as before 2369static const bool sh_fork_late_env = [] { 2370const char * e = std::getenv ("STRATA_SH_FORK_LATE" ); 2371return !e || e [0 ]!= '0' ; 2372 }(); 2373const bool sh_fork = sh_stream_on ()&& !prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr ; 2374const bool sh_fork_late = sh_fork && sh_fork_late_env && !ar_on (); 2375cudaStream_t sh_stream = sh_fork ?sh_cs_ :cs ; 2376if (sh_fork && !sh_fork_late ) { 2377note_prio_fork (cs ); 2378cudaEventRecord (ev_fork_ ,cs ); 2379cudaStreamWaitEvent (sh_cs_ ,ev_fork_ ,0 ); 2380 } 2381// the window's rows routed in 2 launches (one router GEMV reading the weight once, one 2382// top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old) 2383const WeightRef * w_router = v .get ("ffn_gate_inp.weight" ); 2384// S26 STRATA_LFUSE=1: the shared expert's gate row rides in the router GEMV launch, its sigmoid + row scale 2385// move into the combine, gate + up share one launch (all bitwise; resident combine path, 2-8 rows only) 2386const WeightRef * w_sgi = lfuse_on (n )&& g_lfuse_gate () ?v .get ("ffn_gate_inp_shexp.weight" ) :nullptr ; 2387bool sg_ready = false; 2388if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled ()&& NE == 512 && K == 10 ) { 2389try { 2390if (w_sgi != nullptr ) 2391sg_ready = bf16_gemv_fp32_mmvf_multi_aux (mixed_ + tb * N ,N , (const uint16_t * )w_router -> data , 2392logits_ + tb * NE ,NE ,N ,NE ,n , 2393 (const uint16_t * )w_sgi -> data ,sh_g_ + tb ,1 ,cs ); 2394if (!sg_ready ) 2395bf16_gemv_fp32_mmvf_multi (mixed_ + tb * N ,N , (const uint16_t * )w_router -> data ,logits_ + tb * NE ,NE ,N , 2396NE ,n ,cs ); 2397native_router_top10_multi (logits_ + tb * NE ,ids_ + tb * K ,w_ + tb * K ,n ,cs ); 2398 }catch (const std::exception & e ) {err = "verify router: " + std::string (e .what ());return false; } 2399#if defined(STRATA_HIP_GFX906 ) 2400} else if ( dec_batch ) { 2401// gfx906: the Coder's 256-expert router (the native router is 512 x 10 only) for the whole window in one 2402// multi-column BF16 projection and one top-k, bitwise the per-token calls (route_window_parity); ~3 ms 2403// of a ~55 ms verify window on 2x MI50. STRATA_ROUTE_PER_TOKEN=1: the per-token calls. 2404if (! moe_route_window ( wt , g , l , K , ss . moe , mixed_ + tb * N , logits_ + tb * NE , ids_ + tb * K , w_ + tb * K , n , 2405cs , err )) 2406return false; 2407#endif 2408} else 2409for ( int t = tb ; t < te ; ++ t ) { 2410MoEBuffers mb = ss . moe ; 2411mb . logits = logits_ + t * NE ; mb . ids = ids_ + t * K ; mb . weights = w_ + t * K ; 2412if (! moe_route ( wt , g , l , K , mb , mixed_ + t * N , cs , err , nullptr )) return false; 2413} 2414strata::dispatch:: notef ( "router layer: batched native router=%ld, shared-expert gate in the router launch=%ld, route_prior=%ld" , ( long ) ( dec_batch && n > 1 && w_router != nullptr && native_router_enabled () && NE == 512 && K == 10 ), ( long ) sg_ready , ( long ) ( g_route_prior () > 0.0f )); 2415// STRATA_ROUTE_PRIOR=lambda (changes the output): the top-10 picked again with a logit bonus for the resident 2416// experts; the weights stay the router's (route_prior.cu). g_route_prior() above: off unless STRATA_ROUTE_PRIOR is set 2417// (measured on an RTX 3060 12 GB at 2.0: story +37.6%, code +35.2%; on an RTX PRO 5000 72 GB -1.9% / -0.5%, on 2x RTX A4000 2418// -4.2% / +11.0%, so it only helps a card that streams most experts). 2419const float route_prior = g_route_prior (); 2420if ( route_prior > 0.0f && NE == 512 && K == 10 && hits_ . d_res != nullptr ) 2421route_prior_top10 ( logits_ + tb * NE , hits_ . d_res + l * g . n_expert , route_prior , ids_ + tb * K , w_ + tb * K , n , cs ); 2422if ( route_resident_cfg (). margin > 0.0f && NE == 512 && K == 10 && hits_ . d_res != nullptr ) { 2423// STRATA_ROUTE_RESIDENT: after the router, before the plan/doorbell read ids_/w_ (opt-in, changes the output) 2424try { 2425native_route_resident ( logits_ + tb * NE , ids_ + tb * K , w_ + tb * K , hits_ . d_res + l * g . n_expert , n , 2426route_resident_cfg (). margin , route_resident_cfg (). lo , route_resident_cfg (). hi , 2427rr_stats_ != nullptr ? rr_stats_ + ( n <= 8 ? 4 : 0 ) : nullptr , cs ); 2428} catch (const std:: exception & e ) { err = "verify route-resident: " + std:: string ( e . what ()); return false; } 2429} 2430if ( rs_on_ && G == 1 && n <= 16 && T <= 16 ) 2431strata::kernels:: route_marginal_stats ( ids_ + tb * K , n , ( int ) K , rs_dev_ + (( size_t ) T * ( size_t ) g . n_layers + ( size_t ) l ) * 16 , cs ); 2432if ( ar_on ()) { 2433resident_plan ( ids_ + tb * K , n * ( int ) K , ( int ) K , hits_ . d_res + l * g . n_expert , ( int ) g . n_expert , 2434hits_ . cache_base , slot_off_d_ , ( long long ) hits_ . blob , 2435plan_ + ( size_t ) grp * ( size_t ) ( plan_i32_ + 16 ), ( long long ) max_t_ * K , nullptr , 0 , cs , m_plan_err_ ); 2436} else { 2437if ( device_plan_ ) // E-6: every routed expert resident: this group's plan without the host 2438resident_plan ( ids_ + tb * K , n * ( int ) K , ( int ) K , hits_ . d_res + l * g . n_expert , ( int ) g . n_expert , 2439hits_ . cache_base , slot_off_d_ , ( long long ) hits_ . blob , 2440plan_ + ( size_t ) grp * ( size_t ) ( plan_i32_ + 16 ), ( long long ) max_t_ * K , skip_ + grp , 2441( uint32_t ) (( l - lb_ ) * G + grp + 1 ), cs ); 2442#if defined( STRATA_USE_HIP ) 2443if ( g_doorbell_store ) // #649 A/B: the step's ring stored, not incremented over PCIe 2444doorbell_publish_value ( xm , ids_ + tb * K , w_ + tb * K , ( int64_t ) n * N , ( int64_t ) n * K , m_x_ + tb * N , 2445m_ids_ + tb * K , m_w_ + tb * K , m_seq_ , ( uint32_t ) (( l - lb_ ) * G + grp + 1 ), cs ); 2446else 2447#endif 2448// #578: the helper GPUs reduce with the routing weights - publish them; set_always_publish: the rows 2449// whatever the device's residency table says (pipelined windows) 2450if ( remote_opt_ || always_publish_ ) 2451doorbell_publish ( xm , ids_ + tb * K , w_ + tb * K , ( int64_t ) n * N , ( int64_t ) n * K , m_x_ + tb * N , 2452m_ids_ + tb * K , m_w_ + tb * K , m_seq_ , cs ); 2453else { 2454const int32_t * layer_res = hits_ . d_res != nullptr ? ( hits_ . d_res + l * g . n_expert ) : nullptr ; 2455doorbell_publish_res ( xm , ids_ + tb * K , layer_res , ( int ) g . n_expert , ( int64_t ) n * N , ( int64_t ) n * K , 2456m_x_ + tb * N , m_ids_ + tb * K , m_seq_ , cs ); 2457} 2458if ( sh_fork_late ) { 2459note_prio_fork ( cs ); 2460cudaEventRecord ( ev_fork_ , cs ); 2461cudaStreamWaitEvent ( sh_cs_ , ev_fork_ , 0 ); 2462} 2463} 2464stamp ( l , 17 , grp ); 2465bool qdedup = false; // STRATA_VERIFY_QDEDUP took effect: the experts' q8_1 image of xm is already made 2466{ 2467const WeightRef * wgi = need ( v , "ffn_gate_inp_shexp.weight" , err ), * wsg = need ( v , "ffn_gate_shexp.weight" , err ), 2468* wsu = need ( v , "ffn_up_shexp.weight" , err ), * wsd = need ( v , "ffn_down_shexp.weight" , err ); 2469if (! wgi || ! wsg || ! wsu || ! wsd ) return false; 2470if (! native_of ( wsg , v . name ( "ffn_gate_shexp.weight" ), err ) || ! native_of ( wsu , v . name ( "ffn_up_shexp.weight" ), err ) || 2471! native_of ( wsd , v . name ( "ffn_down_shexp.weight" ), err )) 2472return false; 2473NativeSharedWeights nsw ; 2474nsw . gate_type = wsg -> native_type ; nsw . gate_data = wsg -> native_data ; 2475nsw . up_type = wsu -> native_type ; nsw . up_data = wsu -> native_data ; 2476nsw . down_type = wsd -> native_type ; nsw . down_data = wsd -> native_data ; 2477nsw . q8_1 = sh_fork ? sh_xq_ : xq_ ; 2478// STRATA_VERIFY_QDEDUP=1 (not with the forked shared-expert stream, which quantizes into its own buffer): the 2479// experts' q8_1 image of xm is made first and the shared expert's gate/up read it (quantize_q8_1_rows and 2480// native_quantize_q8_1 write the same bytes) 2481qdedup = g_qdedup () && ! sh_fork && strata::kernels::cpu:: expert_layout (). native ; 2482if ( qdedup && ! q8_ffn ) quantize_q8_1_rows ( xm , n , N , nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 , cs ); 2483if (! shared_expert_native_bf16_enabled ()) { 2484if ( dec_batch ) f32_to_bf16_bulk ( mixed_ + tb * N , sh_bf16_ + tb * N , ( int64_t ) n * N , sh_stream ); // contiguous rows 2485else for ( int t = tb ; t < te ; ++ t ) f32_to_bf16_bulk ( mixed_ + t * N , sh_bf16_ + t * N , N , sh_stream ); 2486} 2487try { 2488shared_expert_multi ( n , xm , sh_bf16_ + tb * N , nsw , (const uint16_t * ) wgi -> data , sh_gate_ + ( size_t ) tb * g . n_ff , 2489sh_up_ + ( size_t ) tb * g . n_ff , sh_g_ + tb , shared_ + tb * N , N , g . n_ff , sh_stream , 2490qdedup ? (const void * ) ( nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 ) : nullptr , 2491( sg_ready ? 1 : 0 ) | ( lfuse_on ( n ) && g_lfuse_pair () ? 2 : 0 )); 2492sg_gated_ [ grp ] = sg_ready ; 2493} catch (const std:: exception & e ) { 2494err = std:: string ( "verify shared expert: " ) + e . what (); 2495return false; 2496} 2497if ( sh_fork ) { 2498note_prio_tail ( sh_cs_ , -1 ); 2499cudaEventRecord ( ev_join_ , sh_cs_ ); 2500} 2501} 2502if (strata::kernels::cpu:: expert_layout (). native ) { 2503// APR: Hadamard-folded gate/up take H (s * x); xm itself stays as it is (the shared expert above and the 2504// doorbell copy for the CPU pool, which rotates its own in native_quant_act). The q8_1 image of xm that 2505// STRATA_QFUSE / STRATA_VERIFY_QDEDUP may already have written is of the unrotated input, so a folded layer 2506// always rewrites it from the rotated rows (same stream, after the shared expert has read it). 2507const auto & f = strata::kernels::cpu:: expert_layout (). fmt [( size_t ) l ]; 2508if ( f . had_gu ) { // nat_xr_ exists: init carved it because this layer is folded (had_gu_any) 2509hadamard_rows ( xm , nat_xr_ + ( size_t ) tb * N , n , N , f . had_block , had_sx_ , cs ); 2510quantize_q8_1_rows ( nat_xr_ + ( size_t ) tb * N , n , N , nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 , cs ); 2511} else if (! qdedup && ! q8_ffn ) { 2512quantize_q8_1_rows ( xm , n , N , nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 , cs ); 2513} 2514} else 2515quantize_q8_0_scaled ( xm , hit_xq_ + ( size_t ) tb * ( N / 32 ) * 34 , hit_xs_ + ( size_t ) tb * ( N / 32 ), ( int64_t ) n * N , cs ); 2516stamp ( l , 18 , grp ); 2517return true; 2518}; 2519 2520// ---------------------------------------------------------------- post(l, group): experts, combine 2521static const bool fuse_head_gr_env = [] { 2522const char * e = std:: getenv ( "STRATA_FUSE_HEAD_GR" ); 2523return e && e [ 0 ] == '1' ; 2524}(); 2525const bool fuse_head_gr = fuse_head_gr_env && ( le_ == g . n_layers ) && ( head_ != nullptr && head_ -> loaded ()) && 2526! cvec (). covers ( g . n_layers - 1 ); 2527auto post = [ & ]( int64_t l , int grp ) -> bool { 2528const int tb = tb_ [ grp ], te = te_ [ grp ], n = te - tb ; 2529const uint32_t ring = ( uint32_t ) (( l - lb_ ) * G + grp + 1 ); 2530const int64_t cap = ( int64_t ) n * K , capx = ( int64_t ) max_t_ * K ; 2531int32_t * pl = plan_ + ( size_t ) grp * ( size_t ) ( plan_i32_ + 16 ); 2532const int32_t * p_counts = pl ; 2533const int32_t * p_start = pl + 4 ; 2534const int32_t * p_dst = p_start + capx + 1 ; 2535const int32_t * p_tok = p_dst + capx ; 2536const int64_t ptr_off = (( 4 + ( capx + 1 ) + 2 * capx ) + 1 ) & ~ 1ll ; 2537const unsigned long long * p_ptr = (const unsigned long long * ) ( pl + ptr_off ); 2538const unsigned long long * p_ptr2 = p_ptr + capx ; 2539const int32_t * p_start2 = pl + ptr_off + 4 * capx ; 2540float * hit_out = hit_out_ + ( size_t ) tb * K * N ; 2541float * parts_out = parts_ + ( size_t ) tb * K * N ; 2542const auto & lay = strata::kernels::cpu:: expert_layout (); 2543// plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging. 2544// `gy`: the native launch's groups side by side (0: cap, one block row per possible group). 2545// `vram`: the groups point into this GPU's expert slots - a layer STRATA_EXPERT_NIBBLE converted holds its 2546// gate/up there as 4-bit codes (expert_nibble.hpp); the PCIe share's blobs (host memory, staging) never do. 2547auto grouped = [ & ](const unsigned long long * gp , const int32_t * gs , const int32_t * gn , int64_t gy , float * dst_buf , 2548bool vram ) { 2549if ( lay . native ) { 2550// the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down) 2551const auto & f = lay . fmt [( size_t ) l ]; 2552#if STRATA_EXPERT_NIBBLE_BUILT 2553NativeExpertLayout L = vram && strata::core::nibble:: layer ( l ). on 2554? native_expert_layout_nib ( f . gu_type , f . d_type , f . n_embd , f . n_ff ) 2555: native_expert_layout ( f . gu_type , f . d_type , f . n_embd , f . n_ff ); 2556#else 2557( void ) vram ; 2558NativeExpertLayout L = native_expert_layout ( f . gu_type , f . d_type , f . n_embd , f . n_ff ); 2559#endif 2560if ( f . had_d ) { L . had_block = f . had_block ; L . d_signs = had_sh_ ; } // APR: h is rotated in there 2561native_expert_grouped ( L , gp , gs , gn , p_dst , p_tok , cap , cap , 2562nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 , hit_scratch_ , dst_buf , cs , gy ); 2563} else { 2564moe_grouped_s2_window ( gp , gs , gn , p_dst , p_tok , cap , cap , hit_xq_ + ( size_t ) tb * ( N / 32 ) * 34 , 2565hit_xs_ + ( size_t ) tb * ( N / 32 ), hit_scratch_ , dst_buf , cs , n ); // (a group holds <= n entries) 2566} 2567}; 2568bool hits_in_combine = false; 2569if ( latent_ ) { 2570static const bool u_gpu_mode = [] { const char * v = std:: getenv ( "STRATA_LATENT_U_GPU" ); return v != nullptr && std:: atoi ( v ) != 0 ; }(); 2571if ( device_plan_ && ! u_gpu_mode ) { // the non-u_gpu tail ends in moe_hit_add_mapped's fused wait: no 2572err = "verify latent: device-plan requires STRATA_LATENT_U_GPU=1" ; // skip-aware variant yet 2573return false; 2574} 2575// (the D stage + its mapped copy + doorbell run in pre(l, 0), right after the FFN read - see there) 2576// The GPU plan arrives through mapped memory, exactly like the non-resident path below. 2577if ( device_plan_ ) { // E-6 latent: the device built this group's plan (all-resident) 2578wait_flag_ge_or ( m_flagA_ , ring , skip_ + grp , cs ); 2579copy_i32_from_mapped_unless ( pl , m_plan_ + ( size_t ) grp * ( size_t ) plan_i32_ , plan_i32_ , skip_ + grp , ring , cs ); 2580} else { 2581wait_flag_ge ( m_flagA_ , ring , cs ); // the pool published this group's GPU plan 2582copy_i32_from_mapped ( pl , m_plan_ + ( size_t ) grp * ( size_t ) plan_i32_ , plan_i32_ , cs ); 2583} 2584// A reads q8_1 rows of xl (row = token*G + labels[expert]), not the plain token rows. 2585int32_t * p_tokw = const_cast < int32_t *> ( p_tok ); 2586latent_plan_rows ( p_tokw , p_dst , p_counts , ids_ + ( size_t ) tb * K , 2587lat_labels_dev_ + ( size_t ) l * ( size_t ) lat_E_ , lat_E_ , tb , lat_G_ , ( int ) K , cs ); 2588// (the D stage + its mapped copy + doorbell ran in pre(l, G-1): see the tail of `pre`) 2589float * lat_yl_grp = lat_yl_ + ( size_t ) tb * K * ( size_t ) lat_ELL_ ; 2590const auto & LF = lay . fmt [( size_t ) l ]; 2591const NativeExpertLayout La = native_expert_layout ( LF . gu_type , LF . d_type , ( int ) lat_ELL_ , ( int ) lat_I_ ); 2592stamp ( l , 19 , grp ); 2593native_expert_grouped ( La , p_ptr , p_start , p_counts , p_dst , p_tok , cap , cap , lat_xlq_ , hit_scratch_ , 2594lat_yl_grp , cs , 0 ); // the VRAM-resident share 2595stamp ( l , 20 , grp ); 2596if ( device_plan_ ) 2597wait_flag_ge_or ( m_flagB_ , ring , skip_ + grp , cs ); // E-6 latent: no PCIe share in an all-resident plan 2598else 2599wait_flag_ge ( m_flagB_ , ring , cs ); // the PCIe share's blobs are staged (DMA) or mapped 2600if ( sink_ . pcie_mode == 2 ) { // stage with a copy kernel, then point at staging (plan v0.3 P6) 2601const int64_t per = 4 * kStagingBlobs ; // latent: each group's whole PCIe share fits (n*K <= 64 (edge0: T=4 x K=10 = 40)) 2602uint8_t * stage = staging_ + ( size_t ) ( grp * per ) * lay . max_blob ; 2603fetch_blobs ( p_ptr2 , p_counts + 2 , stage , ( int64_t ) lay . blob_bytes ( l ), ( int ) per , cs ); 2604rebase_ptrs (( unsigned long long * ) p_ptr2 , p_counts + 2 , stage , ( int64_t ) lay . blob_bytes ( l ), cs ); 2605} 2606stamp ( l , 21 , grp ); 2607native_expert_grouped ( La , p_ptr2 , p_start2 , p_counts + 2 , p_dst , p_tok , cap , cap , lat_xlq_ , hit_scratch_ , 2608lat_yl_grp , cs , kPcieGroupRows ); // the PCIe share 2609// U: route r reads yl[r] and U[labels[ids[r]]]; the result is parts_ (one K*N block per group, route order) 2610quantize_q8_1_rows ( lat_yl_grp , cap , ( int ) lat_ELL_ , lat_uq_ , cs ); 2611latent_u_grouped ( lat_u_ + ( size_t ) ( l - lat_first_layer_ ) * lat_dense_ . u_bytes (), (const uint8_t * ) lat_uq_ , ids_ + ( size_t ) tb * K , 2612lat_labels_dev_ + ( size_t ) l * ( size_t ) lat_E_ , lat_E_ , cap , ( int ) lat_ELL_ , ( int ) N , 2613hit_out , cs , lat_fmt_ ); 2614// The CPU pool's share: its full N-dim contributions land in the mapped rows (m_ymiss_); copy them into 2615// parts_ (the GPU's own rows are zeroed there), then add the GPU's U-stage rows computed above into hit_out. 2616static const bool seg_split = std:: getenv ( "STRATA_SEG_SPLIT" ) != nullptr ; // the copy-segment breakdown 2617static const bool u_gpu = [] { const char * v = std:: getenv ( "STRATA_LATENT_U_GPU" ); return v != nullptr && std:: atoi ( v ) != 0 ; }(); 2618if ( u_gpu ) { // knife-0: the CPU's hq rows -> U on the GPU, into parts_ directly (fused wait + U.hq + hit_out) 2619if ( trace_m_ != nullptr ) gpu_stamp ( trace_m_ , ( l * kProfPer + 36 ) * 2 , cs ); // T-TRI breadcrumb (not a profile slot) 2620if ( device_plan_ ) 2621wait_flag_ge_or ( m_flag_ , ring , skip_ + grp , cs ); // E-6 latent: no CPU rows in an all-resident plan 2622else 2623wait_flag_ge ( m_flag_ , ring , cs ); // separate 1-block wait (not 12800 fused spins) 2624if ( trace_m_ != nullptr ) gpu_stamp ( trace_m_ , ( l * kProfPer + 37 ) * 2 , cs ); // T-TRI breadcrumb 2625// knife-0: a copy KERNEL, not cudaMemcpyAsync: a host-issued H2D inside the verify window (the GPU 2626// spinning on the flag it raises) is the issue #31 driver-lock deadlock; the kernel moves the same 2627// bytes with no host CUDA call (the engine's own remedy for this path, generate.cpp:10329-10333). 2628strata::kernels:: copy_bytes_from_mapped ( hq_dev_ , m_ymiss_ + ( size_t ) tb * K * N , 2629( size_t ) cap * (( size_t ) lat_ELL_ / 32 * 36 ), cs ); 2630strata::kernels:: latent_u_matvec ( lat_u_ + ( size_t ) ( l - lat_first_layer_ ) * lat_dense_ . u_bytes (), 2631(const uint8_t * ) hq_dev_ , 2632ids_ + ( size_t ) tb * K , lat_labels_dev_ + ( size_t ) l * ( size_t ) lat_E_ , 2633p_dst , p_counts + 1 , ( int64_t ) lat_E_ , cap , 2634( int ) lat_ELL_ , ( int ) N , ( int ) lat_G_ , parts_out , cs , lat_fmt_ ); 2635moe_hit_set ( parts_out , hit_out , p_dst , p_counts + 1 , cap , N , cs ); // knife-0: assign, as u0 does 2636if ( trace_m_ != nullptr ) gpu_stamp ( trace_m_ , ( l * kProfPer + 38 ) * 2 , cs ); // T-TRI breadcrumb 2637} else if ( seg_split ) { // SEGSPLIT: the measured three-step form (wait / copy / add separated) 2638stamp ( l , 32 , grp ); // before-wait (slot 32: unused) 2639wait_flag_ge ( m_flag_ , ring , cs ); 2640stamp ( l , 33 , grp ); // wait done (ymWait ends) 2641copy_rows_from_mapped ( parts_out , m_ymiss_ + ( size_t ) tb * K * N , ( int64_t ) n * K , N , 2642p_dst , p_counts + 1 , cs ); 2643stamp ( l , 34 , grp ); // copy done (ymCopy ends) 2644moe_hit_add ( parts_out , hit_out , p_dst , p_counts + 1 , cap , N , cs ); 2645stamp ( l , 35 , grp ); // add done (ymAdd ends) 2646} else { 2647moe_hit_add_mapped ( parts_out , hit_out , m_ymiss_ + ( size_t ) tb * K * N , p_dst , p_counts + 1 , cap , N , 2648(const volatile uint32_t * ) m_flag_ , ring , cs ); // LATENT-CUT-A: the fused wait+add 2649} 2650hits_in_combine = false; 2651} else if ( ar_on ()) { 2652strata::dispatch:: note ( "experts layer: all-resident device plan, grouped experts straight into the parts (no doorbell, no CPU rows)" ); 2653stamp ( l , 19 , grp ); 2654grouped ( p_ptr , p_start , p_counts , 0 , parts_out , true); 2655stamp ( l , 20 , grp ); 2656} else { 2657strata::dispatch:: notef ( "experts layer: partial residency, plan from %ld (1 = device plan, 0 = host pool), pcie_mode=%ld, remote_opt=%ld" , ( long ) device_plan_ , ( long ) sink_ . pcie_mode , ( long ) ( remote_opt_ != nullptr )); 2658if ( device_plan_ ) { // E-6: skipped when the device planned this group (all its experts resident) 2659wait_flag_ge_or ( m_flagA_ , ring , skip_ + grp , cs ); 2660copy_i32_from_mapped_unless ( pl , m_plan_ + ( size_t ) grp * ( size_t ) plan_i32_ , plan_i32_ , skip_ + grp , ring , cs ); 2661} else { 2662if ( fuse_wait_on () && ! prof_on_ && m_bal_ == nullptr ) { // 143-amdk: one launch for the wait and the copy 2663wait_copy_i32_from_mapped ( m_flagA_ , ring , pl , m_plan_ + ( size_t ) grp * ( size_t ) plan_i32_ , plan_i32_ , cs ); 2664} else { 2665if ( m_bal_ != nullptr ) // set_pcie_balance: the GPU's share starts as the plan arrives 2666wait_flag_ge_stamped ( m_flagA_ , ring , nullptr , m_bal_ + (( l - lb_ ) * 2 + grp ) * 4 , cs ); 2667else 2668wait_flag_ge ( m_flagA_ , ring , cs ); // the pool published this group's GPU plan 2669copy_i32_from_mapped ( pl , m_plan_ + ( size_t ) grp * ( size_t ) plan_i32_ , plan_i32_ , cs ); 2670} 2671} 2672stamp ( l , 19 , grp ); 2673grouped ( p_ptr , p_start , p_counts , 0 , hit_out , true); 2674stamp ( l , 20 , grp ); 2675if ( device_plan_ ) wait_flag_ge_or ( m_flagB_ , ring , skip_ + grp , cs ); 2676else if ( m_bal_ != nullptr ) // set_pcie_balance: the PCIe part starts 2677wait_flag_ge_stamped ( m_flagB_ , ring , m_bal_ + (( l - lb_ ) * 2 + grp ) * 4 + 1 , nullptr , cs ); 2678else { if ( trace_m_ != nullptr ) gpu_stamp ( trace_m_ , ( l * kProfPer + 15 ) * 2 , cs ); wait_flag_ge ( m_flagB_ , ring , cs ); if ( trace_m_ != nullptr ) gpu_stamp ( trace_m_ , ( l * kProfPer + 25 ) * 2 , cs ); } // K0: flagB wait enter(40)/exit(41) 2679if ( sink_ . pcie_mode == 2 ) { // stage it with a copy kernel, then point at staging 2680const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs ; 2681uint8_t * stage = staging_ + ( size_t ) ( grp * per ) * lay . max_blob ; 2682const unsigned long long * p_dst2 = (const unsigned long long * ) ( pl + dst2_off_ ); // STRATA_ADAPT_FETCH 2683fetch_blobs ( p_ptr2 , p_counts + 2 , stage , ( int64_t ) lay . blob_bytes ( l ), ( int ) per , cs , p_dst2 ); 2684rebase_ptrs (( unsigned long long * ) p_ptr2 , p_counts + 2 , stage , ( int64_t ) lay . blob_bytes ( l ), cs , p_dst2 ); 2685} 2686stamp ( l , 21 , grp ); 2687// the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at 2688// pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them 2689grouped ( p_ptr2 , p_start2 , p_counts + 2 , kPcieGroupRows , hit_out , false); 2690stamp ( l , 22 , grp ); 2691if ( device_plan_ ) { // no CPU share when the device planned the group: its rows are zeros 2692wait_flag_ge_or ( m_flag_ , ring , skip_ + grp , cs ); 2693copy_or_zero_from_mapped ( parts_out , m_ymiss_ + ( size_t ) tb * K * N , ( long long ) n * K * N , 2694skip_ + grp , ring , cs ); 2695} else { 2696const bool fuse_rows = fuse_rows_on () && ! prof_on_ && ! remote_opt_ && dec_batch && m_bal_ == nullptr ; // 143-amdk 2697if (! fuse_rows ) { 2698if ( m_bal_ != nullptr ) // set_pcie_balance: ... and ends as it waits for the CPU's rows 2699wait_flag_ge_stamped ( m_flag_ , ring , m_bal_ + (( l - lb_ ) * 2 + grp ) * 4 + 2 , nullptr , cs ); 2700else { 2701if ( trace_m_ != nullptr ) gpu_stamp ( trace_m_ , ( l * kProfPer + 27 ) * 2 , cs ); 2702wait_flag_ge ( m_flag_ , ring , cs ); // the CPU's share is in the mapped rows 2703if ( trace_m_ != nullptr ) gpu_stamp ( trace_m_ , ( l * kProfPer + 28 ) * 2 , cs ); 2704} 2705} 2706stamp ( l , 23 , grp ); 2707if ( remote_opt_ ) // #578: the helper's rows come back reduced; skip them as well 2708remote_opt_ -> copy_rows ( parts_out , m_ymiss_ + ( size_t ) tb * K * N , tb , n , p_dst , p_counts + 1 , cs ); 2709else if ( fuse_rows ) // the wait folded into the copy's blocks 2710copy_rows_from_mapped_after ( m_flag_ , ring , parts_out , m_ymiss_ + ( size_t ) tb * K * N , ( int64_t ) n * K , N , 2711p_dst , p_counts + 1 , cs ); 2712else if ( dec_batch ) // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows) 2713copy_rows_from_mapped ( parts_out , m_ymiss_ + ( size_t ) tb * K * N , ( int64_t ) n * K , N , 2714p_dst , p_counts + 1 , cs ); 2715else 2716copy_from_mapped ( parts_out , m_ymiss_ + ( size_t ) tb * K * N , ( int64_t ) n * K * N , cs ); 2717} 2718// 143-amdk: the add of the GPU's hit rows is done by the combine that follows (one launch fewer) 2719hits_in_combine = fuse_hits_on () && ! prof_on_ && ! remote_opt_ && ! sg_gated_ [ grp ] && dec_batch && n > 1 && 2720native_moe_combine_enabled () && n <= 8 && 2721native_moe_combine_hits_supported ( parts_ + ( size_t ) tb * K * N , shared_ + tb * N , bo_ + tb * N , N , K , n ); 2722strata::dispatch:: notef ( "experts layer: cpu rows via %ld (1 = fused wait+copy, 0 = wait then copy), hits in combine=%ld" , ( long ) ( fuse_rows_on () && ! prof_on_ && ! remote_opt_ && dec_batch && m_bal_ == nullptr ), ( long ) hits_in_combine ); 2723if (! hits_in_combine ) moe_hit_add ( parts_out , hit_out , p_dst , p_counts + 1 , cap , N , cs ); 2724} 2725// Same condition as `sh_fork` above, which is per group and out of scope here: wait only when the fork 2726// actually ran (a wait on an event never recorded is a no-op, but saying it outright reads better). 2727if ( sh_stream_on () && ! prof_on_ && sh_cs_ != nullptr && ev_fork_ != nullptr && ev_join_ != nullptr ) { 2728cudaStreamWaitEvent ( cs , ev_join_ , 0 ); 2729} 2730strata::dispatch:: notef ( "combine layer: kind %ld (0 per-token, 1 multi, 2 multi+hits, 3 multi+hits gated)" , ( long ) ( sg_gated_ [ grp ] ? 3 : hits_in_combine ? 2 : ( dec_batch && n > 1 && native_moe_combine_enabled ()) ? 1 : 0 )); 2731if ( sg_gated_ [ grp ]) { // STRATA_LFUSE: the shared expert's gate was not applied: the combine applies it (all rows are hits) 2732try { 2733native_moe_combine_multi_hits_gated ( parts_out , w_ + tb * K , shared_ + tb * N , sh_g_ + tb , bo_ + tb * N , N , K , n , cs ); 2734} catch (const std:: exception & e ) { err = "verify combine: " + std:: string ( e . what ()); return false; } 2735} else 2736if ( hits_in_combine ) { 2737try { 2738native_moe_combine_multi_hits_added ( parts_ + ( size_t ) tb * K * N , hit_out , p_dst , p_counts + 1 , w_ + tb * K , 2739shared_ + tb * N , bo_ + tb * N , N , K , n , cs ); 2740} catch (const std:: exception & e ) { err = "verify combine: " + std:: string ( e . what ()); return false; } 2741} else 2742if ( dec_batch && n > 1 && native_moe_combine_enabled ()) { // one launch for the window's rows 2743try { 2744native_moe_combine_multi ( parts_ + ( size_t ) tb * K * N , w_ + tb * K , shared_ + tb * N , bo_ + tb * N , N , K , n , cs ); 2745} catch (const std:: exception & e ) { err = "verify combine: " + std:: string ( e . what ()); return false; } 2746} else 2747for ( int t = tb ; t < te ; ++ t ) { 2748MoEBuffers mb = ss . moe ; 2749mb . weights = w_ + t * K ; mb . shared = shared_ + t * N ; 2750if (! moe_combine_parts ( g , l , K , mb , parts_ + ( size_t ) t * K * N , bo_ + t * N , cs , err )) return false; 2751} 2752if ( remote_opt_ ) remote_opt_ -> combine ( bo_ + tb * N , y_dummy_ + tb * N , tb , n , 2753device_plan_ ? skip_ + grp : nullptr , ring , cs ); 2754stamp ( l , 24 , grp ); 2755if ( tap_on_ && (! batch_rec_ || tap_batch_ ) && l < ( int64_t ) tap_slot_ . size () && tap_slot_ [( size_t ) l ] >= 0 ) { 2756// the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it), the mean of 2757// the hc streams, all rows of the group in one launch 2758const int64_t nt = ( int64_t ) tap_layers_ . size (); 2759#if defined( STRATA_HAVE_DFLASH2 ) 2760strata::kernels:: df2_tap_gr ( Rt ( tb ), HC * N , bo_ + tb * N , N , inj2_ + tb * HC , HC , tap_dev_ + (( size_t ) tb * nt + ( size_t ) tap_slot_ [( size_t ) l ]) * N , 2761nt * N , n , N , ( int ) HC , cs ); 2762#else // builds without the DFlash2 kernels (Metal, SYCL): the research dump's per-row path 2763for ( int t = tb ; t < te ; ++ t ) { 2764cudaMemcpyAsync ( tap_scratch_ , Rt ( t ), ( size_t ) HC * N * 4 , cudaMemcpyDeviceToDevice , cs ); 2765gr_write ( tap_scratch_ , bo_ + t * N , inj2_ + t * HC , gs , tap_scratch_ , cs ); 2766hc_mean_streams ( tap_scratch_ , tap_dev_ + (( size_t ) t * nt + ( size_t ) tap_slot_ [( size_t ) l ]) * N , N , ( int ) HC , cs ); 2767} 2768#endif 2769} 2770if ( l == g . n_layers - 1 ) { 2771if (! fuse_head_gr ) { 2772if ( dec_batch && ! g_no_multi_gr ) gr_write_multi ( Rt ( tb ), bo_ + tb * N , inj2_ + tb * HC , gs , Rt ( tb ), n , cs ); 2773else for ( int t = tb ; t < te ; ++ t ) gr_write ( Rt ( t ), bo_ + t * N , inj2_ + t * HC , gs , Rt ( t ), cs ); 2774if ( cvec (). covers ( l )) cvec_apply ( Rt ( tb ), l , n , HC * N , nullptr , 0 , nullptr , 0 , false, cs ); 2775} 2776} else if ( cvec (). covers ( l )) { 2777cvec_apply ( Rt ( tb ), l , n , HC * N , bo_ + tb * N , N , inj2_ + tb * HC , HC , true, cs ); 2778} 2779return true; 2780}; 2781 2782for ( int grp = 0 ; grp < G ; ++ grp ) 2783if (! pre ( lb_ , grp )) return false; 2784for ( int64_t l = lb_ ; l < le_ ; ++ l ) 2785for ( int grp = 0 ; grp < G ; ++ grp ) { 2786if (! post ( l , grp )) return false; 2787if ( l + 1 < le_ && ! pre ( l + 1 , grp )) return false; 2788} 2789if ( le_ < g . n_layers ) { // a layer split's earlier stage: hand the residual on, no head 2790float * hout = hand_out_ + ( size_t ) hrow0 * HB ; 2791if ( hflag_out_d_ != nullptr && ! batch_rec_ ) { // the overlapped split: payload + the next stage's flag 2792handoff_publish ( hout , R_ , ( int64_t ) T * HC * N , bo_ , ( int64_t ) T * N , inj2_ , ( int64_t ) T * HC , hcount_d_ , 2793hflag_out_d_ , cs , g_test_drop > 0 ? hdrop_d_ : nullptr ); // the test word only with the hook on 2794return true; 2795} 2796copy_from_mapped ( hout , R_ , ( int64_t ) T * HC * N , cs ); 2797copy_from_mapped ( hout + ( size_t ) T * HC * N , bo_ , ( int64_t ) T * N , cs ); 2798copy_from_mapped ( hout + ( size_t ) T * ( HC + 1 ) * N , inj2_ , ( int64_t ) T * HC , cs ); 2799return true; 2800} 2801 2802// ---- the head, T columns, and the argmax of each. The final mixer and the head matvec take at most 2803// kFusedGrMaxT columns a launch: a longer window (--lookup-max-t) runs them in chunks of that many columns (one 2804// chunk - the same launches as before - for every window up to kFusedGrMaxT tokens) 2805stamp ( g . n_layers , 0 , 0 ); 2806{ 2807const WeightRef * hn = wt . find ( "output_hc_norm.weight" ), * hd = wt . find ( "output_hc_down.weight" ), 2808* hu = wt . find ( "output_hc_up.weight" ); 2809if (! hn || ! hd || ! hu ) { err = "verify: an output_hc_* weight is missing" ; return false; } 2810for ( int h0 = 0 ; h0 < T ; h0 += kFusedGrMaxT ) { 2811const int HT = std:: min ( T - h0 , kFusedGrMaxT ); // this chunk's columns: h0 .. h0 + HT 2812// S25 (STRATA_HC_Q8=1): the final mixer from the GGUF's Q8_0 projections too, through the same multi read 2813// (no pending write, no inject) 2814const bool mix_q8 = hd -> hc_q8 != nullptr && hu -> hc_q8 != nullptr && head_ != nullptr && head_ -> loaded (); 2815bool q8_head = false; // the fused read wrote the head's q8_1 activation image (xq_) itself 2816strata::dispatch:: notef ( "head: final mixer q8=%ld fuse_head_gr=%ld native_head=%ld" , ( long ) mix_q8 , ( long ) fuse_head_gr , ( long ) ( head_ != nullptr && head_ -> loaded ())); 2817if ( head_ != nullptr && head_ -> loaded ()) // the head matrix itself is counted by native_mmvq / native_mmvq_il (n_out = the vocabulary) 2818strata::dispatch:: notef ( "head: type %ld, T=%ld columns, vocabulary %ld" , ( long ) head_ -> type (), ( long ) T , ( long ) n_vocab_ ); 2819if ( mix_q8 ) { 2820FusedGrArgs fa [ kFusedGrMaxT ]; 2821for ( int t = h0 ; t < h0 + HT ; ++ t ) { 2822FusedGrArgs & a = fa [ t - h0 ]; 2823a . R = Rt ( t ); a . R_out = Rt ( t ); a . apply = false; 2824a . w_norm = (const float * ) hn -> data ; a . w_down = (const uint16_t * ) hd -> data ; 2825a . w_up = (const uint16_t * ) hu -> data ; a . w_inject = nullptr ; 2826a . q8_down = (const uint8_t * ) hd -> hc_q8 ; a . q8_up = (const uint8_t * ) hu -> hc_q8 ; 2827a . eps = EPS ; a . lo = lo_ + t * g . hc_lr ; a . rs = rs_ + t * HC ; 2828a . mixed = head_mixed_ + t * N ; 2829if ( qcnt_ != nullptr ) { a . q8_cnt = qcnt_ ; a . q8_mixed = xq_ + ( size_t ) ( t - h0 ) * ( N / 32 ) * 36 ; } 2830} 2831q8_head = fused_gr_read_multi ( fa , HT , xn_ + ( size_t ) h0 * HC * N , cs ); 2832} 2833else if ( fuse_head_gr ) { 2834FusedGrArgs fa [ kFusedGrMaxT ]; 2835for ( int t = h0 ; t < h0 + HT ; ++ t ) { 2836FusedGrArgs & a = fa [ t - h0 ]; 2837a . R = Rt ( t ); a . R_out = Rt ( t ); a . apply = true; 2838a . bo_prev = bo_ + t * N ; a . inj_prev = inj2_ + t * HC ; 2839a . w_norm = (const float * ) hn -> data ; 2840a . w_down = (const uint16_t * ) hd -> data ; 2841a . w_up = (const uint16_t * ) hu -> data ; 2842a . w_inject = nullptr ; 2843a . eps = EPS ; 2844a . lo = lo_ + t * g . hc_lr ; 2845a . rs = rs_ + t * HC ; 2846a . inject_out = head_inj_ ; 2847a . mixed = head_mixed_ + t * N ; 2848if ( qcnt_ != nullptr && head_ != nullptr && head_ -> loaded ()) { 2849a . q8_cnt = qcnt_ ; 2850a . q8_mixed = xq_ + ( size_t ) ( t - h0 ) * ( N / 32 ) * 36 ; 2851} 2852} 2853q8_head = fused_gr_read_multi ( fa , HT , xn_ + ( size_t ) h0 * HC * N , cs ); 2854} else if ( head_mix_multi_enabled () && head_ != nullptr && head_ -> loaded ()) { 2855// the final mixer, the window's tokens in one read (fused_gr_read_multi without the pending write: the 2856// last layer's write was done above; its sums are gr_read's) 2857if ( hn -> kind != WeightKind :: F32 || hd -> kind != WeightKind :: Bf16InF32 || hu -> kind != WeightKind :: Bf16InF32 ) { 2858err = "verify: the output_hc_* weights have the wrong engine forms" ; 2859return false; 2860} 2861FusedGrArgs fa [ kFusedGrMaxT ]; 2862for ( int t = h0 ; t < h0 + HT ; ++ t ) { 2863FusedGrArgs & a = fa [ t - h0 ]; 2864a . R = Rt ( t ); a . R_out = Rt ( t ); a . apply = false; 2865a . w_norm = (const float * ) hn -> data ; a . w_down = (const uint16_t * ) hd -> data ; 2866a . w_up = (const uint16_t * ) hu -> data ; a . eps = EPS ; 2867a . lo = lo_ + t * g . hc_lr ; a . rs = rs_ + t * HC ; a . mixed = head_mixed_ + t * N ; 2868if ( qcnt_ != nullptr ) { a . q8_cnt = qcnt_ ; a . q8_mixed = xq_ + ( size_t ) ( t - h0 ) * ( N / 32 ) * 36 ; } 2869} 2870q8_head = fused_gr_read_multi ( fa , HT , xn_ + ( size_t ) h0 * HC * N , cs ); 2871} else { 2872for ( int t = h0 ; t < h0 + HT ; ++ t ) { 2873BlockBuffers bb = ss . block ; 2874bb . R = Rt ( t ); 2875bb . mixed = head_mixed_ + t * N ; 2876if ( head_ != nullptr && head_ -> loaded ()) { 2877if (! lm_head_mix ( wt , g , bb , cs , err )) return false; 2878} else if (! lm_head ( wt , g , bb , head_logits_ + ( size_t ) t * n_vocab_ , cs , err )) { 2879return false; 2880} 2881} 2882} 2883if ( head_ != nullptr && head_ -> loaded ()) { 2884try { 2885float * const hl = head_logits_ + ( size_t ) h0 * ( size_t ) n_vocab_ ; 2886if (! q8_head ) native_quantize_q8_1 ( head_mixed_ + ( size_t ) h0 * N , xq_ , ( int ) N , HT , cs ); // (else the fused read wrote this chunk's image at xq_) 2887if ( g_mmvq_il () && strata::kernels:: native_mmvq_il_supported ( head_ -> type (), ( int ) HT , ( int ) n_vocab_ )) { 2888if ( HT >= 2 ) strata::kernels:: native_q8_1_interleave ( xq_ , xil_ , ( int ) N , ( int ) HT , cs ); 2889strata::kernels:: native_mmvq_il ( head_ -> type (), head_ -> weights (), xq_ , xil_ , hl , ( int ) N , 2890( int ) n_vocab_ , ( int ) HT , cs ); 2891} else 2892native_mmvq ( head_ -> type (), head_ -> weights (), xq_ , hl , ( int ) N , ( int ) n_vocab_ , HT , cs ); 2893} catch (const std:: exception & e ) { 2894err = std:: string ( "verify head: " ) + e . what (); 2895return false; 2896} 2897} 2898} // the head's column chunks 2899// Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that 2900// samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a 2901// fresh draw counter: a captured sampler would bake them in and replay the same draws forever. 2902if ( argmax_rows_wanted ()) { // sm_80 to sm_89 (sm_7x opt-in): the pick over many blocks a row (bitwise the one-block kernel's) 2903argmax_rows ( head_logits_ , T , ( int ) n_vocab_ , arg_scratch_ , m_out_ , cs ); 2904} else { 2905SamplerParams sp ; 2906sp . greedy = true; 2907sp . temperature = 0.0f ; 2908sample_tokens ( head_logits_ , T , ( int ) n_vocab_ , nullptr , 0 , sp , m_out_ , cs ); 2909} 2910// #879: whether each row's logits are all finite, beside the pick (read after the window's own sync) 2911if ( nan_guard_on ()) strata::kernels:: logits_nonfinite_rows ( head_logits_ , T , ( int ) n_vocab_ , m_nf_ , cs ); 2912if ( g_dbg && windows <= 12 && n_vocab_ > 0 && T > 0 ) { // STRATA_VERIFY_DEBUG: the first windows' top-3 2913static std:: vector < float > tmp ; 2914tmp . resize (( size_t ) n_vocab_ ); 2915cudaMemcpy ( tmp . data (), head_logits_ , sizeof( float ) * ( size_t ) n_vocab_ , cudaMemcpyDeviceToHost ); 2916float va = -1e30f , vb = -1e30f , vc = -1e30f ; 2917int ia = -1 , ib = -1 , ic = -1 ; 2918double s2 = 0.0 ; 2919for ( int k = 0 ; k < n_vocab_ ; ++ k ) { 2920float v = tmp [( size_t ) k ]; 2921s2 += ( double ) v * ( double ) v ; 2922if ( v > va ) { vc = vb ; ic = ib ; vb = va ; ib = ia ; va = v ; ia = k ; } 2923else if ( v > vb ) { vc = vb ; ic = ib ; vb = v ; ib = k ; } 2924else if ( v > vc ) { vc = v ; ic = k ; } 2925} 2926std:: fprintf ( stderr , "verify top3: win=%lld T=%d -> %d(%.3f) %d(%.3f) %d(%.3f) rms=%.4f\n" , 2927( long long ) windows , ( int ) T , ia , ( double ) va , ib , ( double ) vb , ic , ( double ) vc , 2928std:: sqrt ( s2 / ( double ) n_vocab_ )); 2929std:: fflush ( stderr ); 2930} 2931} 2932stamp ( g . n_layers , 1 , 0 ); 2933if ( tap_on_ && ! batch_rec_ && tap_file_ != nullptr ) copy_from_mapped ( m_tap_ , tap_dev_ , ( int64_t ) T * ( int64_t ) tap_layers_ . size () * N , cs ); 2934return true; 2935} 2936 2937std:: string Verifier :: profile_by_t_report () { 2938if (! prof_on_ ) return std:: string (); 2939static const char * names [ kProfPer ] = { "-" , "hc-read0" , "qkv gemv" , "conv" , "ab" , "z" , "rec" , "q8+kv-idx" , "k/v+norm-rope" , "kv+idx append" , "q+q-idx" , "scores+topk" , "kv-resolve" , "attention" , "gate" , "" , "out-proj" , "router+plan" , "shared+quant" , "waitA" , "VRAM hits" , "waitB" , "PCIe grp" , "waitCPU" , "copy+combine" , "(gap)" , "head" , "hc0 norm" , "hc0 down" , "hc0 up" , "hc1 norm" , "hc1 down" , "hc1 up" , "ymWait" , "ymCopy" , "ymAdd" }; 2940std:: string out ; 2941char b [ 96 ]; 2942for ( int T = 1 ; T <= 16 ; ++ T ) { 2943if ( prof_t_win_ [ T ] == 0 ) continue; 2944double total = 0 ; 2945std:: snprintf ( b , sizeof b , "T%d (n=%lld):" , T , ( long long ) prof_t_win_ [ T ]); 2946out += b ; 2947for ( int k = 0 ; k < 2 ; ++ k ) { 2948out += k == 0 ? " GDN[" : " | QSA[" ; 2949for ( int i = 0 ; i < kProfPer ; ++ i ) { 2950if ( prof_t_sum_ [ T ][ k ][ i ] <= 0 ) continue; 2951total += prof_t_sum_ [ T ][ k ][ i ]; 2952std:: snprintf ( b , sizeof b , " %s %.3f" , names [ i ], prof_t_sum_ [ T ][ k ][ i ] / 1e6 / ( double ) prof_t_win_ [ T ]); 2953out += b ; 2954} 2955out += " ]" ; 2956} 2957std:: snprintf ( b , sizeof b , " | total %.2f ms\n" , total / 1e6 / ( double ) prof_t_win_ [ T ]); 2958out += b ; 2959} 2960std:: memset ( prof_t_sum_ , 0 , sizeof prof_t_sum_ ); 2961std:: memset ( prof_t_win_ , 0 , sizeof prof_t_win_ ); 2962return out ; 2963} 2964 2965std:: string Verifier :: route_stats_report () { 2966if (! rs_on_ || rs_dev_ == nullptr || g_ == nullptr ) return std:: string (); 2967const int64_t L = g_ -> n_layers ; 2968std:: vector < unsigned long long > h (( size_t ) 17 * ( size_t ) L * 16 ); 2969cudaMemcpy ( h . data (), rs_dev_ , h . size () * 8 , cudaMemcpyDeviceToHost ); 2970std:: string out ; 2971char b [ 160 ]; 2972for ( int T = 1 ; T <= 16 ; ++ T ) { 2973if ( rs_win_ [ T ] == 0 ) continue; 2974double row [ 16 ] = {}; 2975for ( int64_t l = 0 ; l < L ; ++ l ) 2976for ( int r = 0 ; r < 16 ; ++ r ) row [ r ] += ( double ) h [(( size_t ) T * ( size_t ) L + ( size_t ) l ) * 16 + ( size_t ) r ]; 2977const double denom = ( double ) rs_win_ [ T ] * ( double ) L ; 2978double sum = 0 ; 2979for ( int r = 0 ; r < T ; ++ r ) sum += row [ r ] / denom ; 2980std:: snprintf ( b , sizeof b , "T%d (n=%lld): distinct experts per layer %.2f; new per row:" , T , ( long long ) rs_win_ [ T ], sum ); 2981out += b ; 2982for ( int r = 0 ; r < T ; ++ r ) { 2983std:: snprintf ( b , sizeof b , " %.2f" , row [ r ] / denom ); 2984out += b ; 2985} 2986out += "\n" ; 2987} 2988cudaMemset ( rs_dev_ , 0 , h . size () * 8 ); 2989std:: memset ( rs_win_ , 0 , sizeof rs_win_ ); 2990return out ; 2991} 2992 2993std:: string Verifier :: profile_report () { 2994if (! prof_on_ || prof_windows_ == 0 ) return std:: string (); 2995static const char * names [ kProfPer ] = { "-" , "hc-read0" , "q8+qkv/q-idx gemv" , "conv" , "ab" , "z" , "rec" , "q8+kv-idx" , "k/v+norm-rope" , "kv+idx append" , "q+q-idx" , "scores+topk" , "kv-resolve" , "attention" , "gate" , "" , "out-proj" , "router+plan+bell" , "shared+quant" , "waitA" , "VRAM hits" , "waitB" , "PCIe grp" , "waitCPU" , "copy+combine" , "(gap)" , "head" , " hc0 norm" , " hc0 down" , " hc0 up" , " hc1 norm" , " hc1 down" , " hc1 up" , "" , "" , "" }; 2996std:: string out ; 2997char b [ 80 ]; 2998double total = 0 ; 2999for ( int k = 0 ; k < 2 ; ++ k ) { 3000out += k == 0 ? " GDN layers:" : " | QSA layers:" ; 3001for ( int i = 0 ; i < kProfPer ; ++ i ) { 3002if ( prof_sum_ [ k ][ i ] <= 0 ) continue; 3003total += prof_sum_ [ k ][ i ]; 3004std:: snprintf ( b , sizeof b , " %s %.2f" , names [ i ], prof_sum_ [ k ][ i ] / 1e6 / ( double ) prof_windows_ ); 3005out += b ; 3006} 3007} 3008std:: snprintf ( b , sizeof b , " | total %.2f ms/window over %lld windows" , total / 1e6 / ( double ) prof_windows_ , ( long long ) prof_windows_ ); 3009out += b ; 3010for ( auto & r : prof_sum_ ) for ( double & d : r ) d = 0 ; 3011prof_windows_ = 0 ; 3012return out ; 3013} 3014 3015// #871: is the zero-doorbell graph right for the next window? Only while every expert of [lb_, le_) is in VRAM now 3016// (the host table is the one the device copy was uploaded from; a loan, a VRAM shrink or a swap in flight has 3017// marked some -1). Not: the doorbell graph, which asks the pool for what the device does not hold. 3018void Verifier :: refresh_ar () { 3019if (! all_resident_ || h_res_ == nullptr || g_ == nullptr ) return; 3020const int64_t ne = g_ -> n_expert ; 3021const int32_t * r = h_res_ + lb_ * ne ; 3022const int64_t n = ( le_ < 0 ? g_ -> n_layers : le_ ) * ne - lb_ * ne ; 3023int32_t lo = 0 ; 3024for ( int64_t i = 0 ; i < n ; ++ i ) lo = std:: min ( lo , r [ i ]); 3025const bool off = lo < 0 ; 3026if ( off != ar_off_ ) { 3027ar_off_ = off ; 3028std:: fprintf ( stderr , "strata verify: layers [%lld, %lld) %s\n" , ( long long ) lb_ , ( long long ) ( le_ < 0 ? g_ -> n_layers : le_ ), 3029off ? "have experts out of VRAM (a prompt loan, a shrink or a swap): the doorbell graph runs the windows" 3030: "are 100% VRAM resident again: the zero-doorbell graph" ); 3031} 3032} 3033 3034bool Verifier :: capture ( int T , std:: string & err ) { 3035const auto cap_t0 = std::chrono::steady_clock:: now (); 3036cudaGraphExec_t & exec_t = ar_off_ ? exec_nr_ [ sel_long_ ][ T ] : exec_ [ sel_long_ ][ T ]; 3037if ( exec_t != nullptr ) return true; 3038{ // said before the capture: a process that exits inside it (#1275: Windows, 313 MiB free) leaves this line as the trace 3039size_t free_b = 0 , total_b = 0 ; 3040if ( cudaMemGetInfo ( & free_b , & total_b ) == cudaSuccess ) 3041std:: fprintf ( stderr , "strata verify: capturing the %d-token window (%zu MiB of VRAM free)\n" , T , free_b >> 20 ); 3042else 3043( void ) cudaGetLastError (); 3044} 3045if ( cudaStreamBeginCapture ( cs_ , cudaStreamCaptureModeThreadLocal ) != cudaSuccess ) { 3046err = "verify: begin capture failed" ; 3047return false; 3048} 3049#if !defined( STRATA_USE_HIP ) && !defined( STRATA_HIP_GFX906 ) && !defined( STRATA_GPU_METAL ) 3050prio_forks_ . clear (); 3051prio_tails_ . clear (); 3052#endif 3053std:: string rerr ; 3054const bool ok = record_window ( T , cs_ , rerr ); 3055cudaGraph_t graph = nullptr ; 3056const cudaError_t ce = cudaStreamEndCapture ( cs_ , & graph ); 3057if (! ok ) { 3058if ( graph ) cudaGraphDestroy ( graph ); 3059err = rerr ; 3060return false; 3061} 3062if ( ce != cudaSuccess ) { 3063err = std:: string ( "verify: end capture: " ) + cudaGetErrorString ( ce ); 3064return false; 3065} 3066if ( graph && std:: getenv ( "STRATA_VERIFY_NODES" ) != nullptr ) { // the captured node order (D2H / wait_flag / H2D / kernel) 3067size_t nn = 0 ; 3068if ( cudaGraphGetNodes ( graph , nullptr , & nn ) == cudaSuccess && nn > 0 ) { 3069std:: vector < cudaGraphNode_t > nodes ( nn ); 3070if ( cudaGraphGetNodes ( graph , nodes . data (), & nn ) == cudaSuccess ) { 3071std:: fprintf ( stderr , "capture: %zu graph nodes:\n" , nn ); 3072for ( size_t i = 0 ; i < nn ; ++ i ) { 3073cudaGraphNodeType t = cudaGraphNodeTypeEmpty ; cudaGraphNodeGetType ( nodes [ i ], & t ); 3074if ( t == cudaGraphNodeTypeMemcpy ) { 3075cudaMemcpy3DParms mp {}; 3076const char * k = "?" ; 3077if ( cudaGraphMemcpyNodeGetParams ( nodes [ i ], & mp ) == cudaSuccess ) 3078k = mp . kind == cudaMemcpyHostToDevice ? "H2D" : mp . kind == cudaMemcpyDeviceToHost ? "D2H" : mp . kind == cudaMemcpyDeviceToDevice ? "D2D" : "?" ; 3079std:: fprintf ( stderr , " [%3zu] M %s\n" , i , k ); 3080} else if ( t == cudaGraphNodeTypeKernel ) { 3081cudaKernelNodeParams kp {}; 3082const void * f = nullptr ; 3083if ( cudaGraphKernelNodeGetParams ( nodes [ i ], & kp ) == cudaSuccess ) f = kp . func ; 3084std:: fprintf ( stderr , " [%3zu] K func=%p\n" , i , f ); 3085} else { 3086std:: fprintf ( stderr , " [%3zu] type=%d\n" , i , ( int ) t ); 3087} 3088} 3089} 3090} 3091} 3092#if defined( STRATA_USE_HIP ) // 143-amdk: the same listing on HIP (kernel names by hipKernelNameRefByPtr); STRATA_VERIFY_NODES=2 also lists the first nodes in graph order 3093if (std:: getenv ( "STRATA_VERIFY_NODES" ) != nullptr ) { 3094size_t nn = 0 ; 3095hipGraphGetNodes ( graph , nullptr , & nn ); 3096std:: vector < hipGraphNode_t > nodes ( nn ); 3097hipGraphGetNodes ( graph , nodes . data (), & nn ); 3098std:: map < std:: string , int > kinds ; 3099std:: string seq ; 3100size_t shown = 0 ; 3101for ( hipGraphNode_t nd : nodes ) { 3102hipGraphNodeType ty ; 3103hipGraphNodeGetType ( nd , & ty ); 3104std:: string name = "type" + std:: to_string (( int ) ty ); 3105if ( ty == hipGraphNodeTypeKernel ) { 3106hipKernelNodeParams kp {}; 3107if ( hipGraphKernelNodeGetParams ( nd , & kp ) == hipSuccess && kp . func != nullptr ) { 3108#if defined( _WIN32 ) 3109using Fn_hipKernelNameRefByPtr = const char * ( * )(const void * , hipStream_t ); 3110static auto p_hipKernelNameRefByPtr = reinterpret_cast < Fn_hipKernelNameRefByPtr > ( 3111GetProcAddress ( GetModuleHandleA ( "amdhip64_7.dll" ), "hipKernelNameRefByPtr" )); 3112const char * fn = p_hipKernelNameRefByPtr ? p_hipKernelNameRefByPtr ( kp . func , nullptr ) : nullptr ; 3113#else 3114const char * fn = hipKernelNameRefByPtr ( kp . func , nullptr ); 3115#endif 3116if ( fn != nullptr ) name = fn ; 3117} 3118} else if ( ty == hipGraphNodeTypeMemcpy ) name = "memcpy" ; 3119else if ( ty == hipGraphNodeTypeMemset ) name = "memset" ; 3120++ kinds [ name ]; 3121if (std:: atoi (std:: getenv ( "STRATA_VERIFY_NODES" )) >= 2 && shown ++ < 400 ) seq += "\n " + name . substr ( 0 , 110 ); 3122} 3123std:: vector < std:: pair < int , std:: string >> v ; 3124for ( auto & [ k2 , c ] : kinds ) v . push_back ({ c , k2 }); 3125std:: sort ( v . rbegin (), v . rend ()); 3126std:: fprintf ( stderr , "strata verify: the %d-token window graph has %zu nodes:" , T , nn ); 3127for ( size_t i = 0 ; i < v . size () && i < 80 ; ++ i ) std:: fprintf ( stderr , "\n %4d x %.110s" , v [ i ]. first , v [ i ]. second . c_str ()); 3128std:: fprintf ( stderr , "\n%s\n" , seq . c_str ()); 3129} 3130#endif 3131#if !defined( STRATA_USE_HIP ) && !defined( STRATA_GPU_METAL ) // a CUDA debug listing (node types, kernel names) 3132if (std:: getenv ( "STRATA_VERIFY_NODES" ) != nullptr ) { // what the window graph holds 3133size_t nn = 0 ; 3134cudaGraphGetNodes ( graph , nullptr , & nn ); 3135std:: vector < cudaGraphNode_t > nodes ( nn ); 3136cudaGraphGetNodes ( graph , nodes . data (), & nn ); 3137std:: map < std:: string , int > kinds ; 3138for ( cudaGraphNode_t nd : nodes ) { 3139cudaGraphNodeType ty ; 3140cudaGraphNodeGetType ( nd , & ty ); 3141std:: string name = "type" + std:: to_string (( int ) ty ); 3142if ( ty == cudaGraphNodeTypeKernel ) { 3143cudaKernelNodeParams kp {}; 3144if ( cudaGraphKernelNodeGetParams ( nd , & kp ) == cudaSuccess ) { 3145#if CUDART_VERSION >= 12030 // cudaFuncGetName arrived in CUDA 12.3 3146const char * fn = nullptr ; 3147if ( cudaFuncGetName ( & fn , kp . func ) == cudaSuccess && fn ) name = fn ; 3148#endif 3149} 3150} else if ( ty == cudaGraphNodeTypeMemcpy ) name = "memcpy" ; 3151else if ( ty == cudaGraphNodeTypeMemset ) name = "memset" ; 3152++ kinds [ name ]; 3153} 3154std:: vector < std:: pair < int , std:: string >> v ; 3155for ( auto & [ k2 , c ] : kinds ) v . push_back ({ c , k2 }); 3156std:: sort ( v . rbegin (), v . rend ()); 3157std:: fprintf ( stderr , "strata verify: the %d-token window graph has %zu nodes:" , T , nn ); 3158for ( size_t i = 0 ; i < v . size () && i < 40 ; ++ i ) std:: fprintf ( stderr , " %d x %.60s;" , v [ i ]. first , v [ i ]. second . c_str ()); 3159std:: fprintf ( stderr , "\n" ); 3160#if CUDART_VERSION >= 12030 // the programmatic (PDL) edges: CUDA allows them only from a kernel node to a kernel node 3161size_t ne = 0 ; 3162#if CUDART_VERSION >= 13000 3163cudaGraphGetEdges ( graph , nullptr , nullptr , nullptr , & ne ); 3164#else 3165cudaGraphGetEdges_v2 ( graph , nullptr , nullptr , nullptr , & ne ); 3166#endif 3167std:: vector < cudaGraphNode_t > from ( ne ), to ( ne ); 3168std:: vector < cudaGraphEdgeData > ed ( ne ); 3169#if CUDART_VERSION >= 13000 3170const cudaError_t ge = cudaGraphGetEdges ( graph , from . data (), to . data (), ed . data (), & ne ); 3171#else 3172const cudaError_t ge = cudaGraphGetEdges_v2 ( graph , from . data (), to . data (), ed . data (), & ne ); 3173#endif 3174size_t prog = 0 , bad = 0 ; 3175for ( size_t i = 0 ; ge == cudaSuccess && i < ne ; ++ i ) { 3176if ( ed [ i ]. type != cudaGraphDependencyTypeProgrammatic ) continue; 3177++ prog ; 3178cudaGraphNodeType ta , tb2 ; 3179if ( cudaGraphNodeGetType ( from [ i ], & ta ) != cudaSuccess || cudaGraphNodeGetType ( to [ i ], & tb2 ) != cudaSuccess || 3180ta != cudaGraphNodeTypeKernel || tb2 != cudaGraphNodeTypeKernel ) 3181++ bad ; 3182} 3183if ( ge != cudaSuccess ) cudaGetLastError (); 3184std:: fprintf ( stderr , "strata verify: %zu edges, %zu programmatic (PDL), %zu of them not kernel to kernel%s\n" , ne , 3185prog , bad , ge != cudaSuccess ? " (the edge query failed)" : "" ); 3186#endif 3187} 3188#endif 3189unsigned long long iflags = 0 ; 3190#if !defined( STRATA_USE_HIP ) && !defined( STRATA_HIP_GFX906 ) && !defined( STRATA_GPU_METAL ) 3191if ( graph_prio_on ()) { // STRATA_GRAPH_PRIO: the nodes run at their own (captured or repaired) priorities 3192apply_node_priorities ( graph , T ); 3193iflags = cudaGraphInstantiateFlagUseNodePriority ; 3194} 3195#endif 3196#if defined( STRATA_USE_HIP ) 3197if ( env_on ( "STRATA_LAUNCH_PROBE" )) { // STRIX-TDR: how many nodes (about one AQL packet each) the window graph holds 3198size_t nn = 0 , nk = 0 ; 3199hipGraphGetNodes ( graph , nullptr , & nn ); 3200std:: vector < hipGraphNode_t > nodes ( nn ); 3201hipGraphGetNodes ( graph , nodes . data (), & nn ); 3202for ( hipGraphNode_t nd : nodes ) { 3203hipGraphNodeType ty ; 3204if ( hipGraphNodeGetType ( nd , & ty ) == hipSuccess && ty == hipGraphNodeTypeKernel ) ++ nk ; 3205} 3206std:: fprintf ( stderr , "strata tdr-probe: the %d-token window graph has %zu nodes, %zu of them kernels\n" , T , nn , nk ); 3207} 3208#endif 3209const bool made = instantiate_evicting ( exec_t , graph , {}, "verify: instantiate: " , err , T , iflags ); 3210cudaGraphDestroy ( graph ); 3211if (! made ) return false; 3212const cudaError_t ue = cudaGraphUpload ( exec_t , cs_ ); 3213const cudaError_t us = cudaStreamSynchronize ( cs_ ); 3214std:: fprintf ( stderr , "strata verify: captured the %d-token window (upload %s, sync %s) in %.1f ms\n" , T , 3215cudaGetErrorString ( ue ), cudaGetErrorString ( us ), 3216std::chrono:: duration < double , std:: milli > (std::chrono::steady_clock:: now () - cap_t0 ). count ()); 3217// The upload only warms the graph; the first launch does it otherwise. A failed one (out of memory on a full card) 3218// must not stay pending: the next kernel wrapper's cudaGetLastError would read it and end the engine (#3702). 3219if ( ue != cudaSuccess || us != cudaSuccess ) { 3220( void ) cudaGetLastError (); 3221std:: fprintf ( stderr , "strata verify: the %d-token window's upload was skipped (the first launch does it)\n" , T ); 3222} 3223return true; 3224} 3225 3226bool Verifier :: capture_commit (std:: string & err ) { 3227if ( commit_exec_ != nullptr ) return true; 3228using namespace strata:: kernels ; 3229const ModelGeometry & g = * g_ ; 3230SessionState & ss = * ss_ ; 3231const QsaShapes s = shapes_of ( g ); 3232const int64_t C = g . ssm_conv_channels , HV = g . ssm_v_heads , ID = g . idx_key_dim , MT = max_t_ ; 3233const uint64_t gdn_floats = ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size + 3234( uint64_t ) g . ssm_conv_channels * ( g . ssm_d_conv - 1 ); 3235const int64_t TS = ( s . idx_block - 1 ) * ID ; 3236const int64_t HS = ( int64_t ) NG_HIST * NG_HC_DIM ; 3237if ( cudaStreamBeginCapture ( cs_ , cudaStreamCaptureModeThreadLocal ) != cudaSuccess ) { 3238err = "verify: begin commit capture failed" ; 3239return false; 3240} 3241bool ok = true; 3242try { 3243copy_i32_from_mapped ( commit_ , m_commit_ , 2 + MT , cs_ ); 3244int64_t qsa_index = 0 , gdn_index = 0 ; 3245for ( int64_t l = 0 ; l < lb_ ; ++ l ) ( is_qsa_layer ( g , l ) ? qsa_index : gdn_index ) += 1 ; 3246// engine-latency (STRATA_COMMIT_BATCH, default on; =0 keeps the per-layer loop): every GDN layer's conv history and 3247// state in two launches instead of two per layer (~70 graph nodes fewer; the same arithmetic per layer, bitwise). 3248// The commit runs between a window and the draft round, which on HIP waits for it. 3249#if defined( STRATA_GPU_METAL ) // no batched commit kernels on Metal: the per-layer loop (the Mac engine's gated path) 3250static const bool commit_batch = false; 3251#else 3252static const bool commit_batch = [] { const char * e = std:: getenv ( "STRATA_COMMIT_BATCH" ); return ! e || e [ 0 ] != '0' ; }(); 3253#endif 3254bool gdn_batched = false; 3255if ( commit_batch ) { 3256int64_t n_gdn = 0 ; 3257bool norms_ok = true; // the per-layer loop checks each layer's ssm_norm.weight: keep that check 3258for ( int64_t l = lb_ ; l < le_ && norms_ok ; ++ l ) 3259if (! is_qsa_layer ( g , l )) { 3260++ n_gdn ; 3261norms_ok = need ( LayerView ( * wt_ , l ), "ssm_norm.weight" , err ) != nullptr ; 3262} 3263if (! norms_ok ) ok = false; 3264else if ( n_gdn > 0 ) 3265gdn_batched = gdn_commit_layers ( 3266ss . gdn_state + ( size_t ) ( gdn_index - ss . gdn_ord0 ) * gdn_floats , ( int64_t ) gdn_floats , 3267( int64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size , qkv_L_ + ( size_t ) gdn_index * MT * C , 3268MT * C , h_L_ + ( size_t ) gdn_index * MT * C , MT * C , gate_L_ + ( size_t ) gdn_index * MT * HV , 3269beta_L_ + ( size_t ) gdn_index * MT * HV , MT * HV , ( int ) C , ( int ) g . ssm_k_heads , ( int ) HV , ( int ) MT , 3270( int ) n_gdn , commit_ , cs_ ); 3271} 3272// the QSA layers' tail restore + indexer append, one launch for all of them (one block per layer) 3273bool qsa_batched = false; 3274if ( commit_batch && ok && ! g_no_batch_kv ) { 3275QsaIndexerLayers il ; 3276int nq = 0 ; 3277int64_t mc = -1 ; 3278bool fits = true; 3279for ( int64_t l = lb_ , qi = qsa_index ; l < le_ && fits ; ++ l ) { 3280if (! is_qsa_layer ( g , l )) continue; 3281const WeightRef * wikn = need ( LayerView ( * wt_ , l ), "indexer.k_norm.weight" , err ); 3282if (! wikn ) { ok = false; fits = false; break; } 3283const QsaState & st = ss . qsa_states [ qi ]; 3284if ( nq >= QsaIndexerLayers :: kMax || ( mc >= 0 && st . max_cells != mc )) { fits = false; break; } 3285mc = st . max_cells ; 3286il . gamma [ nq ] = (const float * ) wikn -> data ; 3287il . tail_src [ nq ] = tail_snap_ + ( size_t ) qi * TS ; 3288il . tail [ nq ] = st . idx_tail ; il . dead [ nq ] = st . idx_dead ; il . pooled [ nq ] = st . idx_pooled ; 3289il . block_pos [ nq ] = st . idx_block_pos ; 3290++ nq ; 3291++ qi ; 3292} 3293if ( ok && fits && nq > 0 ) { 3294native_qsa_indexer_append_steps_layers ( idx_raw_L_ + ( size_t ) qsa_index * MT * ID , MT * ID , commit_ + 2 , 1 , 3295( int ) MT , 0 , EPS , il , nq , s , mc , rope_scaling (), cs_ ); 3296qsa_batched = true; 3297} 3298} 3299for ( int64_t l = lb_ ; l < le_ && ok ; ++ l ) { 3300const LayerView v ( * wt_ , l ); 3301if ( is_qsa_layer ( g , l ) && qsa_batched ) { 3302++ qsa_index ; 3303} else if (! is_qsa_layer ( g , l ) && gdn_batched ) { 3304++ gdn_index ; 3305} else if (! is_qsa_layer ( g , l )) { 3306if ( MT > kVerifyMaxT ) { // gdn_step_norm_multi takes kVerifyMaxT tokens; gdn_commit_layers takes more 3307err = "verify commit: windows past " + std:: to_string ( kVerifyMaxT ) + " tokens (--lookup-max-t) need " 3308"the batched GDN commit (unset STRATA_COMMIT_BATCH=0, STRATA_GDN_SPLIT, STRATA_GDN_COMMIT_SPLIT=0)" ; 3309ok = false; 3310break; 3311} 3312const WeightRef * wnm = need ( v , "ssm_norm.weight" , err ); 3313if (! wnm ) { ok = false; break; } 3314float * state = ss . gdn_state + ( size_t ) ( gdn_index - ss . gdn_ord0 ) * gdn_floats ; 3315float * conv = state + ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size ; 3316const float * qkv = qkv_L_ + ( size_t ) gdn_index * MT * C ; 3317gdn_conv_commit ( conv , qkv , ( int ) C , commit_ , cs_ ); 3318gdn_step_norm_multi ( state , h_L_ + ( size_t ) gdn_index * MT * C , ( int ) C , gate_L_ + ( size_t ) gdn_index * MT * HV , 3319beta_L_ + ( size_t ) gdn_index * MT * HV , z_ , (const float * ) wnm -> data , EPS , y_dummy_ , 3320( int ) g . ssm_k_heads , ( int ) HV , ( int ) MT , commit_ , cs_ , 3321( int ) MT ); // S26: t_out_begin = MT - the replay's outputs (y_dummy_) are never read 3322++ gdn_index ; 3323} else { 3324const QsaState & st = ss . qsa_states [ qsa_index ]; 3325const WeightRef * wikn = need ( v , "indexer.k_norm.weight" , err ); 3326if (! wikn ) { ok = false; break; } 3327copy_from_mapped ( st . idx_tail , tail_snap_ + ( size_t ) qsa_index * TS , TS , cs_ ); 3328const QsaIndexerBuffers ib { st . idx_tail , st . idx_dead , st . idx_pooled , st . idx_block_pos }; 3329if (! g_no_batch_kv ) { 3330native_qsa_indexer_append_steps ( idx_raw_L_ + ( size_t ) qsa_index * MT * ID , commit_ + 2 , 1 , ( int ) MT , 0 , 3331(const float * ) wikn -> data , EPS , ib , s , st . max_cells , rope_scaling (), cs_ ); 3332} else { 3333for ( int64_t t = 0 ; t < MT ; ++ t ) 3334native_qsa_indexer_append ( idx_raw_L_ + ( size_t ) ( qsa_index * MT + t ) * ID , commit_ + 2 + t , 0 , 3335(const float * ) wikn -> data , EPS , ib , s , st . max_cells , 3336rope_scaling (), cs_ ); 3337} 3338++ qsa_index ; 3339} 3340} 3341if ( ok && ss . ple . ready () && ple_stage ()) copy_indexed ( ss . ple . hist , hist_snap_ , HS , commit_ + 1 , HS , cs_ ); 3342} catch (const std:: exception & e ) { 3343err = std:: string ( "verify commit: " ) + e . what (); 3344ok = false; 3345} 3346cudaGraph_t graph = nullptr ; 3347const cudaError_t ce = cudaStreamEndCapture ( cs_ , & graph ); 3348if (! ok ) { 3349if ( graph ) cudaGraphDestroy ( graph ); 3350return false; 3351} 3352if ( ce != cudaSuccess ) { 3353if ( graph ) cudaGraphDestroy ( graph ); 3354err = std:: string ( "verify: commit capture: " ) + cudaGetErrorString ( ce ); 3355return false; 3356} 3357// (through the same path as the window graphs: on a full card it frees older batch layouts and retries, and the error 3358// it reports is the instantiate's own) 3359const bool made = instantiate_evicting ( commit_exec_ , graph , {}, "verify: commit instantiate: " , err , 0 ); 3360cudaGraphDestroy ( graph ); 3361return made ; 3362} 3363 3364void Verifier :: stage_inputs ( int T , const int32_t * tokens , int64_t pos0 ) { 3365using namespace strata:: kernels ; 3366const ModelGeometry & g = * g_ ; 3367const QsaShapes s = shapes_of ( g ); 3368int32_t * const pk = h_pos_ + ( size_t ) max_t_ * g . n_head ; 3369int32_t * const pi = pk + ( size_t ) max_t_ * g . n_head_kv ; 3370for ( int t = 0 ; t < T ; ++ t ) { 3371h_tok_ [ t ] = tokens [ t ]; 3372qsa_step_fill ( h_step_ + t * kStepCount , pos0 + t , s ); 3373const int32_t pos_t = ( int32_t ) ( pos0 + t ); 3374for ( int64_t h = 0 ; h < g . n_head ; ++ h ) h_pos_ [ t * g . n_head + h ] = pos_t ; 3375for ( int64_t h = 0 ; h < g . n_head_kv ; ++ h ) pk [ t * g . n_head_kv + h ] = pos_t ; 3376for ( int64_t h = 0 ; h < g . idx_q_heads ; ++ h ) pi [ t * g . idx_q_heads + h ] = pos_t ; 3377} 3378if ( g_trace ) std:: fprintf ( stderr , "K0-STAGE-RESET t=%.3f h_seq=%u\n" , ( double ) std::chrono:: duration_cast < std::chrono:: nanoseconds > (std::chrono::steady_clock:: now (). time_since_epoch ()). count () / 1e6 , * (volatile uint32_t * ) h_seq_ ); 3379* (volatile uint32_t * ) h_seq_ = 0 ; 3380* (volatile uint32_t * ) h_flag_ = 0 ; 3381* (volatile uint32_t * ) h_flagA_ = 0 ; 3382* (volatile uint32_t * ) h_flagB_ = 0 ; 3383if ( h_xlseq_ != nullptr ) * (volatile uint32_t * ) h_xlseq_ = 0 ; // edge0: the D stage's doorbell restarts 3384// the overlapped split: the next stage's graph is launched after this, and must see THIS window's raise 3385if ( hflag_out_h_ != nullptr ) * (volatile uint32_t * ) hflag_out_h_ = 0 ; 3386if ( herr_h_ != nullptr ) * (volatile uint32_t * ) herr_h_ = 0 ; 3387if ( hdrop_h_ != nullptr ) * (volatile uint32_t * ) hdrop_h_ = ( g_test_drop > 0 && windows + 1 == g_test_drop ) ? 1u : 0u ; 3388std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3389strata_store_fence (); 3390last_t_ = T ; 3391if ( rs_on_ && T >= 1 && T <= 16 ) ++ rs_win_ [ T ]; 3392last_pos0_ = pos0 ; 3393for ( int t = 0 ; t < T ; ++ t ) last_tokens_ [ t ] = tokens [ t ]; 3394staged_ = true; 3395} 3396 3397void Verifier :: collect_profile () { 3398cudaMemcpy ( prof_h_ . data (), prof_ , prof_h_ . size () * 8 , cudaMemcpyDeviceToHost ); 3399accumulate_profile ( prof_h_ . data ()); 3400if ( g_trace ) trace_dump ( stderr ); // T-TRI: dump the GPU breadcrumbs (slots 32/33/34) each collect 3401} 3402 3403void Verifier :: accumulate_profile (const unsigned long long * stamps ) { 3404double before [ 2 ][ kProfPer ]; 3405std:: memcpy ( before , prof_sum_ , sizeof before ); 3406accumulate_profile_inner ( stamps ); 3407if ( last_t_ >= 1 && last_t_ <= 16 ) { 3408for ( int k = 0 ; k < 2 ; ++ k ) 3409for ( int i = 0 ; i < kProfPer ; ++ i ) prof_t_sum_ [ last_t_ ][ k ][ i ] += prof_sum_ [ k ][ i ] - before [ k ][ i ]; 3410++ prof_t_win_ [ last_t_ ]; 3411} 3412} 3413 3414void Verifier :: accumulate_profile_inner (const unsigned long long * stamps ) { 3415const ModelGeometry & g = * g_ ; 3416const int64_t L = g . n_layers ; 3417auto at = [ & ]( int64_t l , int i ) { return stamps [( size_t ) ( l * kProfPer + i )]; }; 3418// D8: the derived columns below read stamps the hc-read kernels write themselves or the next 3419// layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns - 3420// which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now 3421// contributes nothing. 3422const auto gap = []( unsigned long long to , unsigned long long from ) { 3423return ( from != 0 && to != 0 && to >= from ) ? ( double ) ( to - from ) : 0.0 ; 3424}; 3425// only this stage's layers [lb_, le_) are ever stamped (a layer split); the head only on the last stage 3426for ( int64_t l = lb_ ; l < le_ ; ++ l ) { 3427const int kind = is_qsa_layer ( g , l ) ? 1 : 0 ; 3428unsigned long long prev = at ( l , 0 ); 3429for ( int i = 1 ; i <= 24 ; ++ i ) { 3430const unsigned long long x = at ( l , i ); 3431if ( x == 0 || x < prev ) continue; 3432prof_sum_ [ kind ][ i ] += ( double ) ( x - prev ); 3433prev = x ; 3434} 3435{ // the FFN-side read split like hc-read0: norm 30, down 31, up 32; what is left of 17 is the router, plan, doorbell 3436const double n1 = gap ( at ( l , 30 ), at ( l , 16 )), d1 = gap ( at ( l , 31 ), at ( l , 30 )), u1 = gap ( at ( l , 32 ), at ( l , 31 )); 3437if ( n1 > 0 && d1 > 0 && u1 > 0 ) { 3438prof_sum_ [ kind ][ 30 ] += n1 ; 3439prof_sum_ [ kind ][ 31 ] += d1 ; 3440prof_sum_ [ kind ][ 32 ] += u1 ; 3441prof_sum_ [ kind ][ 17 ] -= gap ( at ( l , 32 ), at ( l , 16 )); 3442} 3443} 3444if ( l + 1 < le_ ) prof_sum_ [ kind ][ 25 ] += gap ( at ( l + 1 , 0 ), at ( l , 24 )); 3445const double dn = gap ( at ( l , 27 ), at ( l , 0 )), dd = gap ( at ( l , 28 ), at ( l , 27 )), du = gap ( at ( l , 1 ), at ( l , 28 )); 3446if ( dn > 0 && dd > 0 && du > 0 ) { // the split exists: show it split, not twice 3447prof_sum_ [ kind ][ 27 ] += dn ; // hc-read0: norm 3448prof_sum_ [ kind ][ 28 ] += dd ; // down 3449prof_sum_ [ kind ][ 29 ] += du ; // up (through both halves, as before) 3450prof_sum_ [ kind ][ 1 ] -= gap ( at ( l , 1 ), at ( l , 0 )); // (hc-read0 shown split) 3451} 3452} 3453if ( le_ == L ) prof_sum_ [ 0 ][ 26 ] += gap ( at ( L , 1 ), at ( L , 0 )); 3454++ prof_windows_ ; 3455} 3456 3457// 0.1.43 (STRATA_ADAPT_OVERLAP): hold the host until the adaptive tier's copies up to `layer` have landed. The wait 3458// is a spin on an atomic the copy stream's host functions raise (no driver call here); 20 s is the window's own limit. 3459bool Verifier :: adapt_gate_wait ( int32_t layer , std:: string & err ) { 3460const Clock :: time_point t0 = Clock :: now (); 3461uint32_t spins = 0 ; 3462// each tier's counter climbs to the last layer it swaps this round, so an all-layers wait asks for that layer 3463const AdaptGate & ag = * adapt_gate_ ; 3464const int32_t want = std:: min ( layer , ag . last ), want_peer = std:: min ( layer , ag . peer_last ); 3465const bool wait_main = ag . last >= 0 && (( size_t ) layer >= ag . has . size () || ag . has [( size_t ) layer ] != 0 ); 3466const bool wait_peer = ag . peer_last >= 0 && (( size_t ) layer >= ag . peer_has . size () || ag . peer_has [( size_t ) layer ] != 0 ); 3467bool announced = false; // the watchdog's label is set only once the wait really starts: no cost when the copies landed 3468while (( wait_main && ag . reached () < want ) || ( wait_peer && ag . peer_reached () < want_peer )) { 3469if (! announced ) { 3470progress_at ( "verify window: waiting for the adaptive tier's copies of layer" , layer ); 3471announced = true; 3472} 3473strata_cpu_pause (); 3474if (( ++ spins & 1023u ) != 0 ) continue; 3475if ( Clock :: now () - t0 > std::chrono:: seconds ( 20 )) { 3476// the release drains the window's own streams, never the tier's copy stream: say so, and hand out the 3477// gate's words and this window's GPU breadcrumbs (STRATA_VERIFY_TRACE) - the last landed layer is the 3478// exact place the stream stopped, which the released window's error line alone never told (#2188's class) 3479const int32_t reach = adapt_gate_ -> reached (), land = adapt_gate_ -> landed . load (); 3480const int32_t hl = adapt_gate_ -> hland != nullptr ? * adapt_gate_ -> hland : -2 ; 3481if ( g_trace ) trace_ev ( "GATE-TIMEOUT" , -1 , layer , reach ); 3482std:: fprintf ( stderr , "strata verify: the adaptive gate waited %lld ms for layer %d: reached %d " 3483"(atomic %d, copy signal %d) - the tier's copy stream was not drained by the release\n" , 3484( long long ) ms_since ( t0 ), ( int ) layer , ( int ) reach , ( int ) land , ( int ) hl ); 3485if ( g_trace ) trace_dump ( stderr ); 3486err = "verify: the adaptive tier's copies for layer " + std:: to_string ( layer ) + " never landed" + 3487released_note ( release_gpu_waits ( 5000 )) + 3488" (the copy stream itself is not drained: reached " + std:: to_string ( reach ) + " of " + 3489std:: to_string ( layer ) + ", STRATA_VERIFY_TRACE=1 prints where the stream stopped)" ; 3490std:: fflush ( stderr ); 3491return false; 3492} 3493} 3494ms_gate += ms_since ( t0 ); 3495return true; 3496} 3497 3498bool Verifier :: handoff_failed (std:: string & err ) const { 3499if ( herr_h_ == nullptr || * (const volatile uint32_t * ) herr_h_ == 0 ) return false; 3500err = "verify: layer split: the hand-off into layer " + std:: to_string ( lb_ ) + " did not arrive within " + 3501std:: to_string ( g_split_wait_ns / 1000000ull ) + " ms (STRATA_SPLIT_WAIT_MS); the window was not used. " 3502"STRATA_SPLIT_OVERLAP=0 runs the serial order" ; 3503trace_ev ( "HANDOFF-TIMEOUT" , -1 , lb_ , ( int64_t ) ( g_split_wait_ns / 1000000ull )); 3504return true; 3505} 3506 3507bool Verifier :: chain_overlap () const { 3508return next_ != nullptr && hflag_out_h_ != nullptr && hflag_out_d_ != nullptr && hcount_d_ != nullptr && 3509next_ -> hflag_in_h_ == hflag_out_h_ && next_ -> device_ != device_ && ! next_ -> ple_stage (); 3510} 3511 3512bool Verifier :: prelaunch ( int T , const int32_t * tokens , int64_t pos0 , std:: string & err ) { 3513const OnDevice on_device ( device_ ); 3514prelaunched_ = 0 ; 3515sel_long_ = select_long_on () && pos0 + T >= select_long_at () ? 1 : 0 ; // the variant the previous stage captured 3516cudaGraphExec_t exec_t = ar_off_ ? exec_nr_ [ sel_long_ ][ T ] : exec_ [ sel_long_ ][ T ]; // #871: the variant the previous stage refreshed 3517if ( T < 1 || T > max_t_ || exec_t == nullptr ) { err = "verify: prelaunch before the window was captured" ; return false; } 3518if ( released_ . load ()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine" ; return false; } 3519if ( pos0 + T > ss_ -> qsa_states [ ss_ -> qsa_primary ()]. max_cells ) { err = "verify: the window runs past the context" ; return false; } 3520const Clock :: time_point t0 = Clock :: now (); 3521stage_inputs ( T , tokens , pos0 ); 3522if ( trace_h_ != nullptr ) std:: memset ( trace_h_ , 0 , trace_n_ * 8 ); 3523std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3524trace_ev ( "WINDOW-PRE" , -1 , -1 , pos0 * 16 + T ); 3525ms_host += ms_since ( t0 ); 3526if ( h_bal_ != nullptr ) std:: memset ( h_bal_ , 0 , ( size_t ) bal_p_ . size () * 4 * 8 ); // this window's stamps only 3527if ( ar_on () && h_plan_err_ != nullptr ) * (volatile uint32_t * ) h_plan_err_ = 0 ; 3528// 0.1.43: the same gate run() applies before it launches (the adaptive tier's copies land first) 3529if ( adapt_gate_ != nullptr && adapt_gate_ -> active . load (std:: memory_order_acquire ) && ar_on () && 3530! adapt_gate_wait (( int32_t ) g_ -> n_layers , err )) return false; 3531strata::dispatch:: Stats :: get (). graph_launch ( T , ar_on () ? 0 : 1 ); 3532const cudaError_t le = cudaGraphLaunch ( exec_t , cs_ ); 3533trace_ev ( "LAUNCHED" , -1 , -1 , ( int64_t ) le ); 3534if ( le != cudaSuccess ) { err = std:: string ( "verify: launch: " ) + cudaGetErrorString ( le ); return false; } 3535( void ) cudaStreamQuery ( cs_ ); 3536prelaunched_ = T ; 3537return true; 3538} 3539 3540bool Verifier :: run ( int T , const int32_t * tokens , int64_t pos0 , PoolMultiFn pool , void * user , int32_t * out , 3541std:: string & err ) { 3542const bool measure = spec_measure_ ; 3543// Clear this borrow and propagated stage borrows on every exit. 3544struct ProposalBorrow { 3545Verifier * verifier ; 3546bool active ; 3547~ ProposalBorrow () { if ( active ) verifier -> set_spec_q ( nullptr , 0 ); } 3548} proposal_borrow { this , measure }; 3549if ( measure && ( T < 1 || T > strata::kernels:: kVerifyMaxT || 3550spec_nq_ < 0 || spec_nq_ > T || ( spec_nq_ > 0 && spec_q_ == nullptr ))) { 3551err = "verify: proposal row count/pointer is invalid" ; return false; 3552} 3553if ( measure && (! head_sampling_ || sampling_ . greedy || sampling_ . temperature <= 0.0f )) { 3554err = "verify: proposal requires sampled head" ; return false; 3555} 3556#if defined( STRATA_GPU_METAL ) 3557if ( measure ) { err = "verify: proposal unsupported on Metal" ; return false; } 3558( void ) pool ; 3559( void ) user ; 3560{ // a sampled, penalised or biased request: the head rows are sampled on the GPU (metal/kernels/sample.metal), Philox(seed, pos0 + t) as the CUDA head 3561const bool sampled_m = ! sampling_ . greedy && sampling_ . temperature > 0.0f ; 3562if ( head_sampling_ && ( sampled_m || hist_d_ != nullptr || sampling_ . logit_bias != nullptr )) { 3563strata::kernels:: SamplerParams sp_m = sampling_ ; 3564sp_m . counter = ( uint64_t ) pos0 ; 3565strata::metal_engine:: window_set_sampling ( metal_ , & sp_m , hist_d_ , hist_len_ ); 3566} else { 3567strata::metal_engine:: window_set_sampling ( metal_ , nullptr , nullptr , 0 ); 3568} 3569} 3570return strata::metal_engine:: window_run ( metal_ , T , tokens , pos0 , head_sampling_ , out , err ); 3571#endif 3572using namespace strata:: kernels ; 3573const OnDevice on_device ( device_ ); 3574last_batch_ = false; 3575if ( T < 1 || T > max_t_ ) { err = "verify: window size out of range" ; return false; } 3576// a layer split's hand-off buffers hold kVerifyMaxT rows 3577if ( T > kVerifyMaxT && ( next_ != nullptr || lb_ > 0 )) { err = "verify: windows past 8 tokens need one stage" ; return false; } 3578if ( released_ . load ()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine" ; return false; } 3579const ModelGeometry & g = * g_ ; 3580SessionState & ss = * ss_ ; 3581if ( pos0 + T > ss . qsa_states [ ss . qsa_primary ()]. max_cells ) { err = "verify: the window runs past the context" ; return false; } 3582// the overlapped split launched this stage's window already: keep the graph variant (#871) chosen for it then, 3583// or this thread would serve the window as the other variant 3584const bool pre = prelaunched_ == T ; 3585prelaunched_ = 0 ; 3586if (! pre && pre_launch_ && ! pre_launch_ ( cs_ , err )) return false; // (a prelaunched window's was served with the first stage's) 3587if (! pre ) refresh_ar (); 3588// STRATA_SELECT_LONG: the select kernels this window's context pays off with (the same on every stage) 3589sel_long_ = select_long_on () && pos0 + T >= select_long_at () ? 1 : 0 ; 3590if (! capture ( T , err ) || ! capture_commit ( err )) return false; 3591const bool chain = chain_overlap (); 3592if ( chain ) { // capture the next stage's window here, on this thread, so the helper only stages and launches 3593const OnDevice on_next ( next_ -> device_ ); 3594next_ -> refresh_ar (); // #871: the variant its prelaunch and its run() will both use 3595next_ -> sel_long_ = sel_long_ ; 3596if (! next_ -> capture ( T , err ) || ! next_ -> capture_commit ( err )) return false; 3597} 3598VDBG ( "captured; staging\n" ); 3599const Clock :: time_point t0 = Clock :: now (); 3600if (! pre && ! staged_ ) stage_inputs ( T , tokens , pos0 ); 3601staged_ = false; 3602const bool do_ple = ss . ple . ready () && ple_stage (); 3603uint32_t ple_rows [ kVerifyLongT * PLE_N_HEADS ]; 3604if ( do_ple ) { 3605int32_t prev [ 2 ] = { ss . ple_prev [ 0 ], ss . ple_prev [ 1 ]}; 3606for ( int t = 0 ; t < T ; ++ t ) { 3607ngram_rows ( & tokens [ t ], prev , 1 , ss . ple . consts , ple_rows + t * PLE_N_HEADS ); 3608prev [ 0 ] = prev [ 1 ]; 3609prev [ 1 ] = tokens [ t ]; 3610ss . ple . table -> prefetch_rows ( ple_rows + t * PLE_N_HEADS ); 3611} 3612} 3613#if defined( STRATA_VERIFY_HGL ) 3614std:: optional < HostGraphLaunch > launch_o ; // (not set when the previous stage launched this window already) 3615#endif 3616const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall ; // #267 test hook (off: false) 3617bool flag_raised = false; // the PLE flag went up before the launch (early_ple_flag_mode) 3618bool ple_gathered = false; 3619bool & graph_launched = ar_off_ ? launched_nr_ [ sel_long_ ][ T ] : launched_ [ sel_long_ ][ T ]; 3620if (! pre && ar_on () && ! test_stall && ( early_ple_flag_mode () == 1 || ( early_ple_flag_mode () == 2 && ! graph_launched ))) { 3621if ( do_ple ) { 3622const Clock :: time_point tp = Clock :: now (); 3623if (! ss . ple . table -> gather_batch ( ple_rows , ( size_t ) T , h_ple_ , err )) return false; 3624std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3625strata_store_fence (); 3626ms_host += ms_since ( tp ); 3627} 3628* (volatile uint32_t * ) h_flag_ = 1 ; 3629flag_raised = true; 3630} 3631static const bool probe_on = env_on ( "STRATA_LAUNCH_PROBE" ); 3632static std:: atomic < int > probe_count { 0 }; 3633const int probe_idx = probe_on && ! pre ? probe_count . fetch_add ( 1 ) : -1 ; 3634const bool probe_this = probe_idx >= 0 && probe_idx < 12 ; 3635Clock :: time_point probe_t0 = Clock :: now (); 3636// knife-0: with the CPU share's U on the GPU (STRATA_LATENT_U_GPU) the flag means "this group's hq rows are 3637// written", so pre-raising it here would let the graph copy the rows before the pool writes them (a wrong first 3638// token, then a repetition loop). The u_gpu graph waits for the pool's own raise below; only the CPU-U path, 3639// whose consumers read the mapped rows, needs the pre-raise (the staging reset zeroes the flag). 3640static const bool u_gpu_flag = [] { const char * v = std:: getenv ( "STRATA_LATENT_U_GPU" ); return v != nullptr && std:: atoi ( v ) != 0 ; }(); 3641if ( latent_ && ! pre && ! test_stall && ! ar_on () && ! u_gpu_flag ) { 3642if ( do_ple ) { 3643const Clock :: time_point tp = Clock :: now (); 3644if (! ss . ple . table -> gather_batch ( ple_rows , ( size_t ) T , h_ple_ , err )) return false; 3645std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3646strata_store_fence (); 3647ms_host += ms_since ( tp ); 3648ple_gathered = true; 3649} 3650* (volatile uint32_t * ) h_flag_ = 1 ; 3651flag_raised = true; 3652} 3653if (! pre ) { 3654if ( trace_h_ != nullptr ) std:: memset ( trace_h_ , 0 , trace_n_ * 8 ); // #649: this window's breadcrumbs only 3655std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3656trace_ev ( "WINDOW" , -1 , -1 , pos0 * 16 + T ); 3657ms_host += ms_since ( t0 ); 3658VDBG ( "staged; launching\n" ); 3659if ( h_bal_ != nullptr ) std:: memset ( h_bal_ , 0 , ( size_t ) bal_p_ . size () * 4 * 8 ); // this window's stamps only 3660if ( ar_on () && h_plan_err_ != nullptr ) * (volatile uint32_t * ) h_plan_err_ = 0 ; 3661// 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first 3662if ( adapt_gate_ != nullptr && adapt_gate_ -> active . load (std:: memory_order_acquire ) && ar_on () && 3663! adapt_gate_wait (( int32_t ) g . n_layers , err )) return false; 3664#if defined( STRATA_VERIFY_HGL ) 3665// A blocking instrumented launch cannot also serve the graph's CPU doorbells. 3666static const bool threaded_launch = [] { 3667const char * value = std:: getenv ( "STRATA_VERIFY_ASYNC_LAUNCH" ); 3668return value != nullptr && value [ 0 ] == '1' ; 3669}(); 3670strata::dispatch:: Stats :: get (). graph_launch ( T , ar_on () ? 0 : 1 ); 3671// STRATA_LAUNCH_PROBE=1 (diagnostic, the first 12 windows): how long the launch call takes, whether the GPU has rung a layer 3672// before the call returns, and what a call that has not returned looks like after 50 ms ... 10 s (STRIX-TDR). 3673std:: atomic < bool > probe_done {false}; 3674std:: thread probe_th ; 3675if ( probe_this ) { 3676probe_t0 = Clock :: now (); 3677size_t fm = 0 , tm = 0 ; 3678( void ) cudaMemGetInfo ( & fm , & tm ); 3679std:: fprintf ( stderr , "strata tdr-probe: window %d T=%d pos=%lld: t=%.0f ms since start, %.0f MiB free, launching%s\n" , probe_idx , T , 3680( long long ) pos0 , ms_since ( probe_proc_t0 ()), ( double ) fm / 1048576.0 , threaded_launch ? " (helper thread)" : "" ); 3681probe_th = std:: thread ([ this , & probe_done , probe_t0 , probe_idx , T ] { 3682static const double marks [] = { 50 , 250 , 500 , 1000 , 2000 , 3000 , 5000 , 10000 , 30000 }; 3683size_t mi = 0 ; 3684while (! probe_done . load (std:: memory_order_acquire ) && mi < sizeof marks / sizeof marks [ 0 ]) { 3685std::this_thread:: sleep_for (std::chrono:: milliseconds ( 2 )); 3686if ( ms_since ( probe_t0 ) < marks [ mi ]) continue; 3687std:: fprintf ( stderr , 3688"strata tdr-probe: window %d T=%d: the launch call has not returned after %.0f ms; GPU rang %u, flags served %u A %u B %u\n" , 3689probe_idx , T , marks [ mi ], h_seq_ ? * (volatile uint32_t * ) h_seq_ : 0u , h_flag_ ? * (volatile uint32_t * ) h_flag_ : 0u , 3690h_flagA_ ? * (volatile uint32_t * ) h_flagA_ : 0u , h_flagB_ ? * (volatile uint32_t * ) h_flagB_ : 0u ); 3691++ mi ; 3692} 3693}); 3694} 3695launch_o . emplace ( ar_off_ ? exec_nr_ [ sel_long_ ][ T ] : exec_ [ sel_long_ ][ T ], cs_ , device_ , threaded_launch , 3696[ this ] { ( void ) release_gpu_waits ( 5000 ); }); 3697const cudaError_t le = launch_o -> status (); 3698if ( probe_this ) { 3699probe_done . store (true, std:: memory_order_release ); 3700probe_th . join (); 3701std:: fprintf ( stderr , "strata tdr-probe: window %d T=%d: launch call %s in %.2f ms; the GPU had rung %u layer(s) and the host served %u at the return\n" , 3702probe_idx , T , threaded_launch ? "handed to the helper" : "returned" , ms_since ( probe_t0 ), 3703h_seq_ ? * (volatile uint32_t * ) h_seq_ : 0u , h_flag_ ? * (volatile uint32_t * ) h_flag_ : 0u ); 3704} 3705#else 3706strata::dispatch:: Stats :: get (). graph_launch ( T , ar_on () ? 0 : 1 ); 3707const cudaError_t le = cudaGraphLaunch ( ar_off_ ? exec_nr_ [ sel_long_ ][ T ] : exec_ [ sel_long_ ][ T ], cs_ ); 3708#endif 3709trace_ev ( "LAUNCHED" , -1 , -1 , ( int64_t ) le ); 3710graph_launched = true; 3711if ( g_trace ) { cudaError_t q = cudaStreamQuery ( cs_ ); std:: fprintf ( stderr , "K0-LAUNCH-QUERY %s\n" , q == cudaSuccess ? "SUCCESS(idle)" : ( q == cudaErrorNotReady ? "NOTREADY(busy)" : cudaGetErrorString ( q ))); } 3712if ( le != cudaSuccess ) { err = std:: string ( "verify: launch: " ) + cudaGetErrorString ( le ); return false; } 3713#if defined( STRATA_VERIFY_HGL ) 3714( void ) launch_o -> query (); 3715#else 3716( void ) cudaStreamQuery ( cs_ ); 3717#endif 3718VDBG ( "launched\n" ); 3719} 3720// The overlapped split: the next stage's window is staged and launched on a helper thread while this thread 3721// serves this stage's layers; its graph waits on the GPU for this stage's hand-off flag. The guard joins the 3722// helper on every return, and on an early return (an error after the launch) releases the next stage's GPU 3723// waits so no spin kernel outlives the window (#267). 3724struct NextLaunch { 3725Verifier * next = nullptr ; 3726std:: thread th ; 3727bool ok = true; 3728bool handed = false; 3729std:: string err ; 3730bool join (std:: string & e ) { 3731if ( th . joinable ()) th . join (); 3732if (! ok ) e = err ; 3733return ok ; 3734} 3735~ NextLaunch () { 3736if ( th . joinable ()) th . join (); 3737if ( next != nullptr && ! handed ) ( void ) next -> release_gpu_waits ( 5000 ); 3738} 3739} nl ; 3740if ( chain ) { 3741nl . next = next_ ; 3742nl . th = std:: thread ([ & nl , T , tokens , pos0 ] { nl . ok = nl . next -> prelaunch ( T , tokens , pos0 , nl . err ); }); 3743} 3744volatile uint32_t * const seq = h_seq_ ; 3745volatile uint32_t * const flag = h_flag_ ; 3746const int G = groups_ [ T ] > 0 ? groups_ [ T ] : 1 ; 3747const int gtb [ 2 ] = { 0 , ( T + 1 ) / 2 }, gte [ 2 ] = { G == 2 ? ( T + 1 ) / 2 : T , T }; 3748const int64_t steps = ( le_ - lb_ ) * G ; 3749if ( ar_on () && ! test_stall ) { 3750if ( flag_raised ) { 3751// up before the launch (early_ple_flag_mode) 3752} else if ( do_ple ) { 3753const Clock :: time_point tp = Clock :: now (); 3754if (! ss . ple . table -> gather_batch ( ple_rows , ( size_t ) T , h_ple_ , err )) return false; 3755std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3756strata_store_fence (); 3757* flag = 1 ; 3758ms_host += ms_since ( tp ); 3759} else { 3760* flag = 1 ; 3761} 3762} else 3763for ( int64_t k = 0 ; k < steps ; ++ k ) { 3764const int64_t l = lb_ + k / G ; 3765const int grp = ( int ) ( k % G ); 3766const uint32_t want = ( uint32_t ) ( k + 1 ); 3767const Clock :: time_point a = Clock :: now (); 3768auto last_flush = a ; 3769uint32_t spins = 0 ; 3770progress_at ( "verify window: waiting for the GPU to reach layer" , l ); 3771while ( * seq < want ) { 3772strata_cpu_pause (); 3773if (( ++ spins & 1023u ) != 0 ) continue; 3774const auto now = Clock :: now (); 3775if ( now - last_flush > std::chrono:: microseconds ( 2000 )) { 3776last_flush = now ; 3777#if defined( STRATA_VERIFY_HGL ) 3778const cudaError_t q = launch_o ? launch_o -> query () : cudaStreamQuery ( cs_ ); 3779#else 3780const cudaError_t q = cudaStreamQuery ( cs_ ); 3781#endif 3782if ( q != cudaErrorNotReady && * seq < want ) { 3783trace_ev ( "NEVER-RANG" , k , l , ( int64_t ) q ); 3784trace_dump ( stderr ); 3785err = "verify: layer " + std:: to_string ( l ) + " never rang (" + 3786( q == cudaSuccess ? std:: string ( "graph finished" ) : std:: string ( cudaGetErrorString ( q ))) + ")" ; 3787return false; 3788} 3789} 3790if ( now - a > std::chrono:: seconds ( 20 )) { 3791// #267: the caller ends the engine; no spin kernel may outlive it 3792#if defined( STRATA_VERIFY_HGL ) 3793trace_ev ( "TIMEOUT" , k , l , ( int64_t ) ( launch_o ? launch_o -> query () : cudaStreamQuery ( cs_ ))); 3794#else 3795trace_ev ( "TIMEOUT" , k , l , ( int64_t ) cudaStreamQuery ( cs_ )); 3796#endif 3797if ( g_trace ) { 3798diag ( stderr ); // the words and the breadcrumbs before the release ... 3799const bool drained = release_gpu_waits ( 5000 ); 3800trace_dump ( stderr ); // ... and after it: did the GPU move once its waits were raised? 3801err = "verify: timed out at layer " + std:: to_string ( l ) + released_note ( drained ); 3802return false; 3803} 3804err = "verify: timed out at layer " + std:: to_string ( l ) + released_note ( release_gpu_waits ( 5000 )); 3805return false; 3806} 3807} 3808strata_load_fence (); // the layer rang: the GPU's activations are read after it (a no-op on x86) 3809const Clock :: time_point b = Clock :: now (); 3810if ( probe_this && k == 0 ) 3811std:: fprintf ( stderr , "strata tdr-probe: window %d T=%d: the first doorbell (layer %lld) seen %.2f ms after the launch began\n" , probe_idx , T , 3812( long long ) l , ms_since ( probe_t0 )); 3813if ( g_trace ) trace_ev ( "RANG" , k , l , ( int64_t ) std::chrono:: duration_cast < std::chrono:: microseconds > ( b - a ). count ()); 3814VDBG ( "layer %lld rang\n" , ( long long ) l ); 3815if ( adapt_gate_ != nullptr && adapt_gate_ -> active . load (std:: memory_order_acquire ) && l >= 0 && 3816((( size_t ) l < adapt_gate_ -> has . size () && adapt_gate_ -> has [( size_t ) l ] != 0 ) || 3817(( size_t ) l < adapt_gate_ -> peer_has . size () && adapt_gate_ -> peer_has [( size_t ) l ] != 0 )) && 3818! adapt_gate_wait (( int32_t ) l , err )) return false; 3819cur_layer_ = want - 1 ; 3820set_plan_slot ( grp ); 3821const int tb = gtb [ grp ], n = gte [ grp ] - gtb [ grp ]; 3822progress_at ( "verify window: the CPU experts of layer" , l ); 3823if ( remote_opt_ ) remote_opt_ -> begin ( h_w_ + ( size_t ) tb * ss . k , tb , n ); 3824if ( pool != nullptr ) { 3825strata::core:: latent_xl_current () = h_latxlq_ ; 3826strata::core:: latent_xlseq_current () = h_xlseq_ ; 3827strata::core:: latent_act0_current () = m_latact0_ ; 3828pool ( user , h_x_ + ( size_t ) tb * g . n_embd , h_ids_ + ( size_t ) tb * ss . k , n , ss . k , 3829h_ymiss_ + ( size_t ) tb * ss . k * g . n_embd , l ); 3830} 3831if ( remote_opt_ ) remote_opt_ -> end (); 3832VDBG ( "layer %lld served\n" , ( long long ) l ); 3833if ( g_trace ) trace_ev ( * (volatile uint32_t * ) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET" , k , l , 3834( int64_t ) ms_since ( b )); // aux: ms the CPU experts took 3835progress_tick (); 3836std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3837strata_store_fence (); 3838if ( h_bal_ != nullptr ) { // set_pcie_balance: the step's plan, its CPU and its PCIe experts 3839const size_t bi = ( size_t ) (( k / G ) * 2 + grp ); 3840bal_ok_ [ bi ] = * (volatile uint32_t * ) h_flagA_ == want ; 3841bal_nc_ [ bi ] = bal_ok_ [ bi ] ? sink_ . cpu_jobs : 0 ; 3842bal_np_ [ bi ] = bal_ok_ [ bi ] ? sink_ . counts [ 2 ] : 0 ; 3843sink_ . cpu_jobs = 0 ; 3844} 3845if ( * (volatile uint32_t * ) h_flagA_ != want ) { // the pool did not publish a plan: an empty one 3846sink_ . counts [ 0 ] = 0 ; 3847sink_ . counts [ 1 ] = 0 ; 3848sink_ . counts [ 2 ] = 0 ; 3849sink_ . start [ 0 ] = 0 ; 3850sink_ . start2 [ 0 ] = 0 ; 3851std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3852* (volatile uint32_t * ) h_flagA_ = want ; 3853raise_flag_b_ordered ( want ); // behind any copy still queued from an earlier layer 3854} 3855// Layer 1's pre(1, 0) copies h_ple_ -> ple_ after Layer 0's wait_flag_ge(m_flag_, 1). 3856// By collecting PLE here at k == 0 (after publishing flagA/flagB for Layer 0 so the GPU can run 3857// Layer 0's VRAM experts, and before raising *flag = 1), the NVMe PLE reads overlap with both 3858// MtpDrafter::draft and Layer 0's attention + router + expert execution! 3859if ( k == 0 && do_ple && ! ple_gathered ) { 3860const Clock :: time_point tp = Clock :: now (); 3861if (! ss . ple . table -> gather_batch ( ple_rows , ( size_t ) T , h_ple_ , err )) return false; 3862std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3863strata_store_fence (); 3864ms_host += ms_since ( tp ); 3865} 3866if (!( test_stall && k + 1 == steps )) * flag = want ; 3867if ( h_bal_ != nullptr ) bal_p_ [( size_t ) (( k / G ) * 2 + grp )] = ms_since ( b ); 3868ms_wait += std::chrono:: duration < double , std:: milli > ( b - a ). count (); 3869ms_pool += ms_since ( b ); 3870} 3871// (#646 staged the next stage's inputs here; 0.1.39b keeps the layer split's order: each stage stages its own) 3872if ( chain ) { 3873// The overlapped split: no host sync between the stages. The next stage's GPU starts on this stage's flag; 3874// this thread goes straight to serving the next stage's layers, and syncs this stage once the chain is done. 3875if (! nl . join ( err )) return false; 3876nl . handed = true; 3877++ windows ; 3878const bool ok = next_ -> run ( T , tokens , pos0 , pool , next_user_ , out , err ); 3879const OnDevice back ( device_ ); 3880const cudaError_t se = cudaStreamSynchronize ( cs_ ); 3881if ( copy_used_ ) { 3882cudaStreamSynchronize ( copy_ ); 3883copy_used_ = false; 3884} 3885if (! ok ) return false; 3886if ( se != cudaSuccess ) { err = std:: string ( "verify: " ) + cudaGetErrorString ( se ); return false; } 3887if ( handoff_failed ( err )) return false; // a middle stage of three or more: its own hand-in 3888if ( ar_on () && h_plan_err_ != nullptr && * (volatile uint32_t * ) h_plan_err_ != 0 ) { // #871, as below 3889* (volatile uint32_t * ) h_plan_err_ = 0 ; 3890err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)" ; 3891return false; 3892} 3893commit_pending_ = false; 3894if ( prof_on_ && G == 1 ) collect_profile (); 3895return true; 3896} 3897progress_at ( "verify window: waiting for the GPU to finish the window (flags A/B/M raised)" , ( int64_t ) T ); 3898// #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall 3899// watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no 3900// spin kernel outlives the process - the case that left Windows GPUs "lost" until a power cycle. The wait 3901// itself stays a blocking sync: a cudaStreamQuery poll here cost IQ3_S ~3% decode (a core calling the driver 3902// beside the expert workers). 3903#if defined( STRATA_VERIFY_HGL ) 3904const cudaError_t launch_result = launch_o ? launch_o -> finish () : cudaSuccess ; 3905if ( launch_result != cudaSuccess ) { 3906err = std:: string ( "verify: launch: " ) + cudaGetErrorString ( launch_result ); 3907return false; 3908} 3909#endif 3910trace_ev ( "SYNC" , -1 , -1 , 0 ); 3911{ static const bool k0print = std:: getenv ( "STRATA_K0SYNC_PRINT" ) != nullptr ; if ( k0print ) { double tb = ( double ) std::chrono:: duration_cast < std::chrono:: nanoseconds > (std::chrono::steady_clock:: now (). time_since_epoch ()). count () / 1e6 ; std:: fprintf ( stderr , "K0-SYNC-BEFORE %.3f\n" , tb ); } } 3912const cudaError_t se = cudaStreamSynchronize ( cs_ ); 3913{ static const bool k0print = std:: getenv ( "STRATA_K0SYNC_PRINT" ) != nullptr ; if ( k0print ) { double ta = ( double ) std::chrono:: duration_cast < std::chrono:: nanoseconds > (std::chrono::steady_clock:: now (). time_since_epoch ()). count () / 1e6 ; std:: fprintf ( stderr , "K0-SYNC-AFTER %.3f se=%s\n" , ta , cudaGetErrorString ( se )); } } 3914trace_ev ( "SYNCED" , -1 , -1 , ( int64_t ) se ); 3915if ( se != cudaSuccess ) { err = std:: string ( "verify: " ) + cudaGetErrorString ( se ); return false; } 3916if ( handoff_failed ( err )) return false; // a stale hand-off: nothing of this window is used 3917if ( ar_on () && h_plan_err_ != nullptr && * (volatile uint32_t * ) h_plan_err_ != 0 ) { // #871: refresh_ar saw the table whole 3918* (volatile uint32_t * ) h_plan_err_ = 0 ; 3919err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)" ; 3920return false; 3921} 3922commit_pending_ = false; 3923progress_at ( "verify window: waiting for the expert copies" , ( int64_t ) T ); 3924if ( copy_used_ ) { 3925cudaStreamSynchronize ( copy_ ); // no host function of this window may raise flag B in the next one 3926copy_used_ = false; 3927} 3928if ( h_bal_ != nullptr && ! all_resident_ && ! bal_paused_ ) pcie_balance_window ( steps , G ); 3929if ( prof_on_ && G == 1 ) collect_profile (); // the window's GPU stage stamps 3930// ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's 3931// own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to 3932// the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever 3933// the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw. 3934if ( le_ < g . n_layers ) { // a layer split's earlier stage: the hand-off is written (synced above) 3935++ windows ; 3936return next_ == nullptr || next_ -> run ( T , tokens , pos0 , pool , next_user_ , out , err ); 3937} 3938const bool sampled = ! sampling_ . greedy && sampling_ . temperature > 0.0f ; 3939if ( head_sampling_ && ( sampled || hist_d_ != nullptr || sampling_ . logit_bias != nullptr )) { 3940SamplerParams sp = sampling_ ; 3941sp . counter = ( uint64_t ) pos0 ; 3942// STRATA_SPEC_PROB: the drafter's q lists for this window, judged by rejection sampling (spec_prob.hpp) 3943bool judged = false; 3944if ( sampled && ( measure || ( spec_q_ != nullptr && spec_nq_ > 0 && T > 1 )) && T <= kVerifyMaxT ) { 3945if ( d_spec_ == nullptr && 3946cudaMalloc (( void ** ) & d_spec_ , ( size_t ) kVerifyMaxT * ( 1 + strata::core:: kSpecQStride ) * sizeof( int32_t )) != 3947cudaSuccess ) { 3948( void ) cudaGetLastError (); 3949d_spec_ = nullptr ; 3950} 3951if ( d_spec_ != nullptr ) { 3952const int nq = measure ? spec_nq_ : std:: min ( spec_nq_ , T - 1 ); 3953int32_t * d_q = d_spec_ + kVerifyMaxT ; 3954if (( T == 1 || cudaMemcpyAsync ( d_spec_ , tokens + 1 , ( size_t ) ( T - 1 ) * sizeof( int32_t ), cudaMemcpyHostToDevice , cs_ ) == 3955cudaSuccess ) && 3956( nq == 0 || cudaMemcpyAsync ( d_q , spec_q_ , ( size_t ) nq * strata::core:: kSpecQStride * sizeof( int32_t ), 3957cudaMemcpyHostToDevice , cs_ ) == cudaSuccess )) 3958judged = measure 3959? sample_tokens_proposal ( head_logits_ , T , ( int ) n_vocab_ , hist_d_ , hist_len_ , sp , 3960d_spec_ , d_q , nq , m_out_ , cs_ ) 3961: sample_tokens_spec ( head_logits_ , T , ( int ) n_vocab_ , hist_d_ , hist_len_ , sp , 3962d_spec_ , d_q , nq , m_out_ , cs_ ); 3963} 3964} 3965spec_q_ = nullptr ; 3966spec_nq_ = 0 ; 3967if ( measure && ! judged ) { 3968( void ) cudaStreamSynchronize ( cs_ ); 3969err = "verify: proposal sampler unavailable or allocation/copy/launch failed" ; 3970return false; 3971} 3972if ( judged ) ++ spec_windows ; 3973else sample_tokens ( head_logits_ , T , ( int ) n_vocab_ , hist_d_ , hist_len_ , sp , m_out_ , cs_ ); 3974if ( cudaStreamSynchronize ( cs_ ) != cudaSuccess ) { // m_out_ is the mapped h_out_: synced, it is readable 3975err = "verify: the head sampling failed" ; 3976return false; 3977} 3978} 3979if ( measure ) { 3980for ( int t = 0 ; t < T ; ++ t ) 3981if (((volatile int32_t * ) h_out_ )[ t ] == strata::core::proposal:: kProposalSamplerErrorToken ) { 3982err = "verify: invalid proposal candidate or zero NULL residual" ; 3983return false; 3984} 3985} 3986for ( int t = 0 ; t < T ; ++ t ) out [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 3987if ( tap_file_ != nullptr && ! batch_rec_ ) tap_write ( T , tokens , pos0 ); 3988note_nonfinite ( T , nullptr ); 3989// STRATA_LOGITS_DUMP=<path> (debug tap, off by default): the window's logits as the sampler saw them, written 3990// AFTER the window (the stream is synchronised above and the graph capture is over, so a plain copy is legal - 3991// the same place STRATA_DBG_NAN copies from). One record is 3992// {int32 magic, int32 T, int32 n_vocab, int32 record, int64 position}, then T * n_vocab FP32 rows; row 0 is 3993// the window's first position (the last prompt token of a prefill), which is what a KL comparison wants. 3994if (const char * logits_path = std:: getenv ( "STRATA_LOGITS_DUMP" )) { 3995static std:: FILE * lf = std:: fopen ( logits_path , "wb" ); 3996static int32_t lrec = 0 ; 3997if ( lf != nullptr ) { 3998std:: vector < float > h (( size_t ) T * ( size_t ) n_vocab_ ); 3999const cudaError_t le = cudaMemcpy ( h . data (), head_logits_ , h . size () * sizeof( float ), cudaMemcpyDeviceToHost ); 4000if ( le == cudaSuccess ) { 4001const int32_t hdr [ 4 ] = { 0x53474F4C /*"LOGS"*/ , T , ( int32_t ) n_vocab_ , lrec ++ }; 4002const int64_t hpos = pos0 ; 4003std:: fwrite ( hdr , sizeof hdr , 1 , lf ); 4004std:: fwrite ( & hpos , sizeof hpos , 1 , lf ); 4005std:: fwrite ( h . data (), sizeof( float ), h . size (), lf ); 4006std:: fflush ( lf ); 4007} else { 4008static bool said = false; 4009if (! said ) { 4010said = true; 4011std:: fprintf ( stderr , "strata verify: STRATA_LOGITS_DUMP copy failed: %s\n" , cudaGetErrorString ( le )); 4012( void ) cudaGetLastError (); 4013} 4014} 4015} 4016} 4017if (static const bool dbg = std:: getenv ( "STRATA_DBG_NAN" ) != nullptr ; dbg ) { // debug: the first non-finite head 4018static bool reported = false; 4019if (! reported ) { 4020std:: vector < float > h (( size_t ) T * ( size_t ) n_vocab_ ); 4021cudaMemcpy ( h . data (), head_logits_ , h . size () * 4 , cudaMemcpyDeviceToHost ); 4022for ( int t = 0 ; t < T && ! reported ; ++ t ) { 4023int64_t bad = 0 ; 4024for ( int64_t v = 0 ; v < n_vocab_ ; ++ v ) bad += !std:: isfinite ( h [( size_t ) t * n_vocab_ + v ]); 4025if ( bad ) { 4026reported = true; 4027std:: fprintf ( stderr , "strata dbg: verify window at position %lld, row %d: %lld of %lld logits non-finite " 4028"(token out %d)\n" , ( long long ) pos0 , t , ( long long ) bad , ( long long ) n_vocab_ , out [ t ]); 4029} 4030} 4031} 4032} 4033VDBG ( "window done\n" ); 4034++ windows ; 4035progress_at ( "decode" ); 4036progress_beat (); 4037return true; 4038} 4039 4040// set_pcie_balance: each stamped step's times into the model's fits (PcieModel::sample), solved once a window. 4041void Verifier :: pcie_balance_window ( int64_t steps , int G ) { 4042const volatile unsigned long long * st = h_bal_ ; 4043PcieModel & M = * bal_ ; 4044for ( int64_t k = 0 ; k < steps ; ++ k ) { 4045const size_t i = ( size_t ) (( k / G ) * 2 + k % G ); 4046if (! bal_ok_ [ i ]) continue; 4047const unsigned long long ta = st [ 4 * i ], tb = st [ 4 * i + 1 ], tw = st [ 4 * i + 2 ]; 4048if ( ta == 0 || tb < ta || tw < tb || tw - ta > 1000000000ull ) continue; // not stamped in this window 4049M . sample ( bal_nc_ [ i ], bal_np_ [ i ], bal_p_ [ i ], ( double ) ( tw - ta ) * 1e-6 ); 4050} 4051M . solve (); 4052} 4053 4054void Verifier :: set_plan_slot ( int grp ) { 4055const int64_t cap = sink_ . cap ; 4056int32_t * base = h_plan_ + ( size_t ) grp * ( size_t ) plan_i32_ ; 4057const int64_t i32 = 4 + ( cap + 1 ) + cap + cap ; 4058const int64_t ptr_off = ( i32 + 1 ) & ~ 1ll ; 4059sink_ . counts = base ; 4060sink_ . start = base + 4 ; 4061sink_ . dst = sink_ . start + cap + 1 ; 4062sink_ . tok = sink_ . dst + cap ; 4063sink_ . ptr = ( unsigned long long * ) ( base + ptr_off ); 4064sink_ . ptr2 = sink_ . ptr + cap ; 4065sink_ . start2 = base + ptr_off + 4 * cap ; 4066sink_ . dst2 = ( unsigned long long * ) ( base + dst2_off_ ); 4067const int G = last_batch_ ? 1 : ( groups_ [ last_t_ ] > 0 ? groups_ [ last_t_ ] : 1 ); 4068const int64_t per = latent_ ? 4 * kStagingBlobs : ( G == 2 ? kStagingBlobs / 2 : kStagingBlobs ); 4069sink_ . staging = ( unsigned long long ) ( staging_ + ( size_t ) ( grp * per ) * strata::kernels::cpu:: expert_layout (). max_blob ); 4070sink_ . staging_cap = per ; 4071} 4072 4073// Flag B only rises: a host function of an earlier layer may run after a later layer already raised it directly. 4074void Verifier :: raise_flag ( uint32_t * flag , uint32_t value ) { strata::core:: flag_raise_max ( flag , value ); } 4075 4076// Flag B for layer `want - 1`, behind every copy queued on the copy stream (PR #5096, @AlanJager). The counter only 4077// rises and the graph waits for "flag B >= layer + 1", so raising it on the spot for a layer with nothing to copy 4078// releases an earlier layer (or the other token group of a split window) whose uploads are still in flight. 4079void Verifier :: raise_flag_b_ordered ( uint32_t want ) { 4080FlagSet & fs = flag_sets_ [( want - 1 ) % (sizeof flag_sets_ / sizeof flag_sets_ [ 0 ])]; 4081const cudaError_t e = strata::core:: raise_flag_b_ordered ( copy_used_ , copy_ , & fs , h_flagB_ , want ); 4082if ( e != cudaSuccess ) { 4083// The flag was not raised: the consumers must not be released to staging that is still being written. 4084std:: fprintf ( stderr , "strata DMA: ordered flag B completion failed: %s\n" , cudaGetErrorString ( e )); 4085std:: fflush ( stderr ); 4086release_gpu_waits ( 5000 ); 4087std:: abort (); 4088} 4089} 4090 4091// Plan v0.3 P6: the PCIe share by DMA. The copy engine moves the blobs while the CPU computes its own share and the 4092// GPU its VRAM experts; a host function raises flag B when they have landed (the graph waits for it before the PCIe 4093// groups). Staging is split between the two token groups of a split window. 4094void Verifier :: fetch_dma ( void * ctx , const uint8_t * const * src , int n , size_t bytes ) { 4095Verifier * v = ( Verifier * ) ctx ; 4096const uint32_t want = v -> cur_layer_ + 1 ; 4097if ( n <= 0 ) { v -> raise_flag_b_ordered ( want ); return; } // an empty plan stays behind the copies already queued 4098v -> copy_used_ = true; 4099uint8_t * stage = ( uint8_t * ) v -> sink_ . staging ; // this group's half in a split window 4100// STRATA_DMA_BATCH (midhatn's #807, F12): the group's independent uploads as one cudaMemcpyBatchAsync. Mode 0 is 4101// the loop the engine always ran, errors unchecked (it never stops the engine). A batch mode whose uploads 4102// cannot be submitted stops the engine: flag B must not release the consumers to expert weights that were never 4103// copied. 4104const int batch_mode = strata::core:: dma_batch_mode (); 4105if ( batch_mode == 0 ) { 4106for ( int i = 0 ; i < n ; ++ i ) cudaMemcpyAsync ( stage + ( size_t ) i * bytes , src [ i ], bytes , cudaMemcpyHostToDevice , v -> copy_ ); 4107} else { 4108const auto copied = strata::core:: copy_expert_blobs ( stage , src , n , bytes , v -> copy_ , batch_mode ); 4109if ( copied != cudaSuccess ) { 4110std:: fprintf ( stderr , "strata DMA: expert upload failed: %s\n" , cudaGetErrorString ( copied )); 4111std:: fflush ( stderr ); 4112v -> release_gpu_waits ( 5000 ); 4113std:: abort (); 4114} 4115} 4116v -> raise_flag_b_ordered ( want ); // copy_used_ is set: the host function runs after this group's uploads 4117} 4118 4119void Verifier :: publish_plan ( void * ctx ) { 4120Verifier * v = ( Verifier * ) ctx ; 4121strata_store_fence (); 4122* (volatile uint32_t * ) v -> h_flagA_ = v -> cur_layer_ + 1 ; 4123} 4124 4125bool Verifier :: window_logprobs (const int32_t * targets , int T , int64_t pos0 , int32_t extra_id , std:: FILE * out , 4126std:: string & err ) { 4127if ( next_ != nullptr ) return next_ -> window_logprobs ( targets , T , pos0 , extra_id , out , err ); 4128const OnDevice on_device ( device_ ); 4129#if defined( STRATA_GPU_METAL ) 4130// the head logits are the Metal window's (window_copy_logits, row by row) 4131if ( n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr ) { 4132err = "window_logprobs: no head logits for this window" ; 4133return false; 4134} 4135std:: vector < float > h (( size_t ) T * ( size_t ) n_vocab_ ); 4136for ( int t = 0 ; t < T ; ++ t ) 4137if (!strata::metal_engine:: window_copy_logits ( metal_ , t , h . data () + ( size_t ) t * ( size_t ) n_vocab_ )) { 4138err = "window_logprobs: the head logits copy failed" ; 4139return false; 4140} 4141#else 4142if ( head_logits_ == nullptr || n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr ) { 4143err = "window_logprobs: no head logits for this window" ; 4144return false; 4145} 4146// run() synchronized cs_ before returning, so the head of this window is complete 4147std:: vector < float > h (( size_t ) T * ( size_t ) n_vocab_ ); 4148if ( cudaMemcpy ( h . data (), head_logits_ , h . size () * sizeof( float ), cudaMemcpyDeviceToHost ) != cudaSuccess ) { 4149err = "window_logprobs: the head logits copy failed" ; 4150return false; 4151} 4152#endif 4153// STRATA_FORCE_FAULT=<m>:<bias> (test only, off by default, no output): adds <bias> to the logit of every token id divisible by <m> 4154// before the rows are scored, so the token-forcing checker (tools/force_check.py) can be shown to reject a faulty build 4155{ 4156static const std:: pair < int64_t , float > fault = [] { 4157const char * v = std:: getenv ( "STRATA_FORCE_FAULT" ); 4158long long m = 0 ; 4159float b = 0.0f ; 4160if ( v != nullptr && std:: sscanf ( v , "%lld:%f" , & m , & b ) == 2 && m > 0 ) return std:: make_pair (( int64_t ) m , b ); 4161return std:: make_pair (( int64_t ) 0 , 0.0f ); 4162}(); 4163if ( fault . first > 0 ) 4164for ( int t = 0 ; t < T ; ++ t ) 4165for ( int64_t v = 0 ; v < n_vocab_ ; v += fault . first ) h [( size_t ) t * ( size_t ) n_vocab_ + ( size_t ) v ] += fault . second ; 4166} 4167for ( int t = 0 ; t < T ; ++ t ) { 4168const float * row = h . data () + ( size_t ) t * ( size_t ) n_vocab_ ; 4169const int32_t tgt = targets [ t ]; 4170if ( tgt < 0 || ( int64_t ) tgt >= n_vocab_ ) continue; 4171int64_t top = 0 ; 4172for ( int64_t v = 1 ; v < n_vocab_ ; ++ v ) 4173if ( row [ v ] > row [ top ]) top = v ; 4174const double maxv = row [ top ]; 4175const bool has_extra = extra_id >= 0 && ( int64_t ) extra_id < n_vocab_ ; 4176double sum = 0.0 , sum_without = 0.0 ; // the second skips extra_id: no cancellation when it holds ~all mass 4177for ( int64_t v = 0 ; v < n_vocab_ ; ++ v ) { 4178const double e = std:: exp (( double ) row [ v ] - maxv ); 4179sum += e ; 4180if ( v != ( int64_t ) extra_id ) sum_without += e ; 4181} 4182const double lse = maxv + std:: log ( sum ); 4183const double extra = has_extra ? ( double ) row [ extra_id ] - lse : NAN ; 4184const double without = has_extra && tgt != extra_id && sum_without > 0.0 4185? ( double ) row [ tgt ] - ( maxv + std:: log ( sum_without )) : NAN ; 4186std:: fprintf ( out , "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f" , ( long long ) ( pos0 + t ), ( int ) tgt , 4187( double ) row [ tgt ] - lse , ( long long ) top , maxv - lse , ( int ) ( top == ( int64_t ) tgt ), extra , 4188without ); 4189// STRATA_LOGPOS_TOPK=K: the K most likely tokens and their log-probabilities too (`id:logprob`), for a 4190// top-k comparison with another engine on the same tokens (docs/UNSLOTH_Q4.md) 4191static const int topk = [] { 4192const char * v = std:: getenv ( "STRATA_LOGPOS_TOPK" ); 4193return v != nullptr ? std:: max ( 0 , std:: min ( 256 , std:: atoi ( v ))) : 0 ; 4194}(); 4195if ( topk > 0 ) { 4196std:: vector < int32_t > order (( size_t ) n_vocab_ ); 4197for ( int64_t v = 0 ; v < n_vocab_ ; ++ v ) order [( size_t ) v ] = ( int32_t ) v ; 4198std:: partial_sort ( order . begin (), order . begin () + topk , order . end (), 4199[ & ]( int32_t a , int32_t b ) { return row [ a ] > row [ b ]; }); 4200for ( int j = 0 ; j < topk ; ++ j ) 4201std:: fprintf ( out , "\t%d:%.6f" , order [( size_t ) j ], ( double ) row [ order [( size_t ) j ]] - lse ); 4202} 4203std:: fprintf ( out , "\n" ); 4204} 4205std:: fflush ( out ); 4206return true; 4207} 4208 4209namespace { bool g_commit_async = false; } 4210void Verifier :: set_commit_async ( bool on ) { g_commit_async = on && std:: getenv ( "STRATA_COMMIT_SYNC" ) == nullptr ; } 4211 4212bool Verifier :: commit ( int n_keep , std:: string & err ) { 4213#if defined( STRATA_GPU_METAL ) 4214return strata::metal_engine:: window_commit ( metal_ , n_keep , err ); 4215#endif 4216const OnDevice on_device ( device_ ); 4217if ( n_keep < 1 || n_keep > last_t_ ) { err = "verify: commit count out of range" ; return false; } 4218const Clock :: time_point t0 = Clock :: now (); 4219h_commit_ [ 0 ] = n_keep ; 4220h_commit_ [ 1 ] = n_keep - 1 ; 4221for ( int t = 0 ; t < max_t_ ; ++ t ) h_commit_ [ 2 + t ] = t < n_keep ? ( int32_t ) ( last_pos0_ + t ) : -1 ; 4222if ( last_t_ == 1 && ! always_publish_ && one_token_self_commit () && ! g_qfuse ()) { 4223// a one-token window has advanced the state itself (record_window): no commit graph. (Not with STRATA_QFUSE: its windows 4224// do not self-commit, see `self_commit` there - skipping the commit here left the GDN state and the indexer tail one token behind.) 4225} else { 4226std:: atomic_thread_fence (std:: memory_order_seq_cst ); 4227// STRATA_COMMIT_TIMING=1 (measurement only): the commit graph's GPU time, from an event pair around it (read at the 4228// next commit, when the pair has long completed); printed every 300 commits 4229static struct CommitTiming { 4230bool on = false, pending = false; 4231cudaEvent_t b = nullptr , e = nullptr ; 4232double ms = 0 ; 4233int64_t n = 0 ; 4234CommitTiming () { const char * v = std:: getenv ( "STRATA_COMMIT_TIMING" ); on = v != nullptr && v [ 0 ] == '1' ; } 4235} ct ; 4236if ( ct . on && ct . b == nullptr && 4237( cudaEventCreate ( & ct . b ) != cudaSuccess || cudaEventCreate ( & ct . e ) != cudaSuccess )) { ct . on = false; ( void ) cudaGetLastError (); } 4238if ( ct . on && ct . pending ) { 4239float ms = 0 ; 4240if ( cudaEventSynchronize ( ct . e ) == cudaSuccess && cudaEventElapsedTime ( & ms , ct . b , ct . e ) == cudaSuccess ) { ct . ms += ms ; ++ ct . n ; } 4241ct . pending = false; 4242if ( ct . n > 0 && ct . n % 300 == 0 ) 4243std:: fprintf ( stderr , "strata verify: commit graph %.3f ms GPU on average over %lld commits\n" , ct . ms / ( double ) ct . n , 4244( long long ) ct . n ); 4245} 4246if ( ct . on ) cudaEventRecord ( ct . b , cs_ ); 4247const cudaError_t le = cudaGraphLaunch ( commit_exec_ , cs_ ); 4248if ( ct . on ) { cudaEventRecord ( ct . e , cs_ ); ct . pending = true; } 4249if ( le != cudaSuccess ) { err = std:: string ( "verify: commit launch: " ) + cudaGetErrorString ( le ); return false; } 4250// set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own 4251// stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's 4252// results are read, i.e. after this graph has run. Everything else waits on commit_done_ (wait_commit). 4253if (! g_commit_async || next_ != nullptr ) { 4254const cudaError_t se = cudaStreamSynchronize ( cs_ ); 4255if ( se != cudaSuccess ) { err = std:: string ( "verify: commit: " ) + cudaGetErrorString ( se ); return false; } 4256} else { 4257const cudaError_t re = cudaEventRecord ( commit_done_ , cs_ ); 4258if ( re != cudaSuccess ) { err = std:: string ( "verify: commit event: " ) + cudaGetErrorString ( re ); return false; } 4259( void ) cudaStreamQuery ( cs_ ); 4260commit_pending_ = true; 4261} 4262} 4263if ( ple_stage ()) // stages that share one session must advance it once 4264for ( int t = 0 ; t < n_keep ; ++ t ) { 4265ss_ -> ple_prev [ 0 ] = ss_ -> ple_prev [ 1 ]; 4266ss_ -> ple_prev [ 1 ] = last_tokens_ [ t ]; 4267} 4268ms_commit += ms_since ( t0 ); 4269return next_ == nullptr || next_ -> commit ( n_keep , err ); 4270} 4271 4272bool Verifier :: commit_deferred () const { 4273#if defined( STRATA_GPU_METAL ) 4274return false; // the Metal window keeps its own bookkeeping: never dropped 4275#else 4276if ( last_t_ < 1 ) return false; 4277const bool self = last_t_ == 1 && ! always_publish_ && one_token_self_commit () && ! g_qfuse (); // as commit() above 4278return ! self && ( next_ == nullptr || next_ -> commit_deferred ()); 4279#endif 4280} 4281 4282bool Verifier :: wait_commit (std:: string & err ) { 4283#if defined( STRATA_GPU_METAL ) 4284( void ) err ; 4285return true; 4286#endif 4287if ( commit_pending_ ) { 4288const OnDevice on_device ( device_ ); 4289commit_pending_ = false; 4290const cudaError_t se = cudaEventSynchronize ( commit_done_ ); 4291if ( se != cudaSuccess ) { err = std:: string ( "verify: commit: " ) + cudaGetErrorString ( se ); return false; } 4292} 4293return next_ == nullptr || next_ -> wait_commit ( err ); 4294} 4295 4296 4297// ================================ BATCH WINDOWS (see init_slots) ================================ 4298 4299bool Verifier :: init_slots (const std:: vector < SessionState *>& slots , std:: string & err ) { 4300const OnDevice on_device ( device_ ); 4301if ( g_ == nullptr || ss_ == nullptr ) { err = "verify: init_slots before init" ; return false; } 4302if ( slots . empty ()) { 4303err = "verify: init_slots needs at least one session" ; 4304return false; 4305} 4306for ( SessionState * x : slots ) { 4307if ( x == nullptr || x -> layer_lo != ss_ -> layer_lo || x -> layer_hi != ss_ -> layer_hi || 4308x -> max_cells != ss_ -> max_cells || x -> gdn_ord0 != ss_ -> gdn_ord0 || x -> qsa_ord0 != ss_ -> qsa_ord0 ) { 4309err = "verify: a slot's session is not carved like the stage's own (layer range, context)" ; 4310return false; 4311} 4312} 4313#if defined( STRATA_GPU_METAL ) 4314// the Metal window keeps each slot's running state itself (metal/src/engine/window.cpp): none of the CUDA batch buffers 4315slots_ = slots ; 4316slot_sp_ . assign ( slots . size (), sampling_ ); 4317slot_bias_dev_ . assign ( slots . size (), nullptr ); 4318slot_tail_ . assign ( slots . size (), {}); 4319if ( metal_ == nullptr || !strata::metal_engine:: window_init_slots ( metal_ , slots , err )) { 4320if ( err . empty ()) err = "verify: the Metal window is not up" ; 4321return false; 4322} 4323std:: fprintf ( stderr , "strata verify: batch windows of up to %d sequences, run slot by slot in the Metal window\n" , ( int ) slots . size ()); 4324return true; 4325#endif 4326const strata::kernels:: QsaShapes s = shapes_of ( * g_ ); 4327const int64_t S = ( int64_t ) slots . size (), CB = 2 + max_t_ ; 4328const int64_t TS = ( s . idx_block - 1 ) * g_ -> idx_key_dim , nQ = g_ -> n_qsa_layers (); 4329void * d = nullptr ; 4330if (! mapped (( size_t ) ( S * CB * 4 + 16 ), ( void ** ) & h_commitb_ , ( void ** ) & m_commitb_ )) { 4331err = "verify: the batch commit staging failed" ; 4332return false; 4333} 4334const uint64_t a = (( uint64_t ) S * CB * 4 + 255 ) & ~ 255ull ; 4335if ( cudaMalloc ( & d , a + ( uint64_t ) S * std:: max < int64_t > ( nQ , 1 ) * TS * 4 ) != cudaSuccess ) { 4336err = "verify: the batch buffers do not fit" ; 4337return false; 4338} 4339arena_b_ = d ; 4340commitb_ = ( int32_t * ) d ; 4341tail_snap_b_ = ( float * ) (( uint8_t * ) d + a ); 4342slots_ = slots ; 4343slot_sp_ . assign ( slots . size (), sampling_ ); // greedy until set_slot_sampling 4344slot_bias_dev_ . assign ( slots . size (), nullptr ); 4345slot_tail_ . assign ( slots . size (), {}); 4346std:: fprintf ( stderr , "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))%s\n" , ( long long ) S , 4347( long long ) lb_ , ( long long ) le_ , g_batch_self_commit ? ", one-row windows keep their rows" : "" ); 4348return true; 4349} 4350 4351bool Verifier :: capture_batch (const int * rows , int S , int hbase , std:: string & err ) { 4352cudaGraphExec_t & ex = exec_bm_ [ bkey ( rows , S , hbase )]; 4353if ( ex != nullptr ) return true; 4354if ( cudaStreamBeginCapture ( cs_ , cudaStreamCaptureModeThreadLocal ) != cudaSuccess ) { 4355err = "verify: begin batch capture failed" ; 4356return false; 4357} 4358batch_rec_ = true; 4359row_base_ = hbase ; 4360for ( int t = 0 ; t < S ; ++ t ) brow_ [ t ] = rows [ t ]; 4361std:: string rerr ; 4362sel_long_ = 0 ; // batch rows: the one-CTA select 4363const bool ok = record_window ( S , cs_ , rerr ); 4364batch_rec_ = false; 4365row_base_ = 0 ; 4366cudaGraph_t graph = nullptr ; 4367const cudaError_t ce = cudaStreamEndCapture ( cs_ , & graph ); 4368if (! ok || ce != cudaSuccess ) { 4369if ( graph ) cudaGraphDestroy ( graph ); 4370err = ! ok ? rerr : std:: string ( "verify: end batch capture: " ) + cudaGetErrorString ( ce ); 4371return false; 4372} 4373const bool made = instantiate_evicting ( ex , graph , bkey ( rows , S , hbase ), "verify: batch instantiate: " , err ); 4374cudaGraphDestroy ( graph ); 4375if (! made ) return false; 4376if ( cudaGraphUpload ( ex , cs_ ) != cudaSuccess || cudaStreamSynchronize ( cs_ ) != cudaSuccess ) 4377( void ) cudaGetLastError (); // only a warm-up: the first launch uploads it (see capture) 4378std:: string list ; 4379for ( int t = 0 ; t < S ; ++ t ) list += ( t ? "," : "" ) + std:: to_string ( rows [ t ]); 4380std:: fprintf ( stderr , "strata verify: captured the batch window over slots %s\n" , list . c_str ()); 4381return true; 4382} 4383 4384bool Verifier :: capture_commit_batch (const int * rows , int S , int hbase , std:: string & err ) { 4385if ( batch_self_commits ( rows , S )) return true; // the window keeps its rows: no commit graph 4386cudaGraphExec_t & cex = commit_bm_ [ bkey ( rows , S , hbase )]; 4387if ( cex != nullptr ) return true; 4388using namespace strata:: kernels ; 4389const ModelGeometry & g = * g_ ; 4390const QsaShapes s = shapes_of ( g ); 4391const int64_t C = g . ssm_conv_channels , HV = g . ssm_v_heads , ZV = g . ssm_value_dim , ID = g . idx_key_dim , MT = max_t_ ; 4392const int64_t CB = 2 + MT , nQ = g . n_qsa_layers (); 4393const uint64_t gdn_floats = ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size + 4394( uint64_t ) g . ssm_conv_channels * ( g . ssm_d_conv - 1 ); 4395const int64_t TS = ( s . idx_block - 1 ) * ID ; 4396const int64_t HS = ( int64_t ) NG_HIST * NG_HC_DIM ; 4397if ( cudaStreamBeginCapture ( cs_ , cudaStreamCaptureModeThreadLocal ) != cudaSuccess ) { 4398err = "verify: begin batch commit capture failed" ; 4399return false; 4400} 4401bool ok = true; 4402try { 4403for ( int t = 0 ; t < S ; ++ t ) 4404if ( t == 0 || rows [ t ] != rows [ t - 1 ]) 4405copy_i32_from_mapped ( commitb_ + ( size_t ) rows [ t ] * CB , m_commitb_ + ( size_t ) rows [ t ] * CB , CB , cs_ ); 4406int64_t qsa_index = 0 , gdn_index = 0 ; 4407for ( int64_t l = 0 ; l < lb_ ; ++ l ) ( is_qsa_layer ( g , l ) ? qsa_index : gdn_index ) += 1 ; 4408for ( int64_t l = lb_ ; l < le_ && ok ; ++ l ) { 4409const LayerView v ( * wt_ , l ); 4410if (! is_qsa_layer ( g , l )) { 4411const WeightRef * wnm = need ( v , "ssm_norm.weight" , err ); 4412if (! wnm ) { ok = false; break; } 4413// STRATA_BATCH_GDN_GROUPS=1: one-row groups (no --batch-mtp proposals) commit their recurrence 4414// in one launch for all slots; the conv commits stay per slot 4415static const bool gdn_groups_on = [] { 4416const char * v = std:: getenv ( "STRATA_BATCH_GDN_GROUPS" ); 4417return v != nullptr && std:: atoi ( v ) != 0 ; 4418}(); 4419bool one_row = S <= 8 ; 4420for ( int t = 1 ; one_row && t < S ; ++ t ) one_row = rows [ t ] != rows [ t - 1 ]; 4421strata::kernels:: GdnGroups gg ; 4422for ( int t = 0 ; t < S ;) { 4423const int first = t ; 4424while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 4425SessionState & sx = * slots_ [( size_t ) rows [ first ]]; 4426const int32_t * keep = commitb_ + ( size_t ) rows [ first ] * CB ; 4427float * state = sx . gdn_state + ( size_t ) ( gdn_index - sx . gdn_ord0 ) * gdn_floats ; 4428float * conv = state + ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size ; 4429gdn_conv_commit ( conv , qkv_L_ + ( size_t ) gdn_index * MT * C + ( size_t ) first * C , 4430( int ) C , keep , cs_ ); 4431if ( gdn_groups_on && one_row ) { 4432gg . state [ gg . n ] = state ; 4433gg . keep [ gg . n ] = keep ; 4434gg . first [ gg . n ] = first ; 4435gg . ntok [ gg . n ] = 1 ; 4436++ gg . n ; 4437continue; 4438} 4439gdn_step_norm_multi ( state , h_L_ + ( size_t ) gdn_index * MT * C + ( size_t ) first * C , ( int ) C , 4440gate_L_ + ( size_t ) gdn_index * MT * HV + ( size_t ) first * HV , 4441beta_L_ + ( size_t ) gdn_index * MT * HV + ( size_t ) first * HV , 4442z_ + ( size_t ) first * ZV , (const float * ) wnm -> data , EPS , 4443y_dummy_ + ( size_t ) first * ZV , ( int ) g . ssm_k_heads , 4444( int ) HV , t - first , keep , cs_ , 4445t - first > 1 ? t - first : 0 ); // a 1-row group keeps the 0.1.39 kernel 4446} 4447if ( gg . n > 0 ) 4448gdn_step_norm_groups ( gg , h_L_ + ( size_t ) gdn_index * MT * C , ( int ) C , 4449gate_L_ + ( size_t ) gdn_index * MT * HV , beta_L_ + ( size_t ) gdn_index * MT * HV , 4450z_ , (const float * ) wnm -> data , EPS , y_dummy_ , ( int ) g . ssm_k_heads , ( int ) HV , true, 4451cs_ ); 4452++ gdn_index ; 4453} else { 4454const WeightRef * wikn = need ( v , "indexer.k_norm.weight" , err ); 4455if (! wikn ) { ok = false; break; } 4456for ( int t = 0 ; t < S ;) { 4457const int first = t ; 4458while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 4459const QsaState & st = slots_ [( size_t ) rows [ first ]] -> qsa_states [ qsa_index ]; 4460copy_from_mapped ( st . idx_tail , tail_snap_b_ + (( size_t ) rows [ first ] * nQ + qsa_index ) * TS , 4461TS , cs_ ); 4462const QsaIndexerBuffers ib { st . idx_tail , st . idx_dead , st . idx_pooled , st . idx_block_pos }; 4463for ( int u = first ; u < t ; ++ u ) 4464native_qsa_indexer_append ( idx_raw_L_ + ( size_t ) ( qsa_index * MT + u ) * ID , 4465commitb_ + ( size_t ) rows [ first ] * CB + 2 + ( u - first ), 44660 , (const float * ) wikn -> data , EPS , ib , s , st . max_cells , 4467rope_scaling (), cs_ ); 4468} 4469++ qsa_index ; 4470} 4471} 4472if ( ok && ss_ -> ple . ready () && ple_stage ()) 4473for ( int t = 0 ; t < S ;) { 4474const int first = t ; 4475while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 4476copy_indexed ( slots_ [( size_t ) rows [ first ]] -> ple_hist , hist_snap_ + ( size_t ) first * HS , 4477HS , commitb_ + ( size_t ) rows [ first ] * CB + 1 , HS , cs_ ); 4478} 4479} catch (const std:: exception & e ) { 4480err = std:: string ( "verify batch commit: " ) + e . what (); 4481ok = false; 4482} 4483cudaGraph_t graph = nullptr ; 4484const cudaError_t ce = cudaStreamEndCapture ( cs_ , & graph ); 4485if (! ok ) { 4486if ( graph ) cudaGraphDestroy ( graph ); 4487return false; 4488} 4489if ( ce != cudaSuccess ) { 4490if ( graph ) cudaGraphDestroy ( graph ); 4491err = std:: string ( "verify: batch commit capture: " ) + cudaGetErrorString ( ce ); 4492return false; 4493} 4494const bool made = instantiate_evicting ( cex , graph , bkey ( rows , S , hbase ), "verify: batch commit instantiate: " , err ); 4495cudaGraphDestroy ( graph ); 4496return made ; 4497} 4498 4499// ---- STRATA_PIPED_MTP: commits after the verdict (see the header) 4500 4501bool Verifier :: init_deferred_commit ( int rows , std:: string & err ) { 4502const OnDevice on_device ( device_ ); 4503if ( slots_ . empty ()) { err = "verify: init_deferred_commit before init_slots" ; return false; } 4504if ( rows < 1 ) { err = "verify: init_deferred_commit needs at least one row" ; return false; } 4505const ModelGeometry & g = * g_ ; 4506const uint64_t R = ( uint64_t ) rows , C = ( uint64_t ) g . ssm_conv_channels , HV = ( uint64_t ) g . ssm_v_heads ; 4507const uint64_t ID = ( uint64_t ) g . idx_key_dim ; 4508const uint64_t nG = ( uint64_t ) std:: max < int64_t > ( g . n_gdn_layers (), 1 ), nQ = ( uint64_t ) std:: max < int64_t > ( g . n_qsa_layers (), 1 ); 4509const uint64_t HS = ( uint64_t ) strata::kernels:: NG_HIST * strata::kernels:: NG_HC_DIM ; 4510const uint64_t CB = 2 + ( uint64_t ) max_t_ , nS = ( uint64_t ) slots_ . size (); 4511const uint64_t floats [ 6 ] = { nG * R * C , nG * R * C , nG * R * HV , nG * R * HV , nQ * R * ID , R * HS }; 4512uint64_t bytes = ( nS * CB * 4 + 255 ) & ~ 255ull ; 4513for ( uint64_t f : floats ) bytes += ( f * 4 + 255 ) & ~ 255ull ; 4514if ( cudaMalloc ( & dc_arena_ , bytes ) != cudaSuccess ) { 4515err = "verify: the saved commit rows (" + std:: to_string ( bytes >> 20 ) + " MiB) do not fit" ; 4516return false; 4517} 4518uint8_t * p = ( uint8_t * ) dc_arena_ ; 4519commitd_ = ( int32_t * ) p ; 4520p += ( nS * CB * 4 + 255 ) & ~ 255ull ; 4521float ** dst [ 6 ] = { & dc_qkv_ , & dc_h_ , & dc_gate_ , & dc_beta_ , & dc_idx_ , & dc_hist_ }; 4522for ( int i = 0 ; i < 6 ; ++ i ) { 4523* dst [ i ] = ( float * ) p ; 4524p += ( floats [ i ] * 4 + 255 ) & ~ 255ull ; 4525} 4526if (! mapped (( size_t ) ( nS * CB * 4 + 16 ), ( void ** ) & h_commitd_ , ( void ** ) & m_commitd_ )) { 4527err = "verify: the deferred commit staging failed" ; 4528return false; 4529} 4530dc_rows_ = rows ; 4531std:: fprintf ( stderr , "strata verify: pipelined batch windows commit after the verdict (layers [%lld, %lld), %d rows, " 4532"%.1f MiB saved rows)\n" , ( long long ) lb_ , ( long long ) le_ , rows , ( double ) bytes / 1048576.0 ); 4533return true; 4534} 4535 4536bool Verifier :: capture_deferred (const int * rows , int S , int hbase , std:: string & err ) { 4537using namespace strata:: kernels ; 4538const auto key = bkey ( rows , S , hbase ); 4539cudaGraphExec_t & sex = save_bm_ [ key ]; 4540cudaGraphExec_t & cex = dcommit_bm_ [ key ]; 4541if ( sex != nullptr && cex != nullptr ) return true; 4542const ModelGeometry & g = * g_ ; 4543const QsaShapes s = shapes_of ( g ); 4544const int64_t C = g . ssm_conv_channels , HV = g . ssm_v_heads , ZV = g . ssm_value_dim , ID = g . idx_key_dim , MT = max_t_ ; 4545const int64_t R = dc_rows_ , CB = 2 + MT , nQ = g . n_qsa_layers (); 4546const uint64_t gdn_floats = ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size + 4547( uint64_t ) g . ssm_conv_channels * ( g . ssm_d_conv - 1 ); 4548const int64_t TS = ( s . idx_block - 1 ) * ID ; 4549const int64_t HS = ( int64_t ) NG_HIST * NG_HC_DIM ; 4550const bool ple = ss_ -> ple . ready () && ple_stage (); 4551auto layer_index = [ & ]( int64_t & qsa_index , int64_t & gdn_index ) { 4552qsa_index = gdn_index = 0 ; 4553for ( int64_t l = 0 ; l < lb_ ; ++ l ) ( is_qsa_layer ( g , l ) ? qsa_index : gdn_index ) += 1 ; 4554}; 4555auto finish = [ & ]( cudaGraphExec_t & ex , bool ok , const char * what ) { 4556cudaGraph_t graph = nullptr ; 4557const cudaError_t ce = cudaStreamEndCapture ( cs_ , & graph ); 4558if (! ok || ce != cudaSuccess ) { 4559if ( graph ) cudaGraphDestroy ( graph ); 4560if ( ok ) err = std:: string ( what ) + cudaGetErrorString ( ce ); 4561return false; 4562} 4563const bool made = instantiate_evicting ( ex , graph , key , what , err ); 4564cudaGraphDestroy ( graph ); 4565return made ; 4566}; 4567// the save: the window's rows [0, S) of the scratch the commit replays -> the group's saved rows [hbase, +S) 4568if ( sex == nullptr ) { 4569if ( cudaStreamBeginCapture ( cs_ , cudaStreamCaptureModeThreadLocal ) != cudaSuccess ) { 4570err = "verify: begin save capture failed" ; 4571return false; 4572} 4573bool ok = true; 4574int64_t qsa_index = 0 , gdn_index = 0 ; 4575layer_index ( qsa_index , gdn_index ); 4576auto copy = [ & ]( float * dst , const float * src , int64_t n ) { 4577ok = ok && cudaMemcpyAsync ( dst , src , ( size_t ) n * sizeof( float ), cudaMemcpyDeviceToDevice , cs_ ) == cudaSuccess ; 4578}; 4579for ( int64_t l = lb_ ; l < le_ ; ++ l ) { 4580if (! is_qsa_layer ( g , l )) { 4581copy ( dc_qkv_ + ( size_t ) ( gdn_index * R + hbase ) * C , qkv_L_ + ( size_t ) gdn_index * MT * C , S * C ); 4582copy ( dc_h_ + ( size_t ) ( gdn_index * R + hbase ) * C , h_L_ + ( size_t ) gdn_index * MT * C , S * C ); 4583copy ( dc_gate_ + ( size_t ) ( gdn_index * R + hbase ) * HV , gate_L_ + ( size_t ) gdn_index * MT * HV , S * HV ); 4584copy ( dc_beta_ + ( size_t ) ( gdn_index * R + hbase ) * HV , beta_L_ + ( size_t ) gdn_index * MT * HV , S * HV ); 4585++ gdn_index ; 4586} else { 4587copy ( dc_idx_ + ( size_t ) ( qsa_index * R + hbase ) * ID , idx_raw_L_ + ( size_t ) qsa_index * MT * ID , S * ID ); 4588++ qsa_index ; 4589} 4590} 4591if ( ple ) copy ( dc_hist_ + ( size_t ) hbase * HS , hist_snap_ , S * HS ); 4592if (! finish ( sex , ok , "verify: save capture: " )) { 4593if ( ok && err . empty ()) err = "verify: save capture failed" ; 4594return false; 4595} 4596} 4597// the commit: as capture_commit_batch, replaying the saved rows; the accepted prefixes come from commitd_ 4598if ( cex == nullptr ) { 4599if ( cudaStreamBeginCapture ( cs_ , cudaStreamCaptureModeThreadLocal ) != cudaSuccess ) { 4600err = "verify: begin deferred commit capture failed" ; 4601return false; 4602} 4603bool ok = true; 4604try { 4605for ( int t = 0 ; t < S ; ++ t ) 4606if ( t == 0 || rows [ t ] != rows [ t - 1 ]) 4607copy_i32_from_mapped ( commitd_ + ( size_t ) rows [ t ] * CB , m_commitd_ + ( size_t ) rows [ t ] * CB , CB , cs_ ); 4608int64_t qsa_index = 0 , gdn_index = 0 ; 4609layer_index ( qsa_index , gdn_index ); 4610for ( int64_t l = lb_ ; l < le_ && ok ; ++ l ) { 4611const LayerView v ( * wt_ , l ); 4612if (! is_qsa_layer ( g , l )) { 4613const WeightRef * wnm = need ( v , "ssm_norm.weight" , err ); 4614if (! wnm ) { ok = false; break; } 4615for ( int t = 0 ; t < S ;) { 4616const int first = t ; 4617while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 4618SessionState & sx = * slots_ [( size_t ) rows [ first ]]; 4619const int32_t * keep = commitd_ + ( size_t ) rows [ first ] * CB ; 4620float * state = sx . gdn_state + ( size_t ) ( gdn_index - sx . gdn_ord0 ) * gdn_floats ; 4621float * conv = state + ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size ; 4622const int64_t row = gdn_index * R + hbase + first ; 4623gdn_conv_commit ( conv , dc_qkv_ + ( size_t ) row * C , ( int ) C , keep , cs_ ); 4624// z only feeds the norm's output, which the commit discards (y_dummy_): the window scratch will do 4625gdn_step_norm_multi ( state , dc_h_ + ( size_t ) row * C , ( int ) C , dc_gate_ + ( size_t ) row * HV , 4626dc_beta_ + ( size_t ) row * HV , z_ + ( size_t ) first * ZV , 4627(const float * ) wnm -> data , EPS , y_dummy_ + ( size_t ) first * ZV , 4628( int ) g . ssm_k_heads , ( int ) HV , t - first , keep , cs_ , 4629t - first > 1 ? t - first : 0 ); 4630} 4631++ gdn_index ; 4632} else { 4633const WeightRef * wikn = need ( v , "indexer.k_norm.weight" , err ); 4634if (! wikn ) { ok = false; break; } 4635for ( int t = 0 ; t < S ;) { 4636const int first = t ; 4637while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 4638const QsaState & st = slots_ [( size_t ) rows [ first ]] -> qsa_states [ qsa_index ]; 4639copy_from_mapped ( st . idx_tail , tail_snap_b_ + (( size_t ) rows [ first ] * nQ + qsa_index ) * TS , TS , cs_ ); 4640const QsaIndexerBuffers ib { st . idx_tail , st . idx_dead , st . idx_pooled , st . idx_block_pos }; 4641for ( int u = first ; u < t ; ++ u ) 4642native_qsa_indexer_append ( dc_idx_ + ( size_t ) ( qsa_index * R + hbase + u ) * ID , 4643commitd_ + ( size_t ) rows [ first ] * CB + 2 + ( u - first ), 0 , 4644(const float * ) wikn -> data , EPS , ib , s , st . max_cells , 4645rope_scaling (), cs_ ); 4646} 4647++ qsa_index ; 4648} 4649} 4650if ( ok && ple ) 4651for ( int t = 0 ; t < S ;) { 4652const int first = t ; 4653while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 4654copy_indexed ( slots_ [( size_t ) rows [ first ]] -> ple_hist , dc_hist_ + ( size_t ) ( hbase + first ) * HS , HS , 4655commitd_ + ( size_t ) rows [ first ] * CB + 1 , HS , cs_ ); 4656} 4657} catch (const std:: exception & e ) { 4658err = std:: string ( "verify deferred commit: " ) + e . what (); 4659ok = false; 4660} 4661if (! finish ( cex , ok , "verify: deferred commit capture: " )) { 4662if ( ok && err . empty ()) err = "verify: deferred commit capture failed" ; 4663return false; 4664} 4665} 4666return true; 4667} 4668 4669bool Verifier :: batch_launch_rows (const int * rows , int S , int hbase , const int32_t * tokens , const int64_t * pos , 4670std:: string & err ) { 4671const OnDevice on_device ( device_ ); 4672if ( dc_rows_ < 1 ) { err = "verify: batch_launch_rows without init_deferred_commit" ; return false; } 4673if ( b_running_ ) { err = "verify: batch_launch_rows while this stage is busy" ; return false; } 4674if ( S < 1 || hbase < 0 || hbase + S > dc_rows_ ) { err = "verify: a pipelined window outside the saved rows" ; return false; } 4675if ( pre_launch_ && ! pre_launch_ ( cs_ , err )) return false; 4676staging_deferred_ = true; 4677const bool staged = stage_batch ( rows , S , hbase , tokens , pos , err ); 4678staging_deferred_ = false; 4679if (! staged || ! capture_deferred ( rows , S , hbase , err )) return false; 4680const auto key = bkey ( rows , S , hbase ); 4681cudaError_t le = cudaGraphLaunch ( exec_bm_ [ key ], cs_ ); 4682if ( le == cudaSuccess ) le = cudaGraphLaunch ( save_bm_ [ key ], cs_ ); // the rows the commit replays, kept for it 4683if ( le != cudaSuccess ) { err = std:: string ( "verify: batch launch: " ) + cudaGetErrorString ( le ); return false; } 4684( void ) cudaStreamQuery ( cs_ ); 4685b_k_ = 0 ; 4686b_steps_ = le_ - lb_ ; 4687ring_now (); 4688b_running_ . store (true, std:: memory_order_release ); // last: an external server reads the rest after it 4689return true; 4690} 4691 4692bool Verifier :: batch_commit_rows (const int * rows , int S , int hbase , const int * keep , const int32_t * tokens , 4693const int64_t * pos , std:: string & err ) { 4694const OnDevice on_device ( device_ ); 4695const auto it = dcommit_bm_ . find ( bkey ( rows , S , hbase )); 4696if ( it == dcommit_bm_ . end () || it -> second == nullptr ) { err = "verify: a deferred commit without its window" ; return false; } 4697const int64_t CB = 2 + max_t_ ; 4698// Each slot's accepted prefix. The graph reads it from mapped memory when it runs; this slot's entry is written 4699// again only at its next verdict, which comes after its next window has passed this stage - behind this commit. 4700for ( int t = 0 ; t < S ;) { 4701const int first = t ; 4702while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 4703const int n = keep [ rows [ first ]]; 4704if ( n < 1 || n > t - first ) { err = "verify: accepted prefix is outside its slot group" ; return false; } 4705int32_t * c = h_commitd_ + ( size_t ) rows [ first ] * CB ; 4706c [ 0 ] = n ; 4707c [ 1 ] = n - 1 ; 4708for ( int64_t j = 0 ; j < max_t_ ; ++ j ) c [ 2 + j ] = j < n ? ( int32_t ) pos [ first + j ] : -1 ; 4709} 4710std:: atomic_thread_fence (std:: memory_order_seq_cst ); 4711const cudaError_t le = cudaGraphLaunch ( it -> second , cs_ ); 4712if ( le != cudaSuccess ) { err = std:: string ( "verify: deferred commit launch: " ) + cudaGetErrorString ( le ); return false; } 4713( void ) cudaStreamQuery ( cs_ ); 4714if ( ple_stage ()) // the host's side of the commit (the hash's last two tokens), the accepted rows only 4715for ( int t = 0 ; t < S ;) { 4716const int first = t ; 4717while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 4718SessionState & sx = * slots_ [( size_t ) rows [ first ]]; 4719for ( int u = first ; u < first + keep [ rows [ first ]]; ++ u ) { 4720sx . ple_prev [ 0 ] = sx . ple_prev [ 1 ]; 4721sx . ple_prev [ 1 ] = tokens [ u ]; 4722} 4723} 4724return true; 4725} 4726 4727bool Verifier :: evict_batch_graph (const std:: vector < int >& keep , bool & evicted , std:: string & err ) { 4728evicted = false; 4729auto old = exec_bm_ . end (); 4730uint64_t oldest = UINT64_MAX ; 4731for ( auto it = exec_bm_ . begin (); it != exec_bm_ . end (); ++ it ) { 4732if ( it -> first == keep ) continue; 4733const auto u = bm_used_ . find ( it -> first ); 4734const uint64_t t = u == bm_used_ . end () ? 0 : u -> second ; 4735if ( t < oldest ) { oldest = t ; old = it ; } 4736} 4737if ( old == exec_bm_ . end ()) return true; 4738if ( cudaStreamSynchronize ( cs_ ) != cudaSuccess ) { 4739err = "verify: synchronizing before batch graph eviction failed" ; 4740return false; 4741} 4742const auto old_key = old -> first ; 4743if ( old -> second ) cudaGraphExecDestroy ( old -> second ); 4744exec_bm_ . erase ( old ); 4745bm_used_ . erase ( old_key ); 4746auto commit_old = commit_bm_ . find ( old_key ); 4747if ( commit_old != commit_bm_ . end ()) { 4748if ( commit_old -> second ) cudaGraphExecDestroy ( commit_old -> second ); 4749commit_bm_ . erase ( commit_old ); 4750} 4751evicted = true; 4752return true; 4753} 4754 4755bool Verifier :: evict_window_graph ( int keep_t , bool & evicted , std:: string & err ) { 4756evicted = false; 4757if ( no_window_eviction_ || keep_t < 1 ) return true; 4758bool have [strata::kernels:: kWindowMaxT + 1 ] = {}; 4759const int top = std:: min < int > ( max_t_ , strata::kernels:: kWindowMaxT ); 4760for ( int t = 1 ; t <= top ; ++ t ) have [ t ] = ( ar_off_ ? exec_nr_ [ sel_long_ ][ t ] : exec_ [ sel_long_ ][ t ]) != nullptr ; 4761const int victim = strata::core:: pick_window_victim ( have , top , keep_t , prelaunched_ ); 4762if ( victim == 0 ) return true; 4763if ( cudaStreamSynchronize ( cs_ ) != cudaSuccess ) { 4764err = "verify: synchronizing before window graph eviction failed" ; 4765return false; 4766} 4767cudaGraphExec_t & e = ar_off_ ? exec_nr_ [ sel_long_ ][ victim ] : exec_ [ sel_long_ ][ victim ]; 4768cudaGraphExecDestroy ( e ); 4769e = nullptr ; 4770( ar_off_ ? launched_nr_ : launched_ )[ sel_long_ ][ victim ] = false; // the next graph of that size is a cold first launch again 4771evicted = true; 4772return true; 4773} 4774 4775// STRATA_GRAPH_PRIO: the capture-time notes. A fork note keeps cs's current tail (the node the branch's first kernel 4776// will depend on); a tail note keeps a priority stream's current tail and the priority its nodes should run at 4777// (1 = the device's highest, -1 = its lowest). No-ops with the switch off, outside a capture, and on HIP / Metal. 4778void Verifier :: note_prio_fork ( cudaStream_t from ) { 4779#if !defined( STRATA_USE_HIP ) && !defined( STRATA_HIP_GFX906 ) && !defined( STRATA_GPU_METAL ) 4780if (! graph_prio_on ()) return; 4781cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone ; 4782const cudaGraphNode_t * deps = nullptr ; 4783size_t nd = 0 ; 4784if ( prio_capture_deps ( from , & st , & deps , & nd ) != cudaSuccess || st != cudaStreamCaptureStatusActive ) { 4785( void ) cudaGetLastError (); 4786return; 4787} 4788for ( size_t i = 0 ; i < nd ; ++ i ) prio_forks_ . push_back ( deps [ i ]); 4789#else 4790( void ) from ; 4791#endif 4792} 4793 4794void Verifier :: note_prio_tail ( cudaStream_t on , int prio ) { 4795#if !defined( STRATA_USE_HIP ) && !defined( STRATA_HIP_GFX906 ) && !defined( STRATA_GPU_METAL ) 4796if (! graph_prio_on ()) return; 4797cudaStreamCaptureStatus st = cudaStreamCaptureStatusNone ; 4798const cudaGraphNode_t * deps = nullptr ; 4799size_t nd = 0 ; 4800if ( prio_capture_deps ( on , & st , & deps , & nd ) != cudaSuccess || st != cudaStreamCaptureStatusActive ) { 4801( void ) cudaGetLastError (); 4802return; 4803} 4804for ( size_t i = 0 ; i < nd ; ++ i ) prio_tails_ . push_back ({ deps [ i ], prio }); 4805#else 4806( void ) on ; ( void ) prio ; 4807#endif 4808} 4809 4810// STRATA_GRAPH_PRIO: what priorities the captured kernel nodes carry (a histogram, logged once per window graph). If the 4811// capture copied none from the streams (design 1's R1: some drivers read back 0 everywhere), each priority stream's 4812// nodes are found by walking its noted tails back to the noted forks and the attribute is set per node. 4813void Verifier :: apply_node_priorities ( cudaGraph_t graph , int T ) { 4814#if !defined( STRATA_USE_HIP ) && !defined( STRATA_HIP_GFX906 ) && !defined( STRATA_GPU_METAL ) 4815int lo = 0 , hi = 0 ; 4816if ( cudaDeviceGetStreamPriorityRange ( & lo , & hi ) != cudaSuccess ) { ( void ) cudaGetLastError (); return; } 4817auto histogram = [ & ](std:: map < int , int >& h ) { 4818size_t nn = 0 ; 4819cudaGraphGetNodes ( graph , nullptr , & nn ); 4820std:: vector < cudaGraphNode_t > nodes ( nn ); 4821cudaGraphGetNodes ( graph , nodes . data (), & nn ); 4822h . clear (); 4823for ( cudaGraphNode_t nd : nodes ) { 4824cudaGraphNodeType ty ; 4825if ( cudaGraphNodeGetType ( nd , & ty ) != cudaSuccess || ty != cudaGraphNodeTypeKernel ) continue; 4826cudaKernelNodeAttrValue v {}; 4827if ( cudaGraphKernelNodeGetAttribute ( nd , cudaKernelNodeAttributePriority , & v ) == cudaSuccess ) ++ h [ v . priority ]; 4828else { ( void ) cudaGetLastError (); ++ h [ 999 ]; } 4829} 4830}; 4831std:: map < int , int > h ; 4832histogram ( h ); 4833bool captured = false; 4834for ( auto & [ p , c ] : h ) captured = captured || ( p != 0 && p != 999 && c > 0 ); 4835int repaired = 0 , walked_forks = ( int ) prio_forks_ . size (), walked_tails = ( int ) prio_tails_ . size (); 4836if (! captured && ! prio_tails_ . empty ()) { // the fallback: per node from the capture-time notes 4837std:: set < cudaGraphNode_t > stop ( prio_forks_ . begin (), prio_forks_ . end ()), seen ; 4838for ( auto & [ tail , pr ] : prio_tails_ ) { 4839std:: vector < cudaGraphNode_t > stack { tail }; 4840while (! stack . empty ()) { 4841cudaGraphNode_t nd = stack . back (); 4842stack . pop_back (); 4843if ( stop . count ( nd ) || ! seen . insert ( nd ). second ) continue; 4844cudaGraphNodeType ty ; 4845if ( cudaGraphNodeGetType ( nd , & ty ) == cudaSuccess && ty == cudaGraphNodeTypeKernel ) { 4846cudaKernelNodeAttrValue v {}; 4847v . priority = pr > 0 ? hi : lo ; 4848if ( cudaGraphKernelNodeSetAttribute ( nd , cudaKernelNodeAttributePriority , & v ) == cudaSuccess ) ++ repaired ; 4849else ( void ) cudaGetLastError (); 4850} 4851size_t nd_n = 0 ; 4852prio_node_deps ( nd , nullptr , & nd_n ); 4853std:: vector < cudaGraphNode_t > deps ( nd_n ); 4854if ( nd_n > 0 && prio_node_deps ( nd , deps . data (), & nd_n ) == cudaSuccess ) 4855for ( size_t i = 0 ; i < nd_n ; ++ i ) stack . push_back ( deps [ i ]); 4856else ( void ) cudaGetLastError (); 4857} 4858} 4859histogram ( h ); 4860} 4861std:: string s ; 4862for ( auto & [ p , c ] : h ) s += " " + std:: to_string ( c ) + " x prio " + ( p == 999 ? std:: string ( "?" ) : std:: to_string ( p )) + ";" ; 4863std:: fprintf ( stderr , "strata verify: the %d-token window's kernel node priorities (range %d..%d):%s %s (%d forks, %d tails noted%s)\n" , 4864T , lo , hi , s . c_str (), captured ? "captured from the streams" : "NOT captured from the streams" , 4865walked_forks , walked_tails , repaired > 0 ? ( ", " + std:: to_string ( repaired ) + " nodes set from the notes" ). c_str () : "" ); 4866#else 4867( void ) graph ; ( void ) T ; 4868#endif 4869} 4870 4871bool Verifier :: instantiate_evicting ( cudaGraphExec_t & ex , cudaGraph_t graph , const std:: vector < int >& key , 4872const char * what , std:: string & err , int keep_t , unsigned long long flags ) { 4873// #997: every layout of active slots keeps its own graph pair (20-30 MiB each on an L40S), and with an expert cache 4874// sized to the reserve the next window graph - a batch layout or a one-request window captured on first use - can 4875// find no VRAM left: free the least recently used layouts until it fits (they are captured again when needed) 4876// (into a local: what a failed instantiate leaves in the output is not specified, and `ex` is a member that 4877// capture() reads as "captured" when it is not null) 4878capture_oom_ = false; 4879cudaGraphExec_t got = nullptr ; 4880cudaError_t ie = cudaGraphInstantiate ( & got , graph , flags ); 4881int freed = 0 ; 4882for ( bool evicted = true; ie == cudaErrorMemoryAllocation && evicted ;) { 4883( void ) cudaGetLastError (); 4884if (! evict_batch_graph ( key , evicted , err )) return false; 4885if ( evicted ) { 4886++ freed ; 4887ie = cudaGraphInstantiate ( & got , graph , flags ); 4888} 4889} 4890if ( freed > 0 ) 4891std:: fprintf ( stderr , "strata verify: no VRAM for a new window graph: freed the graphs of %d older batch slot " 4892"layouts, %zu kept (a larger --vram-reserve-mib keeps more)\n" , freed , exec_bm_ . size ()); 4893// #3702: a single-request window with nothing of a batch left to free: free the graphs of other window sizes 4894int freed_sizes = 0 ; 4895for ( bool evicted = true; ie == cudaErrorMemoryAllocation && evicted && keep_t > 0 ;) { 4896( void ) cudaGetLastError (); 4897if (! evict_window_graph ( keep_t , evicted , err )) return false; 4898if ( evicted ) { 4899++ freed_sizes ; 4900ie = cudaGraphInstantiate ( & got , graph , flags ); 4901} 4902} 4903if ( freed_sizes > 0 ) 4904std:: fprintf ( stderr , "strata verify: no VRAM for the %d-token window graph: freed the graphs of %d other window " 4905"sizes (they are captured again when used; a larger --vram-reserve-mib or " 4906"--vram-reserve-later-mib keeps them)\n" , keep_t , freed_sizes ); 4907if ( ie != cudaSuccess ) { 4908capture_oom_ = ie == cudaErrorMemoryAllocation ; 4909if ( capture_oom_ ) ( void ) cudaGetLastError (); 4910got = nullptr ; 4911err = std:: string ( what ) + cudaGetErrorString ( ie ); 4912return false; 4913} 4914ex = got ; 4915return true; 4916} 4917 4918bool Verifier :: prepare ( int T , bool & no_vram , std:: string & err ) { 4919no_vram = false; 4920#if defined( STRATA_GPU_METAL ) 4921( void ) T ; 4922( void ) err ; 4923return true; 4924#else 4925if ( T < 1 || T > max_t_ ) { err = "verify: window size out of range" ; return false; } 4926if ( next_ != nullptr || lb_ > 0 ) return true; 4927const OnDevice on_device ( device_ ); 4928refresh_ar (); 4929if (( ar_off_ ? exec_nr_ [ sel_long_ ][ T ] : exec_ [ sel_long_ ][ T ]) != nullptr ) return true; 4930capture_oom_ = false; 4931if ( capture ( T , err )) return true; 4932no_vram = capture_oom_ ; 4933return false; 4934#endif 4935} 4936 4937bool Verifier :: stage_batch (const int * rows , int S , int hbase , const int32_t * tokens , const int64_t * pos , 4938std:: string & err ) { 4939using namespace strata:: kernels ; 4940// the row layout: a slot may own a contiguous group of rows (--batch-mtp), also across the stages of a layer split, 4941// whose hand-off buffers hold kVerifyNarrowT rows, or set_handoff_rows' (a stage that hands rows on or takes them); a 4942// batch window keeps kVerifyMaxT rows (the row tables below) when max_t is longer (--lookup-max-t) 4943if (const char * why = batch_rows_error ( rows , S , pos , ( int ) slots_ . size (), std:: min ( max_t_ , kVerifyMaxT ), hbase , 4944next_ != nullptr || lb_ > 0 , handoff_rows_ > 0 ? handoff_rows_ : kVerifyNarrowT )) { 4945err = why ; 4946return false; 4947} 4948if ( released_ . load ()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine" ; return false; } 4949const ModelGeometry & g = * g_ ; 4950for ( int t = 0 ; t < S ; ++ t ) 4951if ( pos [ t ] < 0 || pos [ t ] + 1 > slots_ [( size_t ) rows [ t ]] -> max_cells ) { 4952err = "verify: slot " + std:: to_string ( rows [ t ]) + " runs past its context" ; 4953return false; 4954} 4955refresh_ar (); 4956// --batch-mtp only (limit 0 = 0.1.39: no eviction): slot rotation creates new layouts; bound the captured graph 4957// pairs, evicting the least recently used layout. Without a limit the same eviction frees VRAM for a capture. 4958const auto key = bkey ( rows , S , hbase ); 4959bool evicted = false; 4960if ( batch_graph_limit_ > 0 && exec_bm_ . find ( key ) == exec_bm_ . end () && exec_bm_ . size () >= batch_graph_limit_ && 4961! evict_batch_graph ( key , evicted , err )) 4962return false; 4963bm_used_ [ key ] = ++ bm_tick_ ; 4964// (a pipelined window that commits after the verdict has its own commit graph: capture_deferred) 4965if (! capture_batch ( rows , S , hbase , err ) || (! staging_deferred_ && ! capture_commit_batch ( rows , S , hbase , err ))) 4966return false; 4967const Clock :: time_point t0 = Clock :: now (); 4968const QsaShapes s = shapes_of ( g ); 4969for ( int t = 0 ; t < S ; ++ t ) { 4970h_tok_ [ t ] = tokens [ t ]; 4971qsa_step_fill ( h_step_ + t * kStepCount , pos [ t ], s ); 4972for ( int64_t h = 0 ; h < g . n_head ; ++ h ) h_pos_ [ t * g . n_head + h ] = ( int32_t ) pos [ t ]; 4973int32_t * pk = h_pos_ + ( size_t ) max_t_ * g . n_head ; 4974int32_t * pi = pk + ( size_t ) max_t_ * g . n_head_kv ; 4975for ( int64_t h = 0 ; h < g . n_head_kv ; ++ h ) pk [ t * g . n_head_kv + h ] = ( int32_t ) pos [ t ]; 4976for ( int64_t h = 0 ; h < g . idx_q_heads ; ++ h ) pi [ t * g . idx_q_heads + h ] = ( int32_t ) pos [ t ]; 4977} 4978if ( ss_ -> ple . ready () && ple_stage ()) { 4979uint32_t ple_rows [ kVerifyMaxT * PLE_N_HEADS ]; // (not `rows`: that is the slots of the window's rows) 4980for ( int t = 0 ; t < S ; ++ t ) { 4981const SessionState & sx = * slots_ [( size_t ) rows [ t ]]; 4982int32_t prev [ 2 ] = { sx . ple_prev [ 0 ], sx . ple_prev [ 1 ]}; 4983if ( t > 0 && rows [ t ] == rows [ t - 1 ]) { 4984prev [ 0 ] = t > 1 && rows [ t - 2 ] == rows [ t ] ? tokens [ t - 2 ] : sx . ple_prev [ 1 ]; 4985prev [ 1 ] = tokens [ t - 1 ]; 4986} 4987ngram_rows ( & tokens [ t ], prev , 1 , ss_ -> ple . consts , ple_rows + t * PLE_N_HEADS ); 4988} 4989if (! ss_ -> ple . table -> gather_batch ( ple_rows , ( size_t ) S , h_ple_ , err )) return false; 4990} 4991// Each slot owns a contiguous group. The default commit keeps all its rows; speculative 4992// decoding may change the prefix length after comparing the draft with these picks. 4993const int64_t CB = 2 + max_t_ ; 4994for ( int t = 0 ; t < S ;) { 4995const int first = t ; 4996while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 4997int32_t * c = h_commitb_ + ( size_t ) rows [ first ] * CB ; 4998c [ 0 ] = t - first ; 4999c [ 1 ] = t - first - 1 ; 5000for ( int64_t j = 0 ; j < max_t_ ; ++ j ) 5001c [ 2 + j ] = j < t - first ? ( int32_t ) pos [ first + j ] : -1 ; 5002} 5003if ( g_trace ) std:: fprintf ( stderr , "K0-STAGE-RESET t=%.3f h_seq=%u\n" , ( double ) std::chrono:: duration_cast < std::chrono:: nanoseconds > (std::chrono::steady_clock:: now (). time_since_epoch ()). count () / 1e6 , * (volatile uint32_t * ) h_seq_ ); 5004* (volatile uint32_t * ) h_seq_ = 0 ; 5005* (volatile uint32_t * ) h_flag_ = 0 ; 5006* (volatile uint32_t * ) h_flagA_ = 0 ; 5007* (volatile uint32_t * ) h_flagB_ = 0 ; 5008if ( h_xlseq_ != nullptr ) * (volatile uint32_t * ) h_xlseq_ = 0 ; // edge0: the D stage's doorbell restarts 5009std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5010last_t_ = S ; 5011for ( int t = 0 ; t < S ; ++ t ) last_rows_ [ t ] = rows [ t ]; 5012row_base_ = hbase ; // the graphs' key (and nothing else) reads it until the next stage_batch 5013last_batch_ = true; 5014for ( int t = 0 ; t < S ; ++ t ) { last_tokens_ [ t ] = tokens [ t ]; last_pos_b_ [ t ] = pos [ t ]; } 5015ms_host += ms_since ( t0 ); 5016return true; 5017} 5018 5019bool Verifier :: run_slots ( int S , const int32_t * tokens , const int64_t * pos , PoolMultiFn pool , void * user , int32_t * out , 5020std:: string & err ) { 5021int rows [strata::kernels:: kVerifyMaxT ] = {}; 5022for ( int t = 0 ; t < S && t < strata::kernels:: kVerifyMaxT ; ++ t ) rows [ t ] = t ; 5023return run_slot_rows ( rows , S , tokens , pos , pool , user , out , err ); 5024} 5025 5026bool Verifier :: run_slot_rows (const int * rows , int S , const int32_t * tokens , const int64_t * pos , PoolMultiFn pool , 5027void * user , int32_t * out , std:: string & err ) { 5028#if defined( STRATA_GPU_METAL ) 5029// each row runs in its slot's state and commits there (a one-token window); nothing is left for commit_slots 5030if ( S < 1 || S > ( int ) strata::kernels:: kVerifyMaxT ) { err = "verify: batch window size out of range" ; return false; } 5031( void ) pool ; ( void ) user ; 5032if (!strata::metal_engine:: window_run_slots ( metal_ , rows , S , tokens , pos , out , err )) return false; 5033last_t_ = S ; 5034for ( int t = 0 ; t < S ; ++ t ) { last_rows_ [ t ] = rows [ t ]; last_tokens_ [ t ] = tokens [ t ]; last_pos_b_ [ t ] = pos [ t ]; } 5035last_batch_ = true; 5036// a slot with its own sampling, penalties or logit bias (set_slot_sampling / set_slot_history / set_slot_logit_bias): its row is drawn again from the 5037// window's logits with Philox(seed, position), as a solo window draws it; a plain greedy slot keeps the window's argmax token 5038{ 5039std:: vector < int32_t > hrows ; 5040for ( int t = 0 ; t < S ; ++ t ) { 5041strata::kernels:: SamplerParams sp ; 5042const int32_t * hist = nullptr ; 5043int hlen = 0 ; 5044const int r = slot_row_draw ( S , t , sp , hist , hlen , hrows , err ); 5045if ( r < 0 ) return false; 5046if ( r == 0 ) continue; 5047if (!strata::metal_engine:: window_sample_slot_row ( metal_ , t , sp , hist , hlen , & out [ t ], err )) return false; 5048} 5049} 5050return true; 5051#endif 5052using namespace strata:: kernels ; 5053const OnDevice on_device ( device_ ); 5054const ModelGeometry & g = * g_ ; 5055if ( pre_launch_ && ! pre_launch_ ( cs_ , err )) return false; 5056if (! stage_batch ( rows , S , 0 , tokens , pos , err )) return false; 5057const cudaError_t le = cudaGraphLaunch ( exec_bm_ [ bkey ( rows , S , 0 )], cs_ ); 5058if ( le != cudaSuccess ) { err = std:: string ( "verify: batch launch: " ) + cudaGetErrorString ( le ); return false; } 5059( void ) cudaStreamQuery ( cs_ ); 5060volatile uint32_t * const seq = h_seq_ ; 5061volatile uint32_t * const flag = h_flag_ ; 5062const int64_t steps = le_ - lb_ ; 5063// #646: a stage whose every expert is resident plans on the device and raises no host doorbells, so the 5064// per-layer spin below has nothing to wait for: without the PLE flag the graph finishes with the ring silent 5065// ("verify batch: layer K never rang (graph finished)" - K is that stage's first layer), and with it the graph 5066// sits on the PLE wait until the 20 s timeout. As run() does: raise the PLE flag the graph's first wait reads, 5067// let the graph run to the end, and skip the host's per-layer service (there is nothing to serve). 5068// #646 + #871: the skip is per-window (ar_on), not per-process (all_resident_): a stage that was 100% 5069// resident at init takes the doorbell graph while a prompt loan/shrink/swap is in flight (ar_off_), and that 5070// graph waits on host doorbells the skipped service never raises (GPU at 100%, host in the sync below). 5071if ( ar_on ()) { 5072if ( ss_ -> ple . ready () && ple_stage ()) { 5073std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5074strata_store_fence (); 5075* flag = 1 ; 5076} 5077const cudaError_t se = cudaStreamSynchronize ( cs_ ); 5078if ( se != cudaSuccess ) { err = std:: string ( "verify batch: " ) + cudaGetErrorString ( se ); return false; } 5079cudaStreamSynchronize ( copy_ ); 5080if ( prof_on_ ) collect_profile (); 5081++ windows ; 5082if ( le_ < g . n_layers ) return next_ == nullptr || next_ -> run_slot_rows ( rows , S , tokens , pos , pool , next_user_ , out , err ); 5083if (! sample_rows ( S , err )) return false; 5084for ( int t = 0 ; t < S ; ++ t ) out [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 5085note_nonfinite ( S , last_pos_b_ ); 5086progress_at ( "decode" ); 5087progress_beat (); 5088return true; 5089} 5090for ( int64_t k = 0 ; k < steps ; ++ k ) { 5091const int64_t l = lb_ + k ; 5092const uint32_t want = ( uint32_t ) ( k + 1 ); 5093const Clock :: time_point a = Clock :: now (); 5094auto last_flush = a ; 5095uint32_t spins = 0 ; 5096progress_at ( "verify batch: waiting for the GPU to reach layer" , l ); 5097while ( * seq < want ) { 5098strata_cpu_pause (); 5099if (( ++ spins & 1023u ) != 0 ) continue; 5100const auto now = Clock :: now (); 5101if ( now - last_flush > std::chrono:: microseconds ( 2000 )) { 5102last_flush = now ; 5103const cudaError_t q = cudaStreamQuery ( cs_ ); 5104if ( q != cudaErrorNotReady && * seq < want ) { 5105err = "verify batch: layer " + std:: to_string ( l ) + " never rang (" + 5106( q == cudaSuccess ? std:: string ( "graph finished" ) : std:: string ( cudaGetErrorString ( q ))) + ")" ; 5107return false; 5108} 5109} 5110if ( now - a > std::chrono:: seconds ( 20 )) { 5111err = "verify batch: timed out at layer " + std:: to_string ( l ) + released_note ( release_gpu_waits ( 5000 )); 5112return false; 5113} 5114} 5115strata_load_fence (); // as above, for the batch loop's wait 5116const Clock :: time_point b = Clock :: now (); 5117cur_layer_ = want - 1 ; 5118set_plan_slot ( 0 ); 5119progress_at ( "verify batch: the CPU experts of layer" , l ); 5120// The recorded graph consumes the helper mask and weighted sum just as 5121// the solo graph does. Reset both and supply this layer's routing weights. 5122if ( remote_opt_ ) remote_opt_ -> begin ( h_w_ , 0 , S ); 5123strata::core:: latent_xl_current () = h_latxlq_ ; 5124strata::core:: latent_xlseq_current () = h_xlseq_ ; 5125strata::core:: latent_act0_current () = m_latact0_ ; 5126if ( pool != nullptr ) pool ( user , h_x_ , h_ids_ , S , ss_ -> k , h_ymiss_ , l ); 5127if ( remote_opt_ ) remote_opt_ -> end (); 5128progress_tick (); 5129std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5130strata_store_fence (); 5131if ( * (volatile uint32_t * ) h_flagA_ != want ) { // the pool did not publish a plan: an empty one 5132sink_ . counts [ 0 ] = 0 ; 5133sink_ . counts [ 1 ] = 0 ; 5134sink_ . counts [ 2 ] = 0 ; 5135sink_ . start [ 0 ] = 0 ; 5136sink_ . start2 [ 0 ] = 0 ; 5137std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5138* (volatile uint32_t * ) h_flagA_ = want ; 5139raise_flag_b_ordered ( want ); // behind any copy still queued from an earlier layer 5140} 5141* flag = want ; 5142ms_wait += std::chrono:: duration < double , std:: milli > ( b - a ). count (); 5143ms_pool += ms_since ( b ); 5144} 5145const cudaError_t se = cudaStreamSynchronize ( cs_ ); 5146if ( se != cudaSuccess ) { err = std:: string ( "verify batch: " ) + cudaGetErrorString ( se ); return false; } 5147cudaStreamSynchronize ( copy_ ); 5148if ( prof_on_ ) collect_profile (); 5149++ windows ; 5150if ( le_ < g . n_layers ) return next_ == nullptr || next_ -> run_slot_rows ( rows , S , tokens , pos , pool , next_user_ , out , err ); 5151if (! sample_rows ( S , err )) return false; 5152for ( int t = 0 ; t < S ; ++ t ) out [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 5153note_nonfinite ( S , last_pos_b_ ); 5154progress_at ( "decode" ); 5155progress_beat (); 5156return true; 5157} 5158 5159bool Verifier :: commit_slots (std:: string & err ) { 5160std:: vector < int > keep ( slots_ . size (), 0 ); 5161for ( int t = 0 ; t < last_t_ ; ++ t ) ++ keep [( size_t ) last_rows_ [ t ]]; 5162return commit_slot_prefixes ( keep . data (), err ); 5163} 5164 5165bool Verifier :: commit_slot_prefixes (const int * keep , std:: string & err ) { 5166#if defined( STRATA_GPU_METAL ) 5167( void ) keep ; // (greedy one-row windows, committed by window_run_slots) 5168if (! last_batch_ || last_t_ < 1 ) { err = "verify: commit_slots without a batch window" ; return false; } 5169return true; 5170#endif 5171const OnDevice on_device ( device_ ); 5172if (! last_batch_ || last_t_ < 1 ) { err = "verify: commit_slots without a batch window" ; return false; } 5173const int S = last_t_ ; 5174const Clock :: time_point t0 = Clock :: now (); 5175const int64_t CB = 2 + max_t_ ; 5176// One prefix per slot: rejected draft rows must not enter recurrent state. 5177for ( int t = 0 ; t < S ;) { 5178const int first = t ; 5179while ( t < S && last_rows_ [ t ] == last_rows_ [ first ]) ++ t ; 5180const int n = keep [ last_rows_ [ first ]]; 5181if ( n < 1 || n > t - first ) { 5182err = "verify: accepted prefix is outside its slot group" ; 5183return false; 5184} 5185int32_t * c = h_commitb_ + ( size_t ) last_rows_ [ first ] * CB ; 5186c [ 0 ] = n ; 5187c [ 1 ] = n - 1 ; 5188for ( int j = 0 ; j < max_t_ ; ++ j ) 5189c [ 2 + j ] = j < n ? ( int32_t ) last_pos_b_ [ first + j ] : -1 ; 5190} 5191std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5192if (! batch_self_commits ( last_rows_ , S )) { // (else the window has kept its rows) 5193const cudaError_t le = cudaGraphLaunch ( commit_bm_ [ bkey ( last_rows_ , S , row_base_ )], cs_ ); 5194if ( le != cudaSuccess ) { err = std:: string ( "verify: batch commit launch: " ) + cudaGetErrorString ( le ); return false; } 5195const cudaError_t se = cudaStreamSynchronize ( cs_ ); 5196if ( se != cudaSuccess ) { err = std:: string ( "verify: batch commit: " ) + cudaGetErrorString ( se ); return false; } 5197} 5198if ( ple_stage ()) 5199for ( int t = 0 ; t < S ;) { 5200const int first = t ; 5201while ( t < S && last_rows_ [ t ] == last_rows_ [ first ]) ++ t ; 5202SessionState & sx = * slots_ [( size_t ) last_rows_ [ first ]]; 5203for ( int u = first ; u < first + keep [ last_rows_ [ first ]]; ++ u ) { 5204sx . ple_prev [ 0 ] = sx . ple_prev [ 1 ]; 5205sx . ple_prev [ 1 ] = last_tokens_ [ u ]; 5206} 5207} 5208ms_commit += ms_since ( t0 ); 5209return next_ == nullptr || next_ -> commit_slot_prefixes ( keep , err ); 5210} 5211 5212bool Verifier :: set_slot_logit_bias ( int slot , const std:: vector < float >& bias , std:: string & err ) { 5213if ( next_ && ! next_ -> set_slot_logit_bias ( slot , bias , err )) return false; 5214if ( le_ >= 0 && le_ < g_ -> n_layers ) return true; 5215if ( slot < 0 || slot >= ( int ) slot_bias_dev_ . size ()) return true; 5216const OnDevice on_device ( device_ ); 5217if ( bias . empty ()) { slot_bias_dev_ [( size_t ) slot ] = nullptr ; slot_sp_ [( size_t ) slot ]. logit_bias = nullptr ; return true; } 5218if ( bias . size () != ( size_t ) n_vocab_ ) { err = "logit_bias vocabulary size mismatch" ; return false; } 5219const size_t bytes = bias . size () * sizeof( float ); 5220if ( slot_bias_dev_ [( size_t ) slot ] == nullptr ) { 5221float * d = nullptr ; 5222if ( cudaMalloc (( void ** ) & d , bytes ) != cudaSuccess ) { err = "cannot allocate the slot's logit_bias" ; return false; } 5223slot_bias_dev_ [( size_t ) slot ] = d ; 5224} 5225if ( cudaMemcpy ( slot_bias_dev_ [( size_t ) slot ], bias . data (), bytes , cudaMemcpyHostToDevice ) != cudaSuccess ) { err = "cannot upload the slot's logit_bias" ; return false; } 5226slot_sp_ [( size_t ) slot ]. logit_bias = slot_bias_dev_ [( size_t ) slot ]; 5227return true; 5228} 5229 5230// One batch row's draw inputs: 0 = the row keeps the window's argmax token (a plain greedy slot), 1 = draw it with `sp` (+ `hist` / `hlen`), -1 = error. 5231// Row t of the last window feeds last_tokens_[t] into slot last_rows_[t]; the penalty-history row is the slot's reply tail plus its tokens in this window up to t 5232// (slot_penalty_rows), staged on the device like a solo window's. 5233int Verifier :: slot_row_draw ( int S , int t , strata::kernels:: SamplerParams & sp , const int32_t *& hist , int & hlen , std:: vector < int32_t >& hrows , 5234std:: string & err ) { 5235constexpr int kSlotHistMax = 4096 ; // serve's kPenaltyWindowCap 5236sp = slot_sp_ [( size_t ) last_rows_ [ t ]]; 5237const bool pen = sp . penalty_last_n > 0 && ( sp . penalty_repeat != 1.0f || sp . penalty_freq != 0.0f || sp . penalty_present != 0.0f ); 5238const bool bias = sp . logit_bias != nullptr ; 5239hist = nullptr ; 5240hlen = 0 ; 5241if (( sp . greedy || sp . temperature <= 0.0f ) && ! pen && ! bias ) return 0 ; // a plain greedy slot keeps the window's argmax token untouched 5242sp . counter = ( uint64_t ) last_pos_b_ [ t ]; // Philox(seed, position): the solo window's draw for this position 5243if (! pen ) { sp . penalty_last_n = 0 ; return 1 ; } 5244std:: vector < const int32_t *> tails ( slots_ . size (), nullptr ); 5245std:: vector < int64_t > n_tails ( slots_ . size (), 0 ); 5246for ( size_t b = 0 ; b < slots_ . size () && b < slot_tail_ . size (); ++ b ) { tails [ b ] = slot_tail_ [ b ]. data (); n_tails [ b ] = ( int64_t ) slot_tail_ [ b ]. size (); } 5247hlen = std:: min ( sp . penalty_last_n , kSlotHistMax ); 5248const size_t need = ( size_t ) S * ( size_t ) hlen ; 5249hrows . assign ( need , -1 ); 5250strata::kernels:: slot_penalty_rows ( last_rows_ , last_tokens_ , S , tails . data (), n_tails . data (), hlen , hrows . data ()); 5251const OnDevice on_hist ( device_ ); 5252if ( slot_hist_cap_ < need ) { 5253if ( slot_hist_d_ != nullptr ) cudaFree ( slot_hist_d_ ); 5254slot_hist_d_ = nullptr ; 5255if ( cudaMalloc (( void ** ) & slot_hist_d_ , need * sizeof( int32_t )) != cudaSuccess ) { err = "verify batch: the penalty-history allocation failed" ; return -1 ; } 5256slot_hist_cap_ = need ; 5257} 5258#if defined( STRATA_GPU_METAL ) 5259if ( cudaMemcpy ( slot_hist_d_ + ( size_t ) t * ( size_t ) hlen , hrows . data () + ( size_t ) t * ( size_t ) hlen , ( size_t ) hlen * sizeof( int32_t ), cudaMemcpyHostToDevice ) != cudaSuccess ) 5260#else 5261if ( cudaMemcpyAsync ( slot_hist_d_ + ( size_t ) t * ( size_t ) hlen , hrows . data () + ( size_t ) t * ( size_t ) hlen , ( size_t ) hlen * sizeof( int32_t ), 5262cudaMemcpyHostToDevice , cs_ ) != cudaSuccess ) 5263#endif 5264{ err = "verify batch: the penalty-history copy failed" ; return -1 ; } 5265hist = slot_hist_d_ + ( size_t ) t * ( size_t ) hlen ; 5266return 1 ; 5267} 5268 5269bool Verifier :: sample_rows ( int S , std:: string & err ) { 5270#if defined( STRATA_GPU_METAL ) 5271( void ) S ; 5272err = "verify batch: sample_rows is the CUDA / HIP path" ; 5273return false; 5274#else 5275bool any = false; 5276std:: vector < int32_t > hrows ; 5277for ( int t = 0 ; t < S ; ++ t ) { 5278strata::kernels:: SamplerParams sp ; 5279const int32_t * hist = nullptr ; 5280int hlen = 0 ; 5281const int r = slot_row_draw ( S , t , sp , hist , hlen , hrows , err ); 5282if ( r < 0 ) return false; 5283if ( r == 0 ) continue; 5284strata::kernels:: sample_tokens ( head_logits_ + ( size_t ) t * ( size_t ) n_vocab_ , 1 , ( int ) n_vocab_ , hist , hlen , sp , m_out_ + t , cs_ ); 5285any = true; 5286} 5287if ( any && cudaStreamSynchronize ( cs_ ) != cudaSuccess ) { err = "verify batch: the row sampling failed" ; return false; } 5288return true; 5289#endif 5290} 5291 5292bool Verifier :: batch_launch ( int base , int S , const int32_t * tokens , const int64_t * pos , std:: string & err ) { 5293const OnDevice on_device ( device_ ); 5294if ( b_running_ ) { err = "verify: batch_launch while this stage is busy" ; return false; } 5295int rows [strata::kernels:: kVerifyMaxT ] = {}; 5296for ( int t = 0 ; t < S && t < strata::kernels:: kVerifyMaxT ; ++ t ) rows [ t ] = base + t ; 5297if ( pre_launch_ && ! pre_launch_ ( cs_ , err )) return false; 5298if (! stage_batch ( rows , S , base , tokens , pos , err )) return false; 5299cudaError_t le = cudaGraphLaunch ( exec_bm_ [ bkey ( rows , S , base )], cs_ ); 5300if ( le == cudaSuccess && ! batch_self_commits ( rows , S )) // (else the window has kept its rows itself) 5301le = cudaGraphLaunch ( commit_bm_ [ bkey ( rows , S , base )], cs_ ); // right behind it: every row is kept 5302if ( le != cudaSuccess ) { err = std:: string ( "verify: batch launch: " ) + cudaGetErrorString ( le ); return false; } 5303( void ) cudaStreamQuery ( cs_ ); 5304if ( ple_stage ()) // the host's side of the commit (the hash's last two tokens) 5305for ( int t = 0 ; t < S ; ++ t ) { 5306SessionState & sx = * slots_ [( size_t ) rows [ t ]]; 5307sx . ple_prev [ 0 ] = sx . ple_prev [ 1 ]; 5308sx . ple_prev [ 1 ] = tokens [ t ]; 5309} 5310b_k_ = 0 ; 5311b_steps_ = le_ - lb_ ; 5312ring_now (); 5313b_running_ . store (true, std:: memory_order_release ); // last: an external server reads the rest after it 5314return true; 5315} 5316 5317int Verifier :: batch_serve ( PoolMultiFn pool , void * user ) { 5318if (! b_running_ . load (std:: memory_order_acquire )) return 1 ; 5319volatile uint32_t * const seq = h_seq_ ; 5320// #646: an all-resident stage's graph raises no host doorbells (see run_slot_rows): nothing to serve per layer, 5321// except the PLE flag, which the graph's first wait reads and only the host can raise (the same raise 5322// run_slot_rows makes). Per-window (ar_on): with a loan in flight the doorbell graph needs the per-layer service. 5323if ( ar_on () && ss_ -> ple . ready () && ple_stage ()) { 5324std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5325strata_store_fence (); 5326* h_flag_ = 1 ; 5327} 5328for (;;) { 5329// the window's row count is read after the served-layer count: with external serving the window this call 5330// began on can have finished and the next one been launched meanwhile, and batch_launch writes its rows 5331// (stage_batch) before it resets b_k_, so a count that is the new window's comes with the new rows 5332const int64_t k = b_k_ . load (std:: memory_order_acquire ); 5333if ( ar_on () || k >= b_steps_ ) break; 5334const uint32_t want = ( uint32_t ) ( k + 1 ); 5335if ( * seq < want ) return 0 ; 5336const int S = last_t_ ; 5337const Clock :: time_point b = Clock :: now (); 5338cur_layer_ = want - 1 ; 5339set_plan_slot ( 0 ); 5340if ( remote_opt_ ) remote_opt_ -> begin ( h_w_ , 0 , S ); 5341if ( pool != nullptr ) { 5342strata::core:: latent_xl_current () = h_latxlq_ ; 5343strata::core:: latent_xlseq_current () = h_xlseq_ ; 5344strata::core:: latent_act0_current () = m_latact0_ ; 5345pool ( user , h_x_ , h_ids_ , S , ss_ -> k , h_ymiss_ , lb_ + k ); 5346} 5347if ( remote_opt_ ) remote_opt_ -> end (); 5348progress_tick (); 5349std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5350strata_store_fence (); 5351if ( * (volatile uint32_t * ) h_flagA_ != want ) { // the pool did not publish a plan: an empty one 5352sink_ . counts [ 0 ] = 0 ; 5353sink_ . counts [ 1 ] = 0 ; 5354sink_ . counts [ 2 ] = 0 ; 5355sink_ . start [ 0 ] = 0 ; 5356sink_ . start2 [ 0 ] = 0 ; 5357std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5358* (volatile uint32_t * ) h_flagA_ = want ; 5359raise_flag_b_ordered ( want ); // behind any copy still queued from an earlier layer 5360} 5361* (volatile uint32_t * ) h_flag_ = want ; 5362if ( g_trace ) std:: fprintf ( stderr , "FLAG-SET want=%u\n" , ( unsigned ) want ); 5363ms_pool += ms_since ( b ); 5364ring_now (); 5365b_k_ . fetch_add ( 1 , std:: memory_order_release ); 5366} 5367return 1 ; 5368} 5369 5370int Verifier :: batch_poll ( PoolMultiFn pool , void * user , std:: string & err ) { 5371if (! b_running_ ) return 1 ; 5372// set_external_serve: another thread serves the doorbells (batch_serve) and this one only checks for a window that 5373// will not finish, as below: its graph ended (or failed) with a layer still to ring, or no layer rang for 20 s. 5374// The stream query can wait for the driver's lock while a read's call holds it; the doorbells go on meanwhile. 5375// The served count is read before the query and the ring count after it: a layer served in between rang first. 5376if ( ext_serve_ . load (std:: memory_order_acquire ) && ! ar_on ()) { 5377const int64_t k = b_k_ . load (std:: memory_order_acquire ); 5378if ( k < b_steps_ ) { 5379const auto now = Clock :: now (); 5380if ( now - last_ring () <= std::chrono:: milliseconds ( 2 ) || now - ext_checked_ < std::chrono:: milliseconds ( 1 )) 5381return 0 ; 5382ext_checked_ = now ; // (at most one query a millisecond: pump calls this in a loop) 5383const OnDevice on_device ( device_ ); 5384const cudaError_t q = cudaStreamQuery ( cs_ ); 5385if ( q != cudaErrorNotReady && * (volatile uint32_t * ) h_seq_ < ( uint32_t ) ( k + 1 )) { 5386err = "verify batch: layer " + std:: to_string ( lb_ + k ) + " never rang (" + 5387( q == cudaSuccess ? std:: string ( "graph finished" ) : std:: string ( cudaGetErrorString ( q ))) + ")" ; 5388b_running_ = false; 5389return -1 ; 5390} 5391if ( now - last_ring () > std::chrono:: seconds ( 20 )) { 5392err = "verify batch: timed out at layer " + std:: to_string ( lb_ + k ) + 5393released_note ( release_gpu_waits ( 5000 )); 5394b_running_ = false; 5395return -1 ; 5396} 5397return 0 ; 5398} 5399} 5400const OnDevice on_device ( device_ ); 5401const int S = last_t_ ; 5402// the layers that have rung so far (batch_serve); with one still to ring: did the graph finish without it, or 5403// has it waited too long? 5404if (! batch_serve ( pool , user )) { 5405const auto now = Clock :: now (); 5406if ( now - last_ring () > std::chrono:: milliseconds ( 2 )) { 5407const cudaError_t q = cudaStreamQuery ( cs_ ); 5408if ( q != cudaErrorNotReady && * (volatile uint32_t * ) h_seq_ < ( uint32_t ) ( b_k_ + 1 )) { 5409err = "verify batch: layer " + std:: to_string ( lb_ + b_k_ ) + " never rang (" + 5410( q == cudaSuccess ? std:: string ( "graph finished" ) : std:: string ( cudaGetErrorString ( q ))) + ")" ; 5411b_running_ = false; 5412return -1 ; 5413} 5414if ( now - last_ring () > std::chrono:: seconds ( 20 )) { 5415err = "verify batch: timed out at layer " + std:: to_string ( lb_ + b_k_ ) + 5416released_note ( release_gpu_waits ( 5000 )); 5417b_running_ = false; 5418return -1 ; 5419} 5420} 5421return 0 ; 5422} 5423const cudaError_t q = cudaStreamQuery ( cs_ ); 5424if ( q == cudaErrorNotReady ) return 0 ; 5425if ( q != cudaSuccess ) { err = std:: string ( "verify batch: " ) + cudaGetErrorString ( q ); b_running_ = false; return -1 ; } 5426const cudaError_t qc = cudaStreamQuery ( copy_ ); // no host function of this window may raise flag B in the next 5427if ( qc == cudaErrorNotReady ) return 0 ; 5428if ( prof_on_ ) collect_profile (); 5429if ( last_stage ()) { 5430if (! sample_rows ( S , err )) { b_running_ = false; return -1 ; } 5431for ( int t = 0 ; t < S ; ++ t ) b_out_ [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 5432note_nonfinite ( S , last_pos_b_ ); 5433} 5434++ windows ; 5435b_running_ = false; 5436progress_beat (); 5437return 1 ; 5438} 5439 5440// #879: STRATA_NAN_GUARD=0 turns the guard off (no kernel is recorded; the graphs are captured once, so it is read once) 5441bool Verifier :: nan_guard_on () { 5442static const bool on = [] { 5443const char * v = std:: getenv ( "STRATA_NAN_GUARD" ); 5444return v == nullptr || std:: atoi ( v ) != 0 ; 5445}(); 5446return on ; 5447} 5448 5449namespace { 5450// STRATA_NAN_INJECT=<n>[,<n>...] (debug): the windows (counted from 1 over the process) the guard reports as non-finite 5451const std:: vector < long long >& nan_inject_list () { 5452static const std:: vector < long long > list = [] { 5453std:: vector < long long > v ; 5454if (const char * e = std:: getenv ( "STRATA_NAN_INJECT" )) 5455for (const char * q = e ; * q != 0 ;) { 5456char * end = nullptr ; 5457const long long n = std:: strtoll ( q , & end , 10 ); 5458if ( end == q ) break; 5459if ( n > 0 ) v . push_back ( n ); 5460q = * end == ',' ? end + 1 : end ; 5461} 5462return v ; 5463}(); 5464return list ; 5465} 5466std:: atomic < long long > g_nf_windows { 0 }; 5467} // namespace 5468 5469void Verifier :: note_nonfinite ( int T , const int64_t * pos_b ) { 5470nf_row_ = -1 ; 5471nf_pos_ = -1 ; 5472nf_mask_ = 0 ; 5473if (! nan_guard_on () || h_nf_ == nullptr || ! last_stage ()) return; // (a stage without the head checks nothing) 5474const volatile uint32_t * f = h_nf_ ; 5475for ( int t = 0 ; t < T && t < strata::kernels:: kVerifyMaxT ; ++ t ) 5476for ( int b = 0 ; b < strata::kernels:: kNonfiniteBlocks ; ++ b ) 5477if ( f [ t * strata::kernels:: kNonfiniteBlocks + b ] != 0 ) { nf_mask_ |= 1u << t ; break; } 5478const std:: vector < long long >& inject = nan_inject_list (); 5479if (! inject . empty ()) { 5480const long long k = g_nf_windows . fetch_add ( 1 ) + 1 ; 5481if ( nf_mask_ == 0 && std:: find ( inject . begin (), inject . end (), k ) != inject . end ()) { 5482nf_mask_ = 1u ; 5483std:: fprintf ( stderr , "strata verify: STRATA_NAN_INJECT: window %lld reported as non-finite\n" , k ); 5484} 5485} 5486for ( int t = 0 ; t < T && nf_row_ < 0 ; ++ t ) 5487if (( nf_mask_ >> t ) & 1u ) nf_row_ = t ; 5488if ( nf_row_ >= 0 ) nf_pos_ = pos_b != nullptr ? pos_b [ nf_row_ ] : last_pos0_ + nf_row_ ; 5489} 5490 5491bool Verifier :: copy_logits ( int t , float * host ) const { 5492#if defined( STRATA_GPU_METAL ) 5493return strata::metal_engine:: window_copy_logits ( metal_ , t , host ); 5494#endif 5495if ( next_ != nullptr ) return next_ -> copy_logits ( t , host ); // a layer split: the head is on the last stage 5496if ( head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0 ) return false; 5497return cudaMemcpy ( host , head_logits_ + ( size_t ) t * ( size_t ) n_vocab_ , ( size_t ) n_vocab_ * sizeof( float ), 5498cudaMemcpyDeviceToHost ) == cudaSuccess ; 5499} 5500 5501 5502// ================================ PIPELINED WINDOWS (see verify.hpp) ================================ 5503// 5504// The window is run()'s, step for step: the same graph, the same staging, the same per-layer service (the PLE rows 5505// gathered while layer 0 is served, the zero-doorbell graph's one flag), the same commit graph. Only the waits are 5506// split up: the host polls instead of spinning, so it can serve the other stage's window in between. 5507 5508namespace { 5509double now_ms () { return std::chrono:: duration < double , std:: milli > ( Clock :: now (). time_since_epoch ()). count (); } 5510} // namespace 5511 5512void Verifier :: diag_pipelined (std:: FILE * f , const char * name ) const { 5513auto rd = [](const uint32_t * p ) { return p ? * (const volatile uint32_t * ) p : 0u ; }; 5514auto ev = []( cudaEvent_t e ) { 5515if ( e == nullptr ) return "none" ; 5516const cudaError_t q = cudaEventQuery ( e ); 5517return q == cudaSuccess ? "done" : q == cudaErrorNotReady ? "PENDING" : "error" ; 5518}; 5519std:: fprintf ( f , " %s: %s T=%d pos %lld served %lld/%lld; GPU rang %u, flags served %u A %u B %u; window event %s, " 5520"commit event %s (commit launched %d)\n" , name , fl_active_ ? "IN FLIGHT" : "idle" , last_t_ , 5521( long long ) last_pos0_ , ( long long ) fl_k_ , ( long long ) fl_total_ , rd ( h_seq_ ), rd ( h_flag_ ), rd ( h_flagA_ ), 5522rd ( h_flagB_ ), ev ( ev_done_ ), ev ( ev_commit_ ), ( int ) commit_live_ ); 5523} 5524 5525bool Verifier :: capture_all (std:: string & err ) { 5526const OnDevice on_device ( device_ ); 5527if ( g_ == nullptr ) { err = "verify: capture_all before init" ; return false; } 5528if ( remote_opt_ != nullptr ) { err = "verify: pipelined windows do not serve --remote-expert-opt" ; return false; } 5529if ( released_ . load ()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine" ; return false; } 5530struct NoEvict { // every size is wanted at once here: a capture must not free another size's graph 5531bool & f ; 5532explicit NoEvict ( bool & flag ) : f ( flag ) { f = true; } 5533~ NoEvict () { f = false; } 5534} no_evict ( no_window_eviction_ ); 5535// STRATA_SELECT_LONG: both select variants (see select_long_at): pl_launch takes the one its window's context 5536// needs, and nothing can be captured once pipelined windows are in flight. Without it only [0] 5537for ( int sl = 0 ; sl < ( select_long_on () ? 2 : 1 ); ++ sl ) { 5538sel_long_ = sl ; 5539for ( int T = 1 ; T <= max_t_ ; ++ T ) 5540if (! capture ( T , err )) return false; 5541} 5542sel_long_ = 0 ; 5543if (! capture_commit ( err )) return false; 5544if (( ev_done_ == nullptr && cudaEventCreateWithFlags ( & ev_done_ , cudaEventDisableTiming ) != cudaSuccess ) || 5545( ev_commit_ == nullptr && cudaEventCreateWithFlags ( & ev_commit_ , cudaEventDisableTiming ) != cudaSuccess )) { 5546err = "verify: event create failed" ; 5547return false; 5548} 5549if ( prof_on_ && prof_pin_ == nullptr && 5550cudaHostAlloc (( void ** ) & prof_pin_ , prof_h_ . size () * 8 , cudaHostAllocDefault ) != cudaSuccess ) { 5551prof_pin_ = nullptr ; // the pipelined windows go unprofiled 5552cudaGetLastError (); 5553} 5554pl_ple_rows_ . assign (( size_t ) strata::kernels:: kVerifyMaxT * strata::kernels:: PLE_N_HEADS , 0u ); 5555return true; 5556} 5557 5558// The host staging of a pipelined window: run()'s (stage_inputs), and its PLE rows from `ple_prev` with their pages 5559// prefetched (they are gathered into the mapped rows when layer 0 is served, as run() does). 5560void Verifier :: pl_stage ( int T , const int32_t * tokens , int64_t pos0 , const int32_t ple_prev [ 2 ]) { 5561using namespace strata:: kernels ; 5562stage_inputs ( T , tokens , pos0 ); 5563staged_ = false; // a later run() stages its own window 5564SessionState & ss = * ss_ ; 5565fl_ple_ = ss . ple . ready () && ple_stage (); 5566if ( fl_ple_ ) { 5567int32_t prev [ 2 ] = { ple_prev [ 0 ], ple_prev [ 1 ]}; 5568for ( int t = 0 ; t < T ; ++ t ) { 5569ngram_rows ( & tokens [ t ], prev , 1 , ss . ple . consts , pl_ple_rows_ . data () + t * PLE_N_HEADS ); 5570prev [ 0 ] = prev [ 1 ]; 5571prev [ 1 ] = tokens [ t ]; 5572ss . ple . table -> prefetch_rows ( pl_ple_rows_ . data () + t * PLE_N_HEADS ); 5573} 5574} 5575pl_prev_ [ 0 ] = ple_prev [ 0 ]; 5576pl_prev_ [ 1 ] = ple_prev [ 1 ]; 5577} 5578 5579bool Verifier :: prestage ( int T , const int32_t * tokens , int64_t pos0 , const int32_t ple_prev [ 2 ], std:: string & err ) { 5580if ( fl_active_ ) { err = "verify: a window is in flight on this verifier" ; return false; } 5581if ( T < 1 || T > max_t_ ) { err = "verify: window size out of range" ; return false; } 5582if ( pl_ple_rows_ . empty ()) { err = "verify: pipelined window not prepared (capture_all)" ; return false; } 5583const Clock :: time_point t0 = Clock :: now (); 5584pl_stage ( T , tokens , pos0 , ple_prev ); 5585pl_prestaged_ = true; 5586ms_host += ms_since ( t0 ); 5587return true; 5588} 5589 5590bool Verifier :: pl_launch ( int T , const int32_t * tokens , int64_t pos0 , std:: string & err ) { 5591const OnDevice on_device ( device_ ); 5592if ( fl_active_ ) { err = "verify: a window is already in flight on this verifier" ; return false; } 5593if ( released_ . load ()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine" ; return false; } 5594if ( T < 1 || T > max_t_ || T > strata::kernels:: kVerifyMaxT ) { err = "verify: window size out of range" ; return false; } 5595SessionState & ss = * ss_ ; 5596if ( pos0 + T > ss . qsa_states [ ss . qsa_primary ()]. max_cells ) { err = "verify: the window runs past the context" ; return false; } 5597const int sl = select_long_on () && pos0 + T >= select_long_at () ? 1 : 0 ; // the variant this window's context pays off with 5598if ( exec_ [ sl ][ T ] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_ . empty ()) { 5599err = "verify: pipelined window not prepared (capture_all)" ; 5600return false; 5601} 5602if ( pre_launch_ && ! pre_launch_ ( cs_ , err )) return false; 5603const Clock :: time_point t0 = Clock :: now (); 5604last_batch_ = false; 5605bool staged = pl_prestaged_ && last_t_ == T && last_pos0_ == pos0 ; 5606for ( int t = 0 ; staged && t < T ; ++ t ) staged = last_tokens_ [ t ] == tokens [ t ]; 5607if ( staged && ss . ple . ready () && ple_stage ()) 5608staged = pl_prev_ [ 0 ] == ss . ple_prev [ 0 ] && pl_prev_ [ 1 ] == ss . ple_prev [ 1 ]; 5609pl_prestaged_ = false; 5610if (! staged ) pl_stage ( T , tokens , pos0 , ss . ple_prev ); 5611const int G = groups_ [ T ] > 0 ? groups_ [ T ] : 1 ; 5612fl_T_ = T ; 5613fl_k_ = 0 ; 5614fl_total_ = ( le_ - lb_ ) * G ; 5615fl_prof_ = prof_on_ && G == 1 && prof_pin_ != nullptr ; 5616if ( trace_h_ != nullptr ) std:: memset ( trace_h_ , 0 , trace_n_ * 8 ); // #649: this window's breadcrumbs only 5617std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5618trace_ev ( "WINDOW (pipelined)" , -1 , -1 , pos0 * 16 + T ); 5619ms_host += ms_since ( t0 ); 5620strata::dispatch:: Stats :: get (). graph_launch ( T , ar_on () ? 0 : 1 ); 5621const cudaError_t le = cudaGraphLaunch ( exec_ [ sl ][ T ], cs_ ); 5622trace_ev ( "LAUNCHED" , -1 , -1 , ( int64_t ) le ); 5623if ( le != cudaSuccess ) { err = std:: string ( "verify: launch: " ) + cudaGetErrorString ( le ); return false; } 5624if ( fl_prof_ ) cudaMemcpyAsync ( prof_pin_ , prof_ , prof_h_ . size () * 8 , cudaMemcpyDeviceToHost , cs_ ); 5625if ( cudaEventRecord ( ev_done_ , cs_ ) != cudaSuccess ) { err = "verify: event record failed" ; return false; } 5626( void ) cudaStreamQuery ( cs_ ); // WDDM: submit now 5627fl_active_ = true; 5628fl_since_ms_ = fl_flush_ms_ = fl_launch_ms_ = now_ms (); 5629return true; 5630} 5631 5632int Verifier :: service ( PoolMultiFn pool , void * user , std:: string & err ) { 5633if (! fl_active_ ) return 1 ; 5634if ( fl_k_ >= fl_total_ ) return 1 ; 5635// Nothing rang yet and neither the WDDM flush nor the timeout below is due: return before any CUDA call. The 5636// pipelined loop asks both stages' windows this millions of times a second while they wait on their doorbells, 5637// and the device switch (OnDevice: cudaGetDevice and two cudaSetDevice) made that a few driver calls each time: 5638// 919 million passes before the host stalled inside one of those cudaSetDevice calls with both stages waiting 5639// on it (0.1.41, Windows, an RTX 3060 + RTX 5070 Ti split). The same answer as the loop below gives. 5640if (! ar_on () && * (volatile uint32_t * ) h_seq_ < ( uint32_t ) ( fl_k_ + 1 )) { 5641const double now = now_ms (); 5642if ( now - fl_flush_ms_ <= 2.0 && now - fl_since_ms_ <= 20000.0 ) return 0 ; 5643} 5644const OnDevice on_device ( device_ ); 5645const ModelGeometry & g = * g_ ; 5646SessionState & ss = * ss_ ; 5647const int T = fl_T_ ; 5648// the PLE rows into the mapped staging (layer 1's pre() copies them once flag 1 is up), as run() does at k == 0 5649auto gather_ple = [ & ]() -> bool { 5650if (! fl_ple_ ) return true; 5651const Clock :: time_point tp = Clock :: now (); 5652if (! ss . ple . table -> gather_batch ( pl_ple_rows_ . data (), ( size_t ) T , h_ple_ , err )) return false; 5653std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5654strata_store_fence (); 5655ms_host += ms_since ( tp ); 5656return true; 5657}; 5658if ( ar_on ()) { // the zero-doorbell graph never rings: it waits only for flag 1 (stage 0's PLE rows). 5659// Per-window: with a loan in flight (ar_off_) the doorbell graph needs the per-layer service below. 5660if (! gather_ple ()) return -1 ; 5661* (volatile uint32_t * ) h_flag_ = 1 ; 5662fl_k_ = fl_total_ ; 5663progress_tick (); 5664return 1 ; 5665} 5666const int G = groups_ [ T ] > 0 ? groups_ [ T ] : 1 ; 5667const int gtb [ 2 ] = { 0 , ( T + 1 ) / 2 }, gte [ 2 ] = { G == 2 ? ( T + 1 ) / 2 : T , T }; 5668while ( fl_k_ < fl_total_ ) { 5669const int64_t l = lb_ + fl_k_ / G ; 5670const uint32_t want = ( uint32_t ) ( fl_k_ + 1 ); 5671if ( * (volatile uint32_t * ) h_seq_ < want ) { 5672const double now = now_ms (); 5673if ( now - fl_flush_ms_ > 2.0 ) { // flush WDDM and notice a dead graph, as run() does 5674fl_flush_ms_ = now ; 5675const cudaError_t q = cudaEventQuery ( ev_done_ ); 5676if ( q != cudaErrorNotReady && * (volatile uint32_t * ) h_seq_ < want ) { 5677trace_ev ( "NEVER-RANG" , fl_k_ , l , ( int64_t ) q ); 5678err = "verify: layer " + std:: to_string ( l ) + " never rang (" + 5679( q == cudaSuccess ? std:: string ( "graph finished" ) : std:: string ( cudaGetErrorString ( q ))) + ")" ; 5680return -1 ; 5681} 5682( void ) cudaStreamQuery ( cs_ ); 5683} 5684if ( now - fl_since_ms_ > 20000.0 ) { // #267: no spin kernel may outlive the engine 5685trace_ev ( "TIMEOUT" , fl_k_ , l , 0 ); 5686err = "verify: timed out at layer " + std:: to_string ( l ) + released_note ( release_gpu_waits ( 5000 )); 5687return -1 ; 5688} 5689return 0 ; 5690} 5691const Clock :: time_point b = Clock :: now (); 5692ms_wait += now_ms () - fl_since_ms_ ; 5693const int grp = ( int ) ( fl_k_ % G ); 5694cur_layer_ = want - 1 ; 5695set_plan_slot ( grp ); 5696const int tb = gtb [ grp ], n = gte [ grp ] - gtb [ grp ]; 5697progress_at ( "verify window (pipelined): the CPU experts of layer" , l ); 5698if ( pool != nullptr ) { 5699strata::core:: latent_xl_current () = h_latxlq_ ; 5700strata::core:: latent_xlseq_current () = h_xlseq_ ; 5701strata::core:: latent_act0_current () = m_latact0_ ; 5702pool ( user , h_x_ + ( size_t ) tb * g . n_embd , h_ids_ + ( size_t ) tb * ss . k , n , ss . k , 5703h_ymiss_ + ( size_t ) tb * ss . k * g . n_embd , l ); 5704} 5705if ( g_trace ) trace_ev ( * (volatile uint32_t * ) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET" , fl_k_ , l , 5706( int64_t ) ms_since ( b )); 5707progress_tick (); 5708std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5709strata_store_fence (); 5710if ( * (volatile uint32_t * ) h_flagA_ != want ) { // the pool did not publish a plan: an empty one 5711sink_ . counts [ 0 ] = 0 ; 5712sink_ . counts [ 1 ] = 0 ; 5713sink_ . counts [ 2 ] = 0 ; 5714sink_ . start [ 0 ] = 0 ; 5715sink_ . start2 [ 0 ] = 0 ; 5716std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5717* (volatile uint32_t * ) h_flagA_ = want ; 5718raise_flag_b_ordered ( want ); // behind any copy still queued from an earlier layer 5719} 5720if ( g_trace ) std:: fprintf ( stderr , "GATHER-PLE fl_k=%lld fl_ple=%d\n" , ( long long ) fl_k_ , ( int ) fl_ple_ ); 5721if ( fl_k_ == 0 && ! gather_ple ()) return -1 ; 5722* (volatile uint32_t * ) h_flag_ = want ; 5723if ( g_trace ) std:: fprintf ( stderr , "FLAG-SET want=%u seq=%u fl_k=%lld\n" , ( unsigned ) want , * (volatile uint32_t * ) h_seq_ , ( long long ) fl_k_ ); 5724++ fl_k_ ; 5725ms_pool += ms_since ( b ); 5726fl_since_ms_ = fl_flush_ms_ = now_ms (); 5727} 5728return 1 ; 5729} 5730 5731bool Verifier :: done (std:: string & err ) { 5732if (! fl_active_ || fl_k_ < fl_total_ ) return false; 5733const OnDevice on_device ( device_ ); 5734const cudaError_t q = cudaEventQuery ( ev_done_ ); 5735if ( q == cudaErrorNotReady ) { 5736const double now = now_ms (); 5737if ( now - fl_flush_ms_ > 2.0 ) { fl_flush_ms_ = now ; ( void ) cudaStreamQuery ( cs_ ); } 5738if ( now - fl_since_ms_ > 20000.0 ) { // every layer served, and the graph still runs: #267 as above 5739err = "verify: the window never finished" + released_note ( release_gpu_waits ( 5000 )); 5740} 5741return false; 5742} 5743if ( q != cudaSuccess ) { err = std:: string ( "verify: " ) + cudaGetErrorString ( q ); return false; } 5744if ( copy_used_ ) { // no host function of this window may raise flag B in the next one 5745if ( cudaStreamQuery ( copy_ ) == cudaErrorNotReady ) return false; 5746copy_used_ = false; 5747} 5748return true; 5749} 5750 5751bool Verifier :: pl_finish ( int32_t * out , std:: string & err ) { 5752using namespace strata:: kernels ; 5753const OnDevice on_device ( device_ ); 5754const ModelGeometry & g = * g_ ; 5755fl_active_ = false; 5756if ( fl_prof_ ) accumulate_profile ( prof_pin_ ); 5757++ windows ; 5758trace_ev ( "DONE (pipelined)" , -1 , -1 , ( int64_t ) ( now_ms () - fl_launch_ms_ )); 5759if ( le_ < g . n_layers ) return true; // an earlier stage: the hand-off is written 5760const int T = fl_T_ ; 5761const bool sampled = ! sampling_ . greedy && sampling_ . temperature > 0.0f ; 5762if ( head_sampling_ && ( sampled || hist_d_ != nullptr || sampling_ . logit_bias != nullptr )) { // run()'s host-side sampling, Philox(seed, pos0 + t) 5763SamplerParams sp = sampling_ ; 5764sp . counter = ( uint64_t ) last_pos0_ ; 5765sample_tokens ( head_logits_ , T , ( int ) n_vocab_ , hist_d_ , hist_len_ , sp , m_out_ , cs_ ); 5766if ( cudaStreamSynchronize ( cs_ ) != cudaSuccess ) { 5767err = "verify: the head sampling failed" ; 5768return false; 5769} 5770} 5771if ( out != nullptr ) 5772for ( int t = 0 ; t < T ; ++ t ) out [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 5773note_nonfinite ( T , nullptr ); 5774progress_beat (); 5775return true; 5776} 5777 5778bool Verifier :: pl_commit_async ( int n_keep , std:: string & err ) { 5779const OnDevice on_device ( device_ ); 5780if ( n_keep < 1 || n_keep > last_t_ ) { err = "verify: commit count out of range" ; return false; } 5781if ( commit_exec_ == nullptr || ev_commit_ == nullptr ) { err = "verify: pipelined commit not prepared" ; return false; } 5782const Clock :: time_point t0 = Clock :: now (); 5783if ( commit_live_ ) { // its graph reads the words below when it starts: the previous one has (a window ago) 5784cudaError_t q ; 5785while (( q = cudaEventQuery ( ev_commit_ )) == cudaErrorNotReady ) strata_cpu_pause (); 5786if ( q != cudaSuccess ) { err = std:: string ( "verify: commit: " ) + cudaGetErrorString ( q ); return false; } 5787} 5788h_commit_ [ 0 ] = n_keep ; 5789h_commit_ [ 1 ] = n_keep - 1 ; 5790for ( int t = 0 ; t < max_t_ ; ++ t ) h_commit_ [ 2 + t ] = t < n_keep ? ( int32_t ) ( last_pos0_ + t ) : -1 ; 5791std:: atomic_thread_fence (std:: memory_order_seq_cst ); 5792const cudaError_t le = cudaGraphLaunch ( commit_exec_ , cs_ ); 5793if ( le != cudaSuccess ) { err = std:: string ( "verify: commit launch: " ) + cudaGetErrorString ( le ); return false; } 5794if ( cudaEventRecord ( ev_commit_ , cs_ ) != cudaSuccess ) { err = "verify: event record failed" ; return false; } 5795( void ) cudaStreamQuery ( cs_ ); 5796commit_live_ = true; 5797if ( ple_stage ()) 5798for ( int t = 0 ; t < n_keep ; ++ t ) { 5799ss_ -> ple_prev [ 0 ] = ss_ -> ple_prev [ 1 ]; 5800ss_ -> ple_prev [ 1 ] = last_tokens_ [ t ]; 5801} 5802ms_commit += ms_since ( t0 ); 5803return true; 5804} 5805 5806void Verifier :: absorb_stats ( Verifier & o ) { 5807ms_wait += o . ms_wait ; ms_pool += o . ms_pool ; ms_host += o . ms_host ; ms_commit += o . ms_commit ; 5808windows += o . windows ; 5809o . ms_wait = o . ms_pool = o . ms_host = o . ms_commit = 0 ; 5810o . windows = 0 ; 5811for ( int k = 0 ; k < 2 ; ++ k ) 5812for ( int i = 0 ; i < kProfPer ; ++ i ) { prof_sum_ [ k ][ i ] += o . prof_sum_ [ k ][ i ]; o . prof_sum_ [ k ][ i ] = 0 ; } 5813prof_windows_ += o . prof_windows_ ; 5814o . prof_windows_ = 0 ; 5815} 5816 5817} // namespace strata::core