okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a8a51b280
main
1#include "b60_layout_state.hpp" 2// src/core/verify.cpp - see include/strata/core/verify.hpp. 3#define DPCT_PROFILING_ENABLED 4#include <sycl/sycl.hpp> 5#include <dpct/dpct.hpp> 6#include "strata/sycl_queue.hpp" 7#include "strata/kprof.hpp" 8#include "strata/core/verify.hpp" 9#include "strata/kernels/dflash2.hpp" 10#include "strata/core/remote_expert_opt.hpp" 11#include "strata/core/dma_batch.hpp" 12#include "strata/workload_trace.hpp" 13#if defined(_WIN32 ) 14#include <intrin.h> 15#endif 16 17#include "strata/core/native_head.hpp" 18#include "strata/core/on_device.hpp" 19#include "strata/core/peer_experts.hpp" 20#include "strata/kernels/iq_kernels.hpp" 21#include "strata/kernels/expert_staging.hpp" 22#include "strata/kernels/cpu/expert_layout.hpp" 23#include "strata/kernels/cpu/hadamard.hpp" 24#include "strata/kernels/bf16_gemv.hpp" 25#include "strata/kernels/native_router.hpp" 26#include "strata/kernels/native_moe.hpp" 27#include "strata/kernels/cpu/expert.hpp" 28#include "strata/kernels/elementwise.hpp" 29#include "strata/kernels/fused_gr.hpp" 30#include "strata/kernels/cvec.hpp" 31#include "strata/kernels/gr.hpp" 32#include "strata/kernels/kv_q4.hpp" 33#include "strata/kernels/kv_q8.hpp" 34#include "strata/kernels/native_mmvq.hpp" 35#include "strata/kernels/native_qsa.hpp" 36#include "strata/kernels/native_qsa_indexer.hpp" 37#include "strata/kernels/native_rope.hpp" 38#include "strata/kernels/ngram.hpp" 39#include "strata/kernels/ple.hpp" 40#include "strata/kernels/qsa.hpp" 41#include "strata/kernels/qsa_decode_attn.hpp" 42#include "strata/kernels/qsa_select.hpp" 43#include "strata/kernels/quantize_act.hpp" 44#include "strata/kernels/rope.hpp" 45#include "strata/kernels/s2_expert_grouped.hpp" 46#include "strata/kernels/sampler.hpp" 47#include "strata/core/progress.hpp" 48#include "strata/kernels/shared_expert.hpp" 49#include "strata/kernels/verify_kernels.hpp" 50 51#include <algorithm> 52#include <atomic> 53#include <filesystem> 54#include <map> 55#include <memory> 56#include <string> 57#include <thread> 58#include <vector> 59#include <chrono> 60#include <cmath> 61#include <cstdio> 62#include <cstdlib> 63#include <cstring> 64#include <exception> 65#include <immintrin.h> 66#if defined(__linux__ ) 67#include <pthread.h> 68#include <sched.h> 69#endif 70 71namespace strata::core { 72namespace { 73bool sycl_mirror_adapt () { 74static const bool enabled = [] { 75const char * v = std::getenv ("STRATA_SYCL_MIRROR_ADAPT" ); 76return v && v [0 ]== '1' ; 77 }(); 78return enabled ; 79} 80class ExpertRouteCount ; 81void count_expert_routes (sycl::queue * q ,const int32_t * ids ,int entries , 82int layer ,int experts ,uint32_t * counts ) { 83q -> parallel_for < ExpertRouteCount > ( 84 sycl::nd_range < 1 > ((entries + 31 ) /32 * 32 ,32 ), 85 [= ](sycl::nd_item < 1 > item ) [[sycl ::reqd_sub_group_size (32 )]] { 86const int i = (int )item .get_global_id (0 ); 87if (i < entries ) { 88const int expert = ids [i ]; 89if (expert >=0 && expert < experts ) { 90 sycl::atomic_ref < uint32_t , sycl::memory_order::relaxed , 91 sycl::memory_scope::device , sycl::access::address_space::global_space > 92count (counts [layer * experts + expert ]); 93count .fetch_add (1 ); 94 } 95 } 96 }); 97} 98 99#ifdef STRATA_SYCL_WORKLOAD_TRACE 100// Diagnostic graph copies preserve the actual per-layer plan before its shared 101// scratch is reused. CPU reads them only after the existing end-window wait. 102struct RoutingAudit { 103int32_t * snapshots = nullptr ; 104FILE * output = nullptr ; 105int64_t words = 0 ,layers = 0 ; 106 sycl::queue * queue = nullptr ; 107RoutingAudit (int64_t nwords ,int64_t nlayers , sycl::queue * stream ,const char * path ) 108 :words (nwords ),layers (nlayers ),queue (stream ) { 109output = std::fopen (path ,"a" ); 110if (!output )throw std::runtime_error ("routing audit output unavailable" ); 111snapshots = sycl::malloc_host < int32_t > ((size_t )words * layers * 2 ,* queue ); 112if (!snapshots ) { std::fclose (output );output = nullptr ;throw std::bad_alloc (); } 113 std::memset (snapshots ,0 , (size_t )words * layers * 2 * sizeof (int32_t )); 114 } 115 ~RoutingAudit () { 116if (snapshots ) {try { sycl::free (snapshots ,* queue ); }catch (...) {} } 117if (output ) std::fclose (output ); 118 } 119int32_t * slot (int64_t layer ,int group ) {return snapshots + (size_t )(layer * 2 + group )* words ; } 120}; 121std::map < const Verifier * , std::unique_ptr < RoutingAudit >> routing_audits ; 122#endif 123 124constexpr float EPS = 1e-6f ; 125using Clock = std::chrono::steady_clock ; 126double ms_since (Clock ::time_point t ) {return std::chrono::duration < double , std::milli > (Clock ::now ()- t ).count (); } 127const bool g_dbg = std::getenv ("STRATA_VERIFY_DEBUG" )!= nullptr ; 128inline bool g_lfuse () {static const bool on = [] {const char * v = std::getenv ("STRATA_LFUSE" );return v != nullptr && v [0 ]== '1' ; }();return on ; } 129inline bool g_lfuse_gate () {static const bool on = [] {const char * v = std::getenv ("STRATA_LFUSE_GATE" );return v == nullptr || v [0 ]!= '0' ; }();return on ; } 130inline bool g_lfuse_pair () {static const bool on = [] {const char * v = std::getenv ("STRATA_LFUSE_PAIR" );return v == nullptr || v [0 ]!= '0' ; }();return on ; } 131inline bool g_qdedup () {static const bool on = [] {const char * v = std::getenv ("STRATA_VERIFY_QDEDUP" );return v != nullptr && std::atoi (v )!= 0 ; }();return on ; } 132// S26 STRATA_QFUSE=1: activation q8_1 images written by their producers (the GDN output norm) - the same bytes 133inline bool g_qfuse () {static const bool on = [] {const char * v = std::getenv ("STRATA_QFUSE" );return v != nullptr && std::atoi (v )!= 0 ; }();return on ; } 134#define VDBG (...) do { if (g_dbg) { std::fprintf(stderr, "verify dbg: " __VA_ARGS__); std::fflush(stderr); } } while (0) 135 136struct Bump { 137uint8_t * base = nullptr ; 138uint64_t used = 0 ; 139template < typename T > T * take (uint64_t n ) { 140T * p = base ? (T * ) (base + used ) :nullptr ; 141used += (n * sizeof (T )+ 255 )& ~255ull ; 142return p ; 143 } 144}; 145 146// #649 (HIP, opt-in A/Bs for the gfx1030 verify timeouts; CUDA never reads them) 147// STRATA_VERIFY_COHERENT=1 the handshake words and rows in explicitly coherent (fine-grained) host memory 148// STRATA_DOORBELL_STORE=1 the GPU stores each step's ring instead of read-modify-writing it over PCIe 149bool env_on (const char * name ) { 150const char * e = std::getenv (name ); 151return e != nullptr && e [0 ]!= 0 && e [0 ]!= '0' ; 152} 153 154// STRATA_LAYER_HASH_FILE=<path> (debug, off by default): after every CPU-expert service the host writes one text line 155// "window layer rows xhash idshash whash yhash" (FNV-1a over the host-visible payload the GPU published for the CPU 156// experts - the activation rows, the routed ids, the weights - and over the CPU experts' output rows). Two runs of the 157// same teacher-forced window are compared line by line: the first line that differs names the first layer whose input 158// differs (CLEAN-6.0). The activation rows are published only when a routed expert is not resident, or with 159// STRATA_DOORBELL_CHECK=1 for every layer. 160std::FILE * layer_hash_file () { 161static std::FILE * f = [] { 162const char * p = std::getenv ("STRATA_LAYER_HASH_FILE" ); 163return p != nullptr && p [0 ]!= 0 ? std::fopen (p ,"w" ) :nullptr ; 164 }(); 165return f ; 166} 167uint64_t layer_hash_fnv (const void * p ,size_t bytes ) { 168uint64_t h = 1469598103934665603ull ; 169const auto * b = static_cast < const uint8_t *> (p ); 170for (size_t i = 0 ;i < bytes ;++ i )h = (h ^b [i ])* 1099511628211ull ; 171return h ; 172} 173 174// STRATA_STATE_HASH_FILE=<path> (debug, off by default): before every window the host waits for the queue and writes 175// "window gdn <ordinal> <fnv>" for every GDN layer's recurrent+conv state and "window qsa <ordinal> <fnv>" for the 176// int8 K/V codes and scales of the pages the window's position already filled (page table taken as the identity), 177// so two runs can be compared at the first window to see whether the prompt path left the same state (CLEAN-6.0). 178std::FILE * state_hash_file () { 179static std::FILE * f = [] { 180const char * p = std::getenv ("STRATA_STATE_HASH_FILE" ); 181return p != nullptr && p [0 ]!= 0 ? std::fopen (p ,"w" ) :nullptr ; 182 }(); 183return f ; 184} 185#if defined(STRATA_USE_HIP ) 186const bool g_coherent = env_on ("STRATA_VERIFY_COHERENT" ); 187const bool g_doorbell_store = env_on ("STRATA_DOORBELL_STORE" ); 188#endif 189const bool g_trace = env_on ("STRATA_VERIFY_TRACE" ); 190// STRATA_VERIFY_STEPPED=1 (opt-in, Arc A-series): see Verifier::step_hook_. STRATA_VERIFY_PIPE=0 serves without the 191// helper thread (serial segments) for A/B runs. 192const bool g_stepped = env_on ("STRATA_VERIFY_STEPPED" ); 193 194// STRATA_PIPE_HELPER_SIBLING=1 (opt-in, stepped mode): the host thread is pinned to one logical CPU and a std::thread 195// inherits that mask, so the pipelined serve's pool helper and the main thread's flag-A wait share one CPU and the 196// early segment is mostly submitted only after the pool finished. With this set the helper runs on the host CPU's SMT 197// sibling instead. -1: keep the inherited mask (unset, not pinned to one CPU, or no sibling). 198int pipe_helper_cpu () { 199#if defined(__linux__ ) 200static const int cpu = [] { 201if (!env_on ("STRATA_PIPE_HELPER_SIBLING" ))return -1 ; 202cpu_set_t s ; 203CPU_ZERO (& s ); 204if (pthread_getaffinity_np (pthread_self (),sizeof s ,& s )!= 0 || CPU_COUNT (& s )!= 1 ) { 205 std::fprintf (stderr ,"strata verify: STRATA_PIPE_HELPER_SIBLING: host thread is not pinned to one CPU; unchanged\n" ); 206return -1 ; 207 } 208int host = -1 ; 209for (int c = 0 ;c < CPU_SETSIZE && host < 0 ;++ c ) 210if (CPU_ISSET (c ,& s ))host = c ; 211char path [96 ]; 212 std::snprintf (path ,sizeof path ,"/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list" ,host ); 213int sib = -1 ; 214if (FILE * f = std::fopen (path ,"r" )) { 215char buf [128 ]= {}; 216if (std::fgets (buf ,sizeof buf ,f )!= nullptr ) { 217for (char * p = buf ;* p != 0 && sib < 0 ;) {// "0,8" or "0-1" 218char * end = nullptr ; 219const long a = std::strtol (p ,& end ,10 ); 220if (end == p )break ; 221long b = a ; 222if (* end == '-' ) {p = end + 1 ;b = std::strtol (p ,& end ,10 ); } 223for (long c = a ;c <=b && sib < 0 ;++ c ) 224if (c != host )sib = (int )c ; 225p = (* end == ',' ) ?end + 1 :end ; 226if (* end != ',' )break ; 227 } 228 } 229 std::fclose (f ); 230 } 231 std::fprintf (stderr ,"strata verify: pipelined pool helper on CPU %d (host thread CPU %d)%s\n" ,sib ,host , 232sib < 0 ?": no SMT sibling, unchanged" :"" ); 233return sib ; 234 }(); 235return cpu ; 236#else 237return -1 ; 238#endif 239} 240const bool g_no_multi_gr = env_on ("STRATA_NO_MULTI_GR" );// #783 PR-g: per-token GR reads/writes and generic-T kernels again 241const bool g_no_batch_kv = env_on ("STRATA_NO_BATCH_KV_STEP" );// #783 PR-d: per-token K/V and indexer appends again 242 243// The shared expert runs on its own stream, forked off and joined back per layer (`sh_fork` in record_window). The 244// overlap pays off on CUDA, where it was added (cfd3b72). On HIP a cross-stream event dependency costs more than the 245// shared expert takes to run, so there the fork starts off: same binary, same 48,067-token prompt, three runs each on a 246// 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 247// profiler turns the fork off to time the stages, so a profiled run never showed that. #816 reports the same fall on a 248// gfx1030 (RX 6800, Windows, 42.5 -> 56.4 t/s). STRATA_SH_STREAM overrides either default: `=1` forks, `=0` does not. 249// Strix Halo (gfx1151, unified memory) is the exception: the fork pays there (+1.8% UD-IQ4_XS, +6.7% UD-Q4_K_XL decode 250// at 8K, ids identical), so the gfx1151 arch table sets STRATA_SH_STREAM=1. Read on first use, after that table ran. 251bool sh_stream_on () { 252static const bool on = [] { 253if (const char * v = std::getenv ("STRATA_SH_STREAM" ))return v [0 ]!= '0' ; 254#if defined(STRATA_USE_HIP ) 255return false; 256#else 257return true; 258#endif 259 }(); 260return on ; 261} 262 263// A one-token window always keeps its token, so its graph advances the sequence state itself (the GDN conv history 264// and recurrence state) and Verifier::commit launches no commit graph after it (eddoursul's fork, F7). CUDA only: 265// HIP keeps the commit graph after every window (STRATA_ONE_TOKEN_COMMIT=0 does too). 266// The head's hyper-connection read for the window's tokens in one launch set (CUDA; HIP keeps gr_read per token; 267// STRATA_HEAD_MIX_MULTI=0 does too): bitwise the same sums. 268bool head_mix_multi_enabled () { 269#if defined(STRATA_USE_HIP ) 270return false; 271#else 272static const bool on = [] { 273const char * v = std::getenv ("STRATA_HEAD_MIX_MULTI" ); 274return v == nullptr || std::atoi (v )!= 0 ; 275 }(); 276return on ; 277#endif 278} 279 280bool one_token_self_commit () { 281#if defined(STRATA_USE_HIP ) 282return false; 283#else 284static const bool on = [] { 285const char * v = std::getenv ("STRATA_ONE_TOKEN_COMMIT" ); 286return v == nullptr || std::atoi (v )!= 0 ; 287 }(); 288return on ; 289#endif 290} 291 292// True when the GPU runs under the i915 kernel driver (Arc Alchemist: A310-A770), read from sysfs. 293bool intel_i915_gpu () {return strata::intel_gpu_driver ()== "i915" ; } 294 295// How long the host waits for a layer's doorbell before it gives the window up (#267). 20 s by default; the first 296// window of a run on a card that JIT-compiles its kernels (no AOT: an Arc A750 needs FP64 emulation) can take longer 297// to start, so STRATA_RING_TIMEOUT_S raises it. 298std::chrono::seconds strata_ring_timeout () { 299static const long s = [] { 300const char * v = std::getenv ("STRATA_RING_TIMEOUT_S" ); 301const long n = v ? std::atol (v ) :20 ; 302return n >=1 ?n :20L ; 303 }(); 304return std::chrono::seconds (s ); 305} 306 307// STRATA_VERIFY_STEPPED: no kernel of the window reads a host store while it runs, and no host reads a kernel's store 308// while it runs - every flag is raised before the segment that waits on it is submitted, and the host reads a 309// segment's rings and payload after the segment drained. So the window's mapped buffers need no uncached host memory 310// (sycl_queue.hpp) and its doorbell publishes need no uncached payload stores (sycl_doorbell.hpp). Both cost the 311// window time on an A770 (xe, Coder IQ1_M, 8K prompt): the GPU waited ~70 ms a window for the CPU with them, ~42 312// without; decode 22.8-25.0 -> 26.9-28.9 tok/s. STRATA_VERIFY_HOST_UNCACHED=1 keeps both. 313bool window_host_uncached () { 314static const bool v = !g_stepped || env_on ("STRATA_VERIFY_HOST_UNCACHED" ); 315return v ; 316} 317 318bool mapped (size_t bytes ,void ** h ,void ** d )try { 319/* 320DPCT1048: The original value cudaHostAllocMapped is not meaningful in the 321migrated code and was removed or replaced with 0. You may need to check the 322migrated code. 323*/ 324// polled by the window's kernels: uncached host memory (sycl_queue.hpp); a buffer only read or written between 325// kernels (the stepped window's payload) is ordinary host USM 326if (DPCT_CHECK_ERROR (* h = window_host_uncached () ? strata::host_malloc_polled (bytes , dpct::get_in_order_queue ()) 327 : sycl::malloc_host (bytes , dpct::get_in_order_queue ()))!= 3280 || * h == nullptr )return false; 329 std::memset (* h ,0 ,bytes ); 330return DPCT_CHECK_ERROR (* d = (void * )* h )== 0 ; 331} 332catch (sycl::exception const & exc ) { 333 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 334 <<", line:" <<__LINE__ << std::endl ; 335 std::exit (1 ); 336} 337 338strata::kernels::QsaShapes shapes_of (const ModelGeometry & g ) {return qsa_shapes (g ); } 339 340const WeightRef * need (const LayerView & v ,const char * suffix , std::string & err ) { 341const WeightRef * r = v .get (suffix ); 342if (r == nullptr && err .empty ())err = v .name (suffix )+ " is missing" ; 343return r ; 344} 345 346bool native_of (const WeightRef * w ,const std::string & name , std::string & err ) { 347if (w == nullptr )return false; 348if (w -> native_data == nullptr ) { 349err = "verify: " + name + " is not served natively (run with --native)" ; 350return false; 351 } 352return true; 353} 354 355}// namespace 356 357namespace { 358std::atomic < const Verifier *> g_diag_verifier {nullptr }; 359void diag_active_verifier (std::FILE * f ) { 360if (const Verifier * v = g_diag_verifier .load ())v -> diag (f ); 361} 362// #267: every live verifier (a layer split has one per stage), for the release before the engine ends 363constexpr int kLiveMax = 16 ; 364std::atomic < Verifier *> g_live [kLiveMax ]; 365void release_live_verifiers (std::FILE * f ) { 366for (auto & slot :g_live ) 367if (Verifier * v = slot .load ()) { 368const Clock ::time_point t0 = Clock ::now (); 369const bool done = v -> release_gpu_waits (5000 ); 370if (f != nullptr ) 371 std::fprintf (f ,"strata: released the verify window's GPU waits (#267): the GPU %s\n" , 372done ? ("finished in " + std::to_string ((long long )ms_since (t0 ))+ " ms" ).c_str () 373 :"did not finish within 5 s" ); 374 } 375if (f != nullptr ) std::fflush (f ); 376} 377// #649: the host side of STRATA_VERIFY_TRACE - a ring of the last kTraceN handshake events of every verifier 378struct TraceEv { 379int64_t t_ns ; 380const void * who ; 381int64_t window ,step ,layer ,aux ; 382uint32_t seq ,flag ,a ,b ; 383const char * what ; 384}; 385constexpr uint64_t kTraceN = 4096 ; 386TraceEv g_trace_ring [kTraceN ]; 387std::atomic < uint64_t > g_trace_next {0 }; 388int64_t trace_now_ns () { 389return std::chrono::duration_cast < std::chrono::nanoseconds > (Clock ::now ().time_since_epoch ()).count (); 390} 391std::string released_note (bool drained ) { 392return drained ?"; its GPU waits were released and the GPU finished (#267)" 393 :"; its GPU waits were released but the GPU did not finish within 5 s (#267)" ; 394} 395// #267 test hook: STRATA_TEST_VERIFY_STALL=N withholds the last layer's flag in the N-th window (1-based), so the 396// GPU spins on a flag nobody raises - the bounded window wait and the release are then what ends it. Unset: never. 397const int64_t g_test_stall = [] { 398const char * e = std::getenv ("STRATA_TEST_VERIFY_STALL" ); 399return e != nullptr ? (int64_t ) std::atoll (e ) : (int64_t )0 ; 400}(); 401}// namespace 402 403bool Verifier ::release_gpu_waits (int timeout_ms )try { 404released_ .store (true); 405trace_ev ("RELEASE" ,-1 ,-1 ,timeout_ms ); 406// the words the spin kernels read (wait_flag_ge, wait_flag_ge_or) are mapped host memory, so a store here 407// reaches them with no API call; UINT32_MAX is past every ring. (E-6's skip words are device memory, but 408// wait_flag_ge_or also returns on its flag.) A host function raising flag B later only raises. 409for (uint32_t * p : {h_flag_ ,h_flagA_ ,h_flagB_ }) 410if (p != nullptr )* (volatile uint32_t * )p = UINT32_MAX ; 411 std::atomic_thread_fence (std::memory_order_seq_cst ); 412_mm_sfence (); 413const OnDevice on_device (device_ ); 414const Clock ::time_point t0 = Clock ::now (); 415// SYCL port: no cudaStreamQuery; a queue with nothing left to run reports ext_oneapi_empty() 416for (dpct::queue_ptr q : {cs_ ,copy_ }) { 417if (q == nullptr )continue ; 418while (!q -> ext_oneapi_empty ()) { 419if (ms_since (t0 )> timeout_ms ) { 420trace_ev ("RELEASE-NOT-DRAINED" ,-1 ,-1 , (int64_t )ms_since (t0 )); 421return false; 422 } 423 std::this_thread::sleep_for (std::chrono::milliseconds (1 )); 424 } 425 } 426trace_ev ("RELEASE-DRAINED" ,-1 ,-1 , (int64_t )ms_since (t0 ));// aux: ms the GPU took to finish once released 427return true; 428}catch (...) { 429return false;// the runtime may already be tearing down (the watchdog's path ends the engine) 430} 431 432void Verifier ::trace_ev (const char * what ,int64_t step ,int64_t layer ,int64_t aux )const { 433if (!g_trace )return ; 434auto rd = [](const uint32_t * p ) {return p ?* (const volatile uint32_t * )p :0u ; }; 435TraceEv & e = g_trace_ring [g_trace_next .fetch_add (1 ) %kTraceN ]; 436e = {trace_now_ns (),this ,windows ,step ,layer ,aux ,rd (h_seq_ ),rd (h_flag_ ),rd (h_flagA_ ),rd (h_flagB_ ),what }; 437} 438 439void Verifier ::trace_dump (std::FILE * f )const { 440if (!g_trace || f == nullptr )return ; 441static const char * names [kProfPer ]= {"pre" ,"hc-read0" ,"qkv gemv" ,"conv" ,"ab" ,"z" ,"rec" ,"kv-idx" , 442"k/v rope" ,"kv append" ,"q" ,"scores+topk" ,"kv-resolve" ,"attention" , 443"gate" ,"" ,"out-proj" ,"router+ring" ,"shared" ,"waitA" ,"VRAM hits" ,"waitB" , 444"PCIe grp" ,"waitCPU" ,"combine" ,"" ,"head" ,"" ,"" ,"" ,"" ,"" ,"" }; 445const uint64_t end = g_trace_next .load (); 446const uint64_t n = end < 160 ?end :160 ; 447 std::fprintf (f ,"strata verify trace (#649): the last %llu handshake events (host clock, us before the last; " 448"words: seq = GPU rang, flag = CPU served, A = plan, B = copies)\n" , (unsigned long long )n ); 449const int64_t t_last = n ?g_trace_ring [(end - 1 ) %kTraceN ].t_ns :0 ; 450for (uint64_t i = end - n ;i < end ;++ i ) { 451const TraceEv & e = g_trace_ring [i %kTraceN ]; 452if (e .what == nullptr )continue ; 453 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" , 454 (double ) (t_last - e .t_ns ) /1000.0 ,e .what ,e .who , (long long )e .window , (long long )e .step , 455 (long long )e .layer , (long long )e .aux ,e .seq ,e .flag ,e .a ,e .b ); 456 } 457if (trace_h_ == nullptr || g_ == nullptr )return ; 458// the breadcrumbs: every stamp point the GPU passed in this window (ns of the GPU clock after the window's first) 459unsigned long long t0 = ~0ull ; 460for (size_t i = 0 ;i < trace_n_ ;++ i ) { 461const unsigned long long t = * (const volatile unsigned long long * ) (trace_h_ + i ); 462if (t != 0 && t < t0 )t0 = t ; 463 } 464if (t0 == ~0ull ) { 465 std::fprintf (f ,"strata verify trace: no GPU breadcrumb in this window (the GPU never started it)\n" ); 466return ; 467 } 468int64_t last_l = -1 ; 469for (int64_t l = 0 ;l <=g_ -> n_layers ;++ l ) 470for (int i = 0 ;i < kProfPer ;++ i ) 471for (int grp = 0 ;grp < 2 ;++ grp ) 472if (trace_h_ [(size_t ) ((l * kProfPer + i )* 2 + grp )]!= 0 )last_l = l ; 473 std::fprintf (f ,"strata verify trace: GPU breadcrumbs (us after the window's first), the GPU got as far as layer " 474"%lld:\n" , (long long )last_l ); 475for (int64_t l = std::max < int64_t > (0 ,last_l - 2 );l <= std::min < int64_t > (g_ -> n_layers ,last_l + 1 );++ l ) 476for (int grp = 0 ;grp < 2 ;++ grp ) { 477 std::string line ; 478char b [64 ]; 479for (int i = 0 ;i < kProfPer ;++ i ) { 480const unsigned long long t = trace_h_ [(size_t ) ((l * kProfPer + i )* 2 + grp )]; 481if (t == 0 )continue ; 482 std::snprintf (b ,sizeof b ," %s(%d)=%.1f" ,names [i ],i , (double ) (t - t0 ) /1000.0 ); 483line += b ; 484 } 485if (!line .empty ()) 486 std::fprintf (f ," layer %lld group %d:%s\n" , (long long )l ,grp ,line .c_str ()); 487 } 488 std::fflush (f ); 489} 490 491void Verifier ::diag (std::FILE * f )const { 492auto rd = [](const uint32_t * p ) {return p ?* (const volatile uint32_t * )p :0u ; }; 493// #251: outside a verify stage these are the LAST window's numbers (it finished), not the stalled work's 494const char * where = progress ().where .load (); 495const bool current = where != nullptr && std::strncmp (where ,"verify window" ,13 )== 0 ; 496 std::fprintf (f ," verify window%s: %d tokens at position %lld, host at layer step %u; the GPU rang %u; flags: " 497"served %u, plan (A) %u, copies (B) %u\n" ,current ?"" :" (last window, not the current stage)" , 498last_t_ , (long long )last_pos0_ ,cur_layer_ + 1 ,rd (h_seq_ ),rd (h_flag_ ),rd (h_flagA_ ),rd (h_flagB_ )); 499trace_dump (f );// #649: STRATA_VERIFY_TRACE=1 only 500} 501 502Verifier ::~Verifier ()try { 503// SYCL port: at process exit the Level Zero context can already be gone (serve mode's end), and a destructor 504// that throws aborts the process (exit 139); the waits and frees below are best-effort then. 505const Verifier * self = this ; 506g_diag_verifier .compare_exchange_strong (self ,nullptr ); 507for (auto & slot :g_live ) { 508Verifier * me = this ; 509slot .compare_exchange_strong (me ,nullptr ); 510 } 511if (cs_ )cs_ -> wait (); 512if (slot_hist_d_ != nullptr && cs_ ) {try { sycl::free (slot_hist_d_ ,* cs_ ); }catch (...) {}slot_hist_d_ = nullptr ; } 513if (sh_cs_ )sh_cs_ -> wait (); 514for (auto & e :exec_ ) 515if (e )delete (e ); 516for (auto & e :exec_nr_ ) 517if (e )delete (e ); 518for (auto & v :seg_ ) 519for (auto * e :v ) 520if (e )delete e ; 521if (commit_exec_ )delete (commit_exec_ ); 522#ifdef STRATA_SYCL_WORKLOAD_TRACE 523routing_audits .erase (this ); 524#endif 525if (expert_usage_counts_d_ ) sycl::free (expert_usage_counts_d_ ,* cs_ ); 526for (auto & kv :exec_bm_ ) 527if (kv .second )delete (kv .second ); 528for (auto & kv :commit_bm_ ) 529if (kv .second )delete (kv .second ); 530if (arena_b_ ) sycl::free (arena_b_ , dpct::get_in_order_queue ()); 531if (h_commitb_ ) sycl::free (h_commitb_ , dpct::get_in_order_queue ()); 532if (qcnt_ ) sycl::free (qcnt_ , dpct::get_in_order_queue ()); 533// (a verifier whose init stopped before it made its own queues still holds the process's default queue in all three (cs_, sh_cs_, copy_): that one is never ours to destroy - 534// destroying it took the next verifier's wait down with a SIGSEGV in urQueueFinish when a start was refused for lack of VRAM) 535if (cs_ && cs_ != ext_stream_ && cs_ != & dpct::get_in_order_queue ()) dpct::get_current_device ().destroy_queue ( 536cs_ );// set_stream: the stage's stream, shared, not ours 537if (sh_cs_ && sh_cs_ != cs_ && sh_cs_ != & dpct::get_in_order_queue ()) dpct::get_current_device ().destroy_queue (sh_cs_ ); 538if (copy_ ) {copy_ -> wait ();if (copy_ != & dpct::get_in_order_queue ()) dpct::get_current_device ().destroy_queue (copy_ ); }// (the default one when init never made the copy stream) 539if (commit_done_ ) dpct::destroy_event (commit_done_ ); 540if (ev_done_ ) dpct::destroy_event (ev_done_ ); 541if (ev_commit_ ) dpct::destroy_event (ev_commit_ ); 542if (prof_pin_ ) sycl::free (prof_pin_ , dpct::get_in_order_queue ()); 543if (ev_fork_ ) dpct::destroy_event (ev_fork_ ); 544if (ev_join_ ) dpct::destroy_event (ev_join_ ); 545if (tap_dev_ ) sycl::free (tap_dev_ , dpct::get_in_order_queue ()); 546if (arena_ ) sycl::free (arena_ , dpct::get_in_order_queue ()); 547void * 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_ , 548h_flagA_ ,h_plan_ ,h_flagB_ ,h_plan_err_ }; 549for (void * h :hosts ) 550if (h ) strata::host_free_polled (h , dpct::get_in_order_queue ()); 551}catch (...) { 552} 553 554 555bool Verifier ::init (const WeightTable & wt ,const ModelGeometry & g , 556SessionState & ss ,const VerifyHits & hits , 557const NativeHead * head ,int max_t , std::string & err )try { 558g_diag_verifier .store (this ); 559diag_verify_fn ().store (& diag_active_verifier ); 560for (auto & slot :g_live ) { 561Verifier * none = nullptr ; 562if (slot .load ()== this || slot .compare_exchange_strong (none ,this ))break ; 563 } 564release_gpu_fn ().store (& release_live_verifiers ); 565device_ = dpct::get_current_device_id ();// a layer split's stage on another 566// GPU: its streams, graphs and 567// buffers live there 568 strata::kernels::fused_gr_check ();// once per card: which bitwise-equal hyper-connection read runs there 569wt_ = & wt ; 570g_ = & g ; 571ss_ = & ss ; 572hits_ = hits ; 573head_ = head ; 574max_t_ = max_t ; 575sampling_ .greedy = true;// a fresh verifier samples greedily until set_sampling says otherwise 576sampling_ .temperature = 0.0f ; 577if (max_t < 2 || max_t > strata::kernels::kVerifyMaxT || max_t > strata::kernels::cpu::MAXT ) { 578err = "verify: the window must hold 2.." + std::to_string (strata::kernels::kVerifyMaxT )+ " tokens" ; 579return false; 580 } 581if (hits .d_res == nullptr || hits .cache_base == nullptr || hits .blob <=0 ) { 582err = "verify: needs the profile-filled VRAM expert tier (--expert-profile and --expert-cache); with " 583"--expert-cache auto, no VRAM was left for it - the 'no VRAM is left for the expert cache' line above " 584"says how much is short and what makes room (a smaller --max-context, --kv q4_0, setup --draft-vocab en, " 585"images on the CPU)" ; 586return false; 587 } 588 std::string why ; 589if (!layer_verify_compatible (why )) { 590err = "verify: " + why + " (the verify window reproduces the default native decode path)" ; 591return false; 592 } 593if (!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 || 594g .ssm_d_conv != 4 ) { 595err = "verify: geometry differs from the artifact's" ; 596return false; 597 } 598if (le_ < 0 )le_ = g .n_layers ; 599if (lb_ < 0 || lb_ >=le_ || le_ > g .n_layers || (lb_ > 0 && hand_in_ == nullptr )|| 600 (le_ < g .n_layers && hand_out_ == nullptr )) { 601err = "verify: the stage's layer range or its hand-off buffers are wrong" ; 602return false; 603 } 604const WeightRef * wo = wt .find ("output.weight" ); 605if (wo == nullptr ) {err = "verify: output.weight is missing" ;return false; } 606n_vocab_ = wo -> ne1 ; 607 608const strata::kernels::QsaShapes s = shapes_of (g ); 609cap_ = strata::kernels::qsa_selection_width (strata::kernels::kTopkMaxCells ,s ); 610max_blocks_ = ss .qsa_states [ss .qsa_primary ()].max_cells /s .idx_block + 2 ; 611attn_scratch_floats_ = (int64_t ) strata::kernels::qsa_decode_attn_scratch_floats (cap_ ,s ); 612 613const uint64_t T = (uint64_t )max_t ,N = (uint64_t )g .n_embd ,HC = (uint64_t )g .hc ,K = (uint64_t )ss .k ; 614const uint64_t C = (uint64_t )g .ssm_conv_channels ,ZV = (uint64_t )g .ssm_value_dim ,HV = (uint64_t )g .ssm_v_heads ; 615const uint64_t NH = (uint64_t )g .n_head ,HD = (uint64_t )g .head_dim ,NKV = (uint64_t )g .n_head_kv ; 616const uint64_t IQ = (uint64_t )g .idx_q_heads ,ID = (uint64_t )g .idx_key_dim ; 617const uint64_t nG = (uint64_t )g .n_gdn_layers (),nQ = (uint64_t )g .n_qsa_layers (); 618const uint64_t HS = (uint64_t ) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM ; 619const uint64_t TS = (uint64_t ) (s .idx_block - 1 )* ID ; 620const int max_in = (int ) std::max < uint64_t > (std::max < uint64_t > (N ,ZV ),NH * HD ); 621 622// ---- mapped staging 623bool ok = mapped (T * 4 , (void ** )& h_tok_ , (void ** )& m_tok_ )&& 624mapped (T * strata::kernels::kStepCount * 4 , (void ** )& h_step_ , (void ** )& m_step_ )&& 625mapped (T * (NH + NKV + IQ )* 4 , (void ** )& h_pos_ , (void ** )& m_pos_ )&& 626mapped ((2 + T )* 4 + 16 , (void ** )& h_commit_ , (void ** )& m_commit_ )&& 627mapped (T * N * 4 , (void ** )& h_ple_ , (void ** )& m_ple_ )&& 628mapped (T * 4 + 16 , (void ** )& h_out_ , (void ** )& m_out_ )&& 629mapped (T * N * 4 , (void ** )& h_x_ , (void ** )& m_x_ )&& 630mapped (T * K * 4 , (void ** )& h_ids_ , (void ** )& m_ids_ )&& 631mapped (T * K * 4 , (void ** )& h_w_ , (void ** )& m_w_ )&& 632mapped (64 , (void ** )& h_seq_ , (void ** )& m_seq_ )&& 633mapped (64 , (void ** )& h_flag_ , (void ** )& m_flag_ )&& 634mapped (64 , (void ** )& h_flagA_ , (void ** )& m_flagA_ )&& 635mapped (64 , (void ** )& h_flagB_ , (void ** )& m_flagB_ )&& 636mapped (64 , (void ** )& h_plan_err_ , (void ** )& m_plan_err_ )&& 637mapped (T * K * N * 4 , (void ** )& h_ymiss_ , (void ** )& m_ymiss_ ); 638if (!ok ) {err = "verify: mapped staging allocation failed" ;return false; } 639// DFlash2 taps (set_taps): off, and nothing is allocated or recorded, otherwise 640if (!tap_req_ .empty ()&& lb_ == 0 && le_ == g .n_layers ) { 641tap_layers_ .clear (); 642for (int l :tap_req_ )if (l >=0 && l < g .n_layers - 1 )tap_layers_ .push_back (l ); 643tap_slot_ .assign ((size_t )g .n_layers ,-1 ); 644for (size_t i = 0 ;i < tap_layers_ .size ();++ i )tap_slot_ [(size_t )tap_layers_ [i ]]= (int )i ; 645const size_t nt = tap_layers_ .size (); 646if (nt == 0 || (tap_dev_ = sycl::malloc_device < float > ((size_t )T * nt * N , dpct::get_in_order_queue ()))== nullptr ) { 647err = "verify: the DFlash2 tap buffers could not be allocated" ; 648return false; 649 } 650tap_on_ = true; 651 } 652// the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1) 653 { 654const int64_t cap = (int64_t ) (T * K ); 655const int64_t i32 = 4 + (cap + 1 )+ cap + cap ; 656const int64_t ptr_off = (i32 + 1 )& ~1ll ; 657plan_i32_ = ptr_off + 4 * cap + (cap + 1 )+ 1 ; 658if (!mapped ((size_t )plan_i32_ * 4 * 2 + 64 , (void ** )& h_plan_ , (void ** )& m_plan_ )) { 659err = "verify: mapped plan allocation failed" ; 660return false; 661 } 662sink_ .counts = h_plan_ ; 663sink_ .start = h_plan_ + 4 ; 664sink_ .dst = sink_ .start + cap + 1 ; 665sink_ .tok = sink_ .dst + cap ; 666sink_ .ptr = (unsigned long long * ) (h_plan_ + ptr_off ); 667sink_ .ptr2 = sink_ .ptr + cap ; 668sink_ .start2 = h_plan_ + ptr_off + 4 * cap ; 669sink_ .cap = cap ; 670sink_ .publish = & Verifier ::publish_plan ; 671sink_ .fetch = & Verifier ::fetch_dma ; 672sink_ .ctx = this ; 673 } 674 675// APR: the rotated copy of the expert input (nat_xr_, T x N floats) only where a layer's gate/up is 676// Hadamard-folded; its one reader is that layer's f.had_gu branch in the expert-input step below 677bool had_gu_any = false; 678 { 679const auto & lay = strata::kernels::cpu::expert_layout (); 680for (size_t l = 0 ;lay .native && l < lay .fmt .size ();++ l )had_gu_any = had_gu_any || lay .fmt [l ].had_gu ; 681 } 682// ---- the device arena: the same sequence counted, then carved 683auto carve = [& ](Bump & b ) { 684tok_ = b .take < int32_t > (T );step_ = b .take < int32_t > (T * strata::kernels::kStepCount ); 685pos_ = b .take < int32_t > (T * (NH + NKV + IQ ));commit_ = b .take < int32_t > (2 + T ); 686ple_ = b .take < float > (T * N );emb_ = b .take < float > (T * N );R_ = b .take < float > (T * HC * N ); 687mixed_ = b .take < float > (T * N );bo_ = b .take < float > (T * N ); 688inj_ = b .take < float > (T * HC );inj2_ = b .take < float > (T * HC ); 689lo_ = b .take < float > (T * (uint64_t )g .hc_lr );rs_ = b .take < float > (T * HC );xn_ = b .take < float > (T * HC * N ); 690xq_ = b .take < uint8_t > (strata::kernels::native_q8_1_bytes (max_in , (int )T )); 691sh_xq_ = b .take < uint8_t > (strata::kernels::native_q8_1_bytes (max_in , (int )T )); 692qkv_L_ = b .take < float > (nG * T * C );h_L_ = b .take < float > (nG * T * C ); 693gate_L_ = b .take < float > (nG * T * HV );beta_L_ = b .take < float > (nG * T * HV ); 694z_ = b .take < float > (T * ZV );y_ = b .take < float > (T * ZV );y_dummy_ = b .take < float > (T * ZV ); 695qfull_ = b .take < float > (T * NH * 2 * HD );qcur_ = b .take < float > (T * NH * HD ); 696kcur_ = b .take < float > (T * NKV * HD );vcur_ = b .take < float > (T * NKV * HD ); 697idx_raw_L_ = b .take < float > (nQ * T * ID );qidx_ = b .take < float > (T * IQ * ID ); 698scores_ = b .take < float > (T * (uint64_t )max_blocks_ );sel_ = b .take < int32_t > (T * (uint64_t )cap_ ); 699attn_ = b .take < float > (T * NH * HD );attn32_ = b .take < float > (T * NH * HD ); 700attn_scratch_ = b .take < float > (T * (uint64_t )attn_scratch_floats_ ); 701tail_snap_ = b .take < float > (nQ * TS ); 702logits_ = b .take < float > (T * (uint64_t )g .n_expert );w_ = b .take < float > (T * K );ids_ = b .take < int32_t > (T * K ); 703shared_ = b .take < float > (T * N );parts_ = b .take < float > (T * K * N );hit_out_ = b .take < float > (T * K * N ); 704hit_slot_ = b .take < int32_t > (T * K );hit_dst_ = b .take < int32_t > (T * K );hit_count_ = b .take < int32_t > (4 ); 705plan_ = b .take < int32_t > (2 * ((uint64_t )plan_i32_ + 16 )); 706staging_ = b .take < uint8_t > ((uint64_t )kStagingBlobs * strata::kernels::cpu::expert_layout ().max_blob ); 707hit_xq_ = b .take < uint8_t > (T * (N /32 )* 34 );hit_xs_ = b .take < float > (T * (N /32 )); 708nat_xq_ = b .take < uint8_t > (T * (N /32 )* 36 ); 709nat_xr_ = had_gu_any ?b .take < float > (T * N ) :nullptr ; 710hit_scratch_ = b .take < uint8_t > (std::max < uint64_t > ( 711 strata::kernels::moe_hit_grouped_scratch_bytes ((int64_t ) (T * K ),g .n_embd ,g .n_ff ), 712 strata::kernels::native_expert_scratch_bytes ((int64_t ) (T * K ),g .n_ff ))); 713head_mixed_ = b .take < float > (T * N );head_inj_ = b .take < float > (HC ); 714sh_bf16_ = b .take < uint16_t > (T * N );sh_gate_ = b .take < float > (T * (uint64_t )g .n_ff ); 715sh_up_ = b .take < float > (T * (uint64_t )g .n_ff );sh_g_ = b .take < float > (T + 4 ); 716head_logits_ = b .take < float > (T * (uint64_t )n_vocab_ ); 717arg_scratch_ = b .take < uint8_t > (strata::kernels::argmax_rows_scratch_bytes ((int )T )); 718one_ = b .take < int32_t > (4 ); 719hist_snap_ = b .take < float > (T * HS ); 720ple_key_ = b .take < float > (T * (uint64_t ) strata::kernels::NG_HC_DIM );ple_val_ = b .take < float > (T * N ); 721 }; 722Bump count ; 723carve (count ); 724if (DPCT_CHECK_ERROR (arena_ = (void * )strata::malloc_device_guarded ( 725count .used , dpct::get_in_order_queue ()))!= 0 ) { 726err = "verify: the device arena (" + std::to_string (count .used >>20 )+ " MiB) does not fit" ; 727return false; 728 } 729 strata::big_fill_zero (dpct::get_in_order_queue (),arena_ ,count .used ); 730if (g_trace && trace_h_ == nullptr ) {// #649: the breadcrumbs, mapped so they read while the GPU hangs 731trace_n_ = (size_t ) (g .n_layers + 1 )* kProfPer * 2 ; 732if (!mapped (trace_n_ * 8 , (void ** )& trace_h_ , (void ** )& trace_m_ )) { 733trace_h_ = trace_m_ = nullptr ; 734trace_n_ = 0 ; 735 } 736#if defined(STRATA_USE_HIP ) 737 std::fprintf (stderr ,"strata verify trace (#649): on; coherent words %s, doorbell %s, HIP_HOST_COHERENT=%s " 738"HSA_ENABLE_SDMA=%s GPU_MAX_HW_QUEUES=%s\n" ,g_coherent ?"explicit" :"default" , 739g_doorbell_store ?"stored" :"incremented" , std::getenv ("HIP_HOST_COHERENT" ) ? std::getenv ("HIP_HOST_COHERENT" ) :"-" , 740 std::getenv ("HSA_ENABLE_SDMA" ) ? std::getenv ("HSA_ENABLE_SDMA" ) :"-" , 741 std::getenv ("GPU_MAX_HW_QUEUES" ) ? std::getenv ("GPU_MAX_HW_QUEUES" ) :"-" ); 742#else 743 std::fprintf (stderr ,"strata verify trace (#649): on\n" ); 744#endif 745 } 746prof_on_ = std::getenv ("STRATA_VERIFY_PROFILE" )!= nullptr ; 747if (prof_on_ ) { 748const size_t np = (size_t )g .n_layers * kProfPer + 4 ; 749/* 750DPCT1026: The call to cudaGetLastError was removed because this 751functionality is redundant in SYCL. 752*/ 753if (DPCT_CHECK_ERROR (prof_ = (unsigned long long * )sycl::malloc_device ( 754np * 8 , dpct::get_in_order_queue ()))!= 0 ) { 755prof_on_ = false;prof_ = nullptr ; 756 }else { 757 dpct::get_in_order_queue ().memset (prof_ ,0 ,np * 8 ).wait (); 758prof_h_ .assign (np ,0 ); 759 } 760 } 761Bump real ; 762real .base = (uint8_t * )arena_ ; 763carve (real ); 764 { 765const int32_t one = 1 ; 766if (DPCT_CHECK_ERROR (dpct::get_in_order_queue () 767 .memcpy (one_ ,& one ,sizeof one ) 768 .wait ())!= 0 ) { 769err = "verify: the arena could not be set" ; 770return false; 771 } 772 } 773 {// APR (prism.hadamard, hadamard.txt): the sign vectors on this device, before any graph capture 774had_sx_ = strata::kernels::hadamard_device_signs (strata::kernels::cpu::hadamard_signs ((int )g .n_embd ), (int )g .n_embd ); 775had_sh_ = strata::kernels::hadamard_device_signs (strata::kernels::cpu::hadamard_signs ((int )g .n_ff ), (int )g .n_ff ); 776 } 777sink_ .staging = (unsigned long long )staging_ ; 778sink_ .staging_cap = kStagingBlobs ; 779 (void )TS ; 780/* 781DPCT1025: The SYCL queue is created ignoring the flag and priority 782options. 783*/ 784if (DPCT_CHECK_ERROR ( 785copy_ = dpct::get_current_device ().create_queue (true))!= 0 ) { 786err = "verify: copy stream create failed" ; 787return false; 788 } 789if (ext_stream_ != nullptr )cs_ = 790ext_stream_ ;// set_stream (pipelined windows): the stage's shared 791// stream 792/* 793DPCT1025: The SYCL queue is created ignoring the flag and priority 794options. 795*/ 796else if (DPCT_CHECK_ERROR ( 797cs_ = dpct::get_current_device ().create_queue (true))!= 0 ) 798cs_ = & dpct::get_in_order_queue (); 799/* 800DPCT1025: The SYCL queue is created ignoring the flag and priority 801options. 802*/ 803if (cs_ == & dpct::get_in_order_queue ()|| 804DPCT_CHECK_ERROR ( 805sh_cs_ = dpct::get_current_device ().create_queue (true))!= 0 ) { 806err = "verify: stream create failed" ; 807return false; 808 } 809if (std::getenv ("STRATA_VERIFY_DEBUG" )!= nullptr ) { 810// SYCL: a queue belongs to one context, so ev_fork_/ev_join_ (recorded on cs_) can only be waited on by 811// sh_cs_ when the two streams are the same card. Print both, and whether the streams are the shared ones. 812auto dn = [](dpct::queue_ptr q )-> std::string { 813if (q == nullptr )return "<null>" ; 814try {return q -> get_device ().get_info < sycl::info::device::name > (); }catch (...) {return "<no device>" ; } 815 }; 816 std::fprintf (stderr ,"strata verify: init device %d, cs '%s', sh_cs '%s', ext_stream %s, copy '%s'\n" , 817device_ ,dn (cs_ ).c_str (),dn (sh_cs_ ).c_str (), 818ext_stream_ == nullptr ?"none" :dn (ext_stream_ ).c_str (),dn (copy_ ).c_str ()); 819 std::fflush (stderr ); 820 } 821if (DPCT_CHECK_ERROR (commit_done_ = new sycl::event ())!= 0 || 822DPCT_CHECK_ERROR (ev_fork_ = new sycl::event ())!= 0 || 823DPCT_CHECK_ERROR (ev_join_ = new sycl::event ())!= 0 ) { 824err = "verify: event create failed" ; 825return false; 826 } 827// Check whether 100% of experts across [lb_, le_) are resident in this stage's VRAM cache. 828// When true, every layer plans on device and writes directly into parts_ without any CPU doorbells, 829// wait_flag_ge spins, PCIe empty launches, or moe_hit_add copies. 830all_resident_ = false; 831ar_off_ = false; 832h_res_ = hits .h_res ; 833if (h_plan_err_ != nullptr )* (volatile uint32_t * )h_plan_err_ = 0 ; 834if (hits .h_res != nullptr && hits .d_res != nullptr && hits .cache_base != nullptr ) { 835const char * v_ar = std::getenv ("STRATA_VERIFY_ALL_RESIDENT" ); 836if (v_ar == nullptr || std::atoi (v_ar )!= 0 ) { 837bool all_ok = true; 838for (int64_t l = lb_ ;l < le_ && all_ok ;++ l ) { 839for (int64_t e = 0 ;e < g .n_expert ;++ e ) { 840if (hits .h_res [l * g .n_expert + e ]< 0 ) { 841all_ok = false; 842break ; 843 } 844 } 845 } 846all_resident_ = all_ok ; 847 } 848 } 849// E-6: a layer whose routed experts are all resident is planned on the device (STRATA_VERIFY_DEVICE_PLAN=1: on; 850// exact, but neutral on RIBPC 1-2 GPUs: off by default) 851 { 852const char * v = std::getenv ("STRATA_VERIFY_DEVICE_PLAN" ); 853// (not with set_always_publish: the device table may lag the host's while windows are in flight) 854device_plan_ = !all_resident_ && !always_publish_ && (v != nullptr && std::atoi (v )!= 0 ); 855 } 856// (halo's STRATA_VERIFY_RESIDENT=1 is this window's all_resident_ graph above, which 0.1.39 has on by default) 857if (g_qfuse ()) {// S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero) 858if (DPCT_CHECK_ERROR (qcnt_ = sycl::malloc_device < unsigned int > ( 859 (size_t )(g .n_embd /32 ), 860 dpct::get_in_order_queue ()))!= 0 || 861DPCT_CHECK_ERROR ( 862 dpct::get_in_order_queue () 863 .memset (qcnt_ ,0 , 864sizeof (unsigned )* (size_t )(g .n_embd /32 )) 865 .wait ())!= 0 ) { 866/* 867DPCT1026: The call to cudaGetLastError was removed because this 868functionality is redundant in SYCL. 869*/ 870if (qcnt_ ) sycl::free (qcnt_ , dpct::get_in_order_queue ()); 871qcnt_ = nullptr ; 872 } 873 } 874if (all_resident_ || device_plan_ ) { 875bool ok2 = true; 876if (device_plan_ ) 877ok2 = DPCT_CHECK_ERROR (skip_ = (uint32_t * )sycl::malloc_device ( 87864 , dpct::get_in_order_queue ()))== 0 && 879DPCT_CHECK_ERROR ( 880 dpct::get_in_order_queue ().memset (skip_ ,0 ,64 ).wait ())== 8810 ; 882if (ok2 && hits .slot_off != nullptr && hits .n_slots > 0 ) { 883ok2 = DPCT_CHECK_ERROR ( 884slot_off_d_ = sycl::malloc_device < unsigned long long > ( 885 (size_t )hits .n_slots , dpct::get_in_order_queue ()))== 8860 && 887DPCT_CHECK_ERROR (dpct::get_in_order_queue () 888 .memcpy (slot_off_d_ ,hits .slot_off , 889 (size_t )hits .n_slots * 890sizeof (unsigned long long )) 891 .wait ())== 0 ; 892 } 893/* 894DPCT1026: The call to cudaGetLastError was removed because this 895functionality is redundant in SYCL. 896*/ 897if (!ok2 ) {;all_resident_ = false;device_plan_ = false; } 898 } 899if (sycl_mirror_adapt ()) { 900if (!device_plan_ || !env_on ("STRATA_VERIFY_NO_HOST" )) 901throw std::runtime_error ("mirror adaptive expert usage requires NoHost device planning" ); 902expert_usage_counts_h_ .assign ((size_t )g .n_layers * (size_t )g .n_expert ,0 ); 903expert_usage_counts_d_ = sycl::malloc_device < uint32_t > (expert_usage_counts_h_ .size (),* cs_ ); 904if (!expert_usage_counts_d_ )throw std::bad_alloc (); 905cs_ -> memset (expert_usage_counts_d_ ,0 ,expert_usage_counts_h_ .size ()* sizeof (uint32_t )).wait_and_throw (); 906 } 907#ifdef STRATA_SYCL_WORKLOAD_TRACE 908if (const char * audit = std::getenv ("STRATA_SYCL_ROUTING_AUDIT_FILE" );audit && * audit ) { 909if (!device_plan_ )throw std::runtime_error ("routing audit requires device planning" ); 910routing_audits [this ]= std::make_unique < RoutingAudit > (plan_i32_ ,g .n_layers ,cs_ ,audit ); 911 } 912#endif 913if (std::getenv ("STRATA_VERIFY_DEBUG" )!= nullptr ) {// SYCL port: the per-layer residual ladder (token 0) 914dbgR_ = (float * ) sycl::malloc_device ((size_t )g .n_layers * g .n_embd * 4 , dpct::get_in_order_queue ()); 915dbgM_ = (float * ) sycl::malloc_device ((size_t )g .n_layers * g .n_embd * 4 , dpct::get_in_order_queue ()); 916 } 917 std::fprintf (stderr ,"strata verify: window up to %d tokens, %.1f MiB of device buffers%s\n" ,max_t , 918 (double )count .used /1048576.0 , 919all_resident_ ?" (100% VRAM resident: zero-doorbell graph)" :"" ); 920return true; 921} 922catch (sycl::exception const & exc ) { 923 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 924 <<", line:" <<__LINE__ << std::endl ; 925 std::exit (1 ); 926} 927 928const float * Verifier ::final_R (int t )const {return R_ + (size_t )t * (size_t ) (g_ -> hc * g_ -> n_embd ); } 929 930// ================================ THE WINDOW, AS CAPTURED ================================ 931// 932// Plan v0.3 P6 (split window): with `groups_ == 2` the window's tokens are cut into two groups A = [0, T/2 up) and 933// B = the rest, and the stream is ordered 934// 935// pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B) | post(1,A) pre(2,A) | ... 936// 937// 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 938// 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 939// state), never A's experts, so nothing waits that did not wait before. Every token's arithmetic is unchanged. 940bool Verifier ::record_window (int T , dpct::queue_ptr cs , std::string & err ) { 941 strata::kernels::B60MainActorScope b60_actor_scope ; 942using namespace strata::kernels ; 943const ModelGeometry & g = * g_ ; 944// 0.1.43 (STRATA_VERIFY_LEAN=0 turns it off): with the device plan under STRATA_VERIFY_NO_HOST no host ever answers a doorbell, so 945// a layer's doorbell publish, the three flag waits, the plan copy, the PCIe-share group and its staging kernels are nodes of 946// the graph that only wait for each other or do nothing: ~9 nodes (~1.4 ms) per layer-window less. The VRAM / mirror groups, the 947// combine and the answers are the same kernels on the same data. 948static const bool lean_env = [] {const char * v = std::getenv ("STRATA_VERIFY_LEAN" );return !(v && v [0 ]== '0' ); }(); 949static const bool no_host_env = [] {const char * v = std::getenv ("STRATA_VERIFY_NO_HOST" );return v && * v && std::strcmp (v ,"0" )!= 0 ; }(); 950// Not for a batch window (batch_rec_): unless the stage is all-resident, run_slot_rows / batch_poll wait for each 951// layer's doorbell, so a lean batch graph finishes with the ring silent ("verify batch: layer 0 never rang (graph 952// finished)", then the engine dies). Batch windows keep the doorbell nodes; the solo window stays lean. 953const bool lean = lean_env && no_host_env && device_plan_ && !batch_rec_ && !step_hook_ && !step_hook2_ && !remote_opt_ && !always_publish_ && !g_stepped ; 954const WeightTable & wt = * wt_ ; 955SessionState & ss = * ss_ ; 956const int64_t N = g .n_embd ,HC = g .hc ,K = ss .k ,C = g .ssm_conv_channels ,ZV = g .ssm_value_dim ; 957const 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 ; 958const int64_t IQ = g .idx_q_heads ,ID = g .idx_key_dim ,NE = g .n_expert ,MT = max_t_ ; 959const QsaShapes s = shapes_of (g ); 960const GrShapes gs {g .n_embd ,g .hc ,g .hc_lr }; 961const uint64_t gdn_floats = (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size + 962 (uint64_t )g .ssm_conv_channels * (g .ssm_d_conv - 1 ); 963const int64_t HS = (int64_t )NG_HIST * NG_HC_DIM ; 964const int64_t TS = (s .idx_block - 1 )* ID ; 965const bool ple_on = ss .ple .ready ()&& ple_stage (); 966auto Rt = [& ](int t ) {return R_ + (size_t )t * HC * N ; }; 967const int G = (split_ && T >=2 && !batch_rec_ ) ?2 :1 ;// a batch window is one group 968const bool self_commit = T == 1 && !batch_rec_ && !g_qfuse ()&& one_token_self_commit ()&& 969 !self_commit_off_ ;// see Verifier::commit 970static const bool dec_batch = [] {const char * v = std::getenv ("STRATA_DEC_BATCH" );return v == nullptr || std::atoi (v )!= 0 ; }(); 971// SYCL port, STRATA_VERIFY_EAGER=1: the window runs on the queue instead of as a graph, and each stage stamp is 972// a host-side wait + clock (there is no %globaltimer here), so the existing stage profiler reports ms per stage. 973static const bool eager = std::getenv ("STRATA_VERIFY_EAGER" )!= nullptr ; 974auto stamp = [& ](int64_t l ,int i ,int grp ) { 975if (trace_m_ != nullptr )gpu_stamp (trace_m_ , (int ) ((l * kProfPer + i )* 2 + grp ),cs );// #649 976if (!prof_on_ || grp != 0 )return ; 977if (eager ) {cs -> wait ();prof_h_ [(size_t ) (l * kProfPer + i )]= (unsigned long long ) std::chrono::steady_clock::now ().time_since_epoch ().count (); } 978else gpu_stamp (prof_ , (int ) (l * kProfPer + i ),cs ); 979 }; 980const int tb_ [2 ]= {0 , (T + 1 ) /2 },te_ [2 ]= {G == 2 ? (T + 1 ) /2 :T ,T }; 981// S26 STRATA_LFUSE=1: where the shared expert's gate / scale fusions apply (the paths they replace are the ones taken) 982auto lfuse_on = [& ](int n ) { 983return g_lfuse ()&& ar_on ()&& native_moe_combine_enabled ()&& dec_batch && n > 1 && n <=8 && 984shared_expert_native_bf16_enabled (); 985 }; 986bool sg_gated_ [2 ]= {false, false};// per group: the combine applies the shared gate 987if (!batch_rec_ )groups_ [T ]= G ; 988const int64_t nQall = g .n_qsa_layers (); 989// a batch window: row t is slot t, whose state lives in its own session 990auto slot_ss = [& ](int t )-> SessionState & {return batch_rec_ ?* slots_ [(size_t )brow_ [t ]] :ss ; }; 991const int hrow0 = batch_rec_ ?row_base_ :0 ;// a slot group's own hand-off rows 992 993// ---- the window's inputs, from mapped staging 994copy_i32_from_mapped (tok_ ,m_tok_ ,T ,cs ); 995copy_i32_from_mapped (step_ ,m_step_ , (int64_t )T * kStepCount ,cs ); 996copy_i32_from_mapped (pos_ ,m_pos_ , (int64_t )MT * (NH + NKV + IQ ),cs ); 997// per-ROW positions of the K rows [t][NKV] and the indexer query rows [t][IQ] (for batched RoPE) 998const int32_t * pos_k = pos_ + MT * NH ; 999const int32_t * pos_i = pos_ + MT * (NH + NKV ); 1000 1001// ---- the embeddings, broadcast to the hc streams - or, in a later stage of a layer split, the previous stage's 1002// residual, pending write and inject (see set_stage) 1003const int64_t HB = Verifier ::handoff_floats (g ); 1004if (lb_ > 0 ) { 1005const float * hin = hand_in_ + (size_t )hrow0 * HB ;// the group's rows: [R][bo][inj] contiguous 1006copy_from_mapped (R_ ,hin , (int64_t )T * HC * N ,cs ); 1007copy_from_mapped (bo_ ,hin + (size_t )T * HC * N , (int64_t )T * N ,cs ); 1008copy_from_mapped (inj2_ ,hin + (size_t )T * (HC + 1 )* N , (int64_t )T * HC ,cs ); 1009 }else if (const NativeEmbed * ne = native_embed ()) {// plan v0.3 P6: the GGUF-form table 1010ne -> gather_dev (tok_ ,T ,emb_ ,cs ); 1011broadcast_streams (emb_ ,R_ ,N , (int )HC ,T ,cs ); 1012 }else { 1013const WeightRef * w = wt .find ("token_embd.weight" ); 1014if (w == nullptr || w -> codebook_iq4nl || (w -> code_bits != 2 && w -> code_bits != 4 && w -> code_bits != 8 )) { 1015err = "verify: token_embd.weight is missing or not an S2/S4/S8 tensor" ; 1016return false; 1017 } 1018const auto * codes = (const uint8_t * )w -> data ; 1019const auto * scales = (const float * ) (codes + w -> codes_bytes ); 1020const auto * offsets = w -> has_offset ? (const float * ) (codes + w -> codes_bytes + w -> scales_bytes ) :nullptr ; 1021const uint64_t row_codes = (uint64_t ) (w -> ne0 / (8 /w -> code_bits )); 1022const uint64_t row_groups = (uint64_t ) (w -> ne0 /w -> group_elems ); 1023embedding_gather_dev (codes ,scales ,offsets ,tok_ ,T ,w -> ne0 ,w -> code_bits ,w -> code_bias ,w -> group_elems , 1024row_codes ,row_groups ,emb_ ,cs ); 1025broadcast_streams (emb_ ,R_ ,N , (int )HC ,T ,cs ); 1026 } 1027 1028// per-layer state indices (GDN and QSA layers are numbered separately) 1029 std::vector < int64_t > gdn_idx ((size_t )g .n_layers ,-1 ),qsa_idx ((size_t )g .n_layers ,-1 ); 1030 { 1031int64_t qi = 0 ,gi = 0 ; 1032for (int64_t l = 0 ;l < g .n_layers ;++ l ) { 1033if (is_qsa_layer (g ,l ))qsa_idx [(size_t )l ]= qi ++ ; 1034else gdn_idx [(size_t )l ]= gi ++ ; 1035 } 1036 } 1037 1038// ---------------------------------------------------------------- pre(l, group): up to the ring 1039auto pre = [& ](int64_t l ,int grp )-> bool { 1040const int tb = tb_ [grp ],te = te_ [grp ],n = te - tb ; 1041#ifdef STRATA_SYCL_WORKLOAD_TRACE 1042 strata::workload_trace::ContextGuard layer_context (strata::workload_trace::context .position ,n ,l ); 1043#endif 1044 strata::workload_trace::Scope layer_trace ("decode.layer.pre" ,cs ,n ,N ); 1045stamp (l ,0 ,grp ); 1046const LayerView v (wt ,l ); 1047const char * pfx [2 ]= {"hc_attn_" ,"hc_ffn_" }; 1048const WeightRef * wn [2 ],* wd [2 ],* wu [2 ],* wi [2 ]; 1049for (int h = 0 ;h < 2 ;++ h ) { 1050wn [h ]= need (v , (std::string (pfx [h ])+ "norm.weight" ).c_str (),err ); 1051wd [h ]= need (v , (std::string (pfx [h ])+ "down.weight" ).c_str (),err ); 1052wu [h ]= need (v , (std::string (pfx [h ])+ "up.weight" ).c_str (),err ); 1053wi [h ]= need (v , (std::string (pfx [h ])+ "inject.weight" ).c_str (),err ); 1054if (!wn [h ]|| !wd [h ]|| !wu [h ]|| !wi [h ])return false; 1055 } 1056// the previous layer's FFN write, folded into this layer's first read (a control vector after it has 1057// already applied it) 1058bool pending = l > 0 && !cvec ().covers (l - 1 ); 1059if (l == 1 && ple_on ) { 1060if (grp == 0 ) { 1061if (ar_on ())wait_flag_ge (m_flag_ ,1 ,cs ); 1062copy_from_mapped (ple_ ,m_ple_ , (int64_t )T * N ,cs ); 1063 } 1064float * normalized = (float * ) ((uint8_t * )ss .ple .scratch + ple_block_scratch_bytes ()); 1065static const bool ple_batch_env = [] { 1066const char * e = std::getenv ("STRATA_PLE_BATCH" ); 1067return !e || e [0 ]!= '0' ; 1068 }(); 1069const bool ple_batch_kv = ple_batch_env && dec_batch && n > 1 && ss .ple .w .key_bf16 != nullptr && 1070ss .ple .w .value_bf16 != nullptr && ple_native_bf16_enabled ()&& 1071ple_native_postops_enabled (); 1072// S25 (STRATA_PLE_BATCH=1): the key and value projections depend only on each row's n-gram embedding, so 1073// the group's rows run through the multi-row forms of the same kernels (the weights read once); every 1074// row's arithmetic is the single-row call's. The history-dependent rest stays row by row. 1075static const bool ple_batch = [] {const char * e = std::getenv ("STRATA_PLE_BATCH" );return e && e [0 ]== '1' ; }(); 1076PleWeights pw = ss .ple .w ; 1077const bool nkey = pw .key_native_data != nullptr && pw .key_bf16 == nullptr ; 1078const bool batched = !ple_batch_kv && ple_batch && n > 1 && (pw .key_bf16 != nullptr || nkey )&& ple_native_bf16_enabled (); 1079if (ple_batch_kv ) { 1080try { 1081bf16_gemv_fp32_mmvf_multi (ple_ + (size_t )tb * N ,N ,ss .ple .w .key_bf16 , 1082xn_ + (size_t )tb * HC * N ,HC * N ,N ,HC * N ,n ,cs ); 1083bf16_gemv_fp32_mmvf_multi (ple_ + (size_t )tb * N ,N ,ss .ple .w .value_bf16 , 1084z_ + (size_t )tb * N ,N ,N ,N ,n ,cs ); 1085 }catch (const std::exception & e ) { 1086err = std::string ("verify PLE multi: " )+ e .what (); 1087return false; 1088 } 1089 }else if (batched ) { 1090try { 1091if (pw .key_bf16 != nullptr ) 1092bf16_gemv_fp32_mmvf_multi (ple_ + tb * N ,N ,pw .key_bf16 ,ple_key_ + (size_t )tb * NG_HC_DIM , 1093NG_HC_DIM ,N ,NG_HC_DIM ,n ,cs ); 1094else { 1095native_quantize_q8_1 (ple_ + tb * N ,xq_ , (int )N ,n ,cs ); 1096native_mmvq (pw .key_native_type ,pw .key_native_data ,xq_ ,ple_key_ + (size_t )tb * NG_HC_DIM , 1097 (int )N ,NG_HC_DIM ,n ,cs ); 1098 } 1099bf16_gemv_fp32_mmvf_multi (ple_ + tb * N ,N ,pw .value_bf16 ,ple_val_ + tb * N ,N ,N ,N ,n ,cs ); 1100 }catch (const std::exception & e ) { 1101err = std::string ("verify PLE batch: " )+ e .what (); 1102return false; 1103 } 1104 } 1105// #783 PR-g (stuchapin909): the window's residual writes in one launch (STRATA_NO_MULTI_GR=1: per token) 1106const bool multi_write = dec_batch && !g_no_multi_gr && n > 1 ; 1107if (multi_write )gr_write_multi (Rt (tb ),bo_ + tb * N ,inj2_ + tb * HC ,gs ,Rt (tb ),n ,cs ); 1108for (int t = tb ;t < te ;++ t ) { 1109if (batched ) {pw .pre_key = ple_key_ + (size_t )t * NG_HC_DIM ;pw .pre_value = ple_val_ + t * N ; } 1110if (!multi_write )gr_write (Rt (t ),bo_ + t * N ,inj2_ + t * HC ,gs ,Rt (t ),cs ); 1111PleOut po ; 1112po .normalized = normalized ; 1113po .result = Rt (t ); 1114float * hist = batch_rec_ ?slot_ss (t ).ple_hist :ss .ple .hist ;// the row's own history 1115try { 1116if (ple_batch_kv ) { 1117ple_block_projected (xn_ + (size_t )t * HC * N ,z_ + (size_t )t * N ,Rt (t ),hist , 1118ss .ple .w ,po ,ss .ple .scratch ,cs ); 1119 }else { 1120ple_block (ple_ + t * N ,Rt (t ),hist ,pw ,po ,ss .ple .scratch ,cs ); 1121 } 1122ple_history_advance (hist ,normalized ,cs ); 1123 }catch (const std::exception & e ) { 1124err = std::string ("verify PLE: " )+ e .what (); 1125return false; 1126 } 1127copy_from_mapped (hist_snap_ + (size_t )t * HS ,hist ,HS ,cs ); 1128 } 1129pending = false; 1130 } 1131auto gr_read_group = [& ](int half ,bool apply ,float * inj_prev ,float * inj_out ) { 1132 strata::workload_trace::Scope gr_trace ("decode.gr_read" ,cs ,n ,HC * N ,g .hc_lr ,HC ,N ,half ); 1133FusedGrArgs fa [kFusedGrMaxT ]; 1134for (int t = tb ;t < te ;++ t ) { 1135FusedGrArgs & a = fa [t - tb ]; 1136a .R = Rt (t );a .R_out = Rt (t );a .apply = apply ; 1137a .bo_prev = bo_ + t * N ;a .inj_prev = inj_prev + t * HC ; 1138a .w_norm = (const float * )wn [half ]-> data ;a .w_down = (const uint16_t * )wd [half ]-> data ; 1139a .w_up = (const uint16_t * )wu [half ]-> data ;a .w_inject = (const uint16_t * )wi [half ]-> data ; 1140a .q8_down = (const uint8_t * )wd [half ]-> hc_q8 ;a .q8_up = (const uint8_t * )wu [half ]-> hc_q8 ; 1141a .q8_inject = (const uint8_t * )wi [half ]-> hc_q8 ; 1142a .eps = EPS ;a .lo = lo_ + t * g .hc_lr ;a .rs = rs_ + t * HC ; 1143a .inject_out = inj_out + t * HC ;a .mixed = mixed_ + t * N ; 1144if (qcnt_ != nullptr || (b60_gr_q8_requested ()&& n == 1 )) {// S26 STRATA_QFUSE: the consumer's q8_1 image written by the read itself 1145a .q8_cnt = qcnt_ ; 1146if (half == 0 )a .q8_mixed = xq_ + (size_t ) (t - tb )* (N /32 )* 36 ; 1147else if (strata::kernels::cpu::expert_layout ().native )a .q8_mixed = nat_xq_ + (size_t )t * (N /32 )* 36 ; 1148 } 1149 } 1150return fused_gr_read_multi (fa ,n ,xn_ + (size_t )tb * HC * N ,cs , (prof_on_ && grp == 0 ) ?prof_ :nullptr , 1151 (int ) (l * kProfPer + (half == 0 ?27 :30 ))); 1152 }; 1153const bool q8_attn = gr_read_group (0 ,pending ,inj2_ ,inj_ );// true: xq_ holds mixed's q8_1 (STRATA_QFUSE) 1154stamp (l ,1 ,grp ); 1155float * xm = mixed_ + tb * N ; 1156try { 1157if (!is_qsa_layer (g ,l )) { 1158// ======================= GDN ======================= 1159const WeightRef * wqkv = need (v ,"attn_qkv.weight" ,err ),* wg = need (v ,"attn_gate.weight" ,err ), 1160* wout = need (v ,"ssm_out.weight" ,err ),* wa = need (v ,"ssm_alpha.weight" ,err ), 1161* wb = need (v ,"ssm_beta.weight" ,err ),* wc = need (v ,"ssm_conv1d.weight" ,err ), 1162* wnm = need (v ,"ssm_norm.weight" ,err ),* wdt = need (v ,"ssm_dt.bias" ,err ), 1163* wsa = need (v ,"ssm_a" ,err ); 1164if (!wqkv || !wg || !wout || !wa || !wb || !wc || !wnm || !wdt || !wsa )return false; 1165if (!native_of (wqkv ,v .name ("attn_qkv.weight" ),err )|| !native_of (wg ,v .name ("attn_gate.weight" ),err )|| 1166 !native_of (wout ,v .name ("ssm_out.weight" ),err )) 1167return false; 1168const int64_t gi = gdn_idx [(size_t )l ]; 1169float * state = ss .gdn_state + (size_t ) (gi - ss .gdn_ord0 )* gdn_floats ; 1170float * conv = state + (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 1171float * qkv = qkv_L_ + (size_t )gi * MT * C ; 1172float * hb = h_L_ + (size_t )gi * MT * C ; 1173float * gate = gate_L_ + (size_t )gi * MT * HV ; 1174float * beta = beta_L_ + (size_t )gi * MT * HV ; 1175if (!q8_attn )native_quantize_q8_1 (xm ,xq_ , (int )N ,n ,cs ); 1176native_mmvq (wqkv -> native_type ,wqkv -> native_data ,xq_ ,qkv + (size_t )tb * C , (int )N , (int )C ,n ,cs ); 1177stamp (l ,2 ,grp ); 1178if (batch_rec_ ) {// contiguous rows may be proposals for the same slot 1179for (int t = tb ;t < te ;) { 1180const int first = t ; 1181while (t < te && brow_ [t ]== brow_ [first ])++ t ; 1182SessionState & sx = slot_ss (first ); 1183const float * cx = sx .gdn_state + (size_t ) (gi - sx .gdn_ord0 )* gdn_floats + 1184 (uint64_t )g .ssm_state_size * g .ssm_v_heads * g .ssm_state_size ; 1185gdn_conv_l2_multi (cx ,qkv + (size_t )first * C , (const float * )wc -> data , 1186hb + (size_t )first * C , (int )C , (int ) (2 * HK ),EPS ,t - first ,cs ,0 ); 1187 } 1188 }else 1189// a one-token window keeps its token: it advances the conv history and the state itself (commit) 1190gdn_conv_l2_multi (conv ,qkv , (const float * )wc -> data ,hb , (int )C , (int ) (2 * HK ),EPS ,n ,cs ,tb , 1191self_commit ); 1192stamp (l ,3 ,grp ); 1193gdn_ab_multi (xm , (const uint16_t * )wa -> data , (const uint16_t * )wb -> data , (const float * )wdt -> data , 1194 (const float * )wsa -> data ,gate + (size_t )tb * HV ,beta + (size_t )tb * HV , (int )N , (int )HV , 1195n ,cs ); 1196stamp (l ,4 ,grp ); 1197native_mmvq (wg -> native_type ,wg -> native_data ,xq_ ,z_ + (size_t )tb * ZV , (int )N , (int )ZV ,n ,cs ); 1198stamp (l ,5 ,grp ); 1199// the recurrence from the untouched state over tokens [0, te); outputs only for this group's 1200static const bool gdn_groups_on = [] {// STRATA_BATCH_GDN_GROUPS=1, all slots in one launch 1201const char * e = std::getenv ("STRATA_BATCH_GDN_GROUPS" ); 1202return e != nullptr && std::atoi (e )!= 0 ; 1203 }(); 1204if (batch_rec_ && gdn_groups_on && te - tb <=8 ) { 1205GdnGroups gg ; 1206for (int t = tb ;t < te ;) { 1207const int first = t ; 1208while (t < te && brow_ [t ]== brow_ [first ])++ t ; 1209SessionState & sx = slot_ss (first ); 1210gg .state [gg .n ]= sx .gdn_state + (size_t ) (gi - sx .gdn_ord0 )* gdn_floats ; 1211gg .first [gg .n ]= first ; 1212gg .ntok [gg .n ]= t - first ; 1213++ gg .n ; 1214 } 1215gdn_step_norm_groups (gg ,hb , (int )C ,gate ,beta ,z_ , (const float * )wnm -> data ,EPS ,y_ , (int )HK , 1216 (int )HV , false,cs ); 1217 }else 1218if (batch_rec_ ) {// each slot's recurrence over its own proposed-token group 1219for (int t = tb ;t < te ;) { 1220const int first = t ; 1221while (t < te && brow_ [t ]== brow_ [first ])++ t ; 1222SessionState & sx = slot_ss (first ); 1223float * stx = sx .gdn_state + (size_t ) (gi - sx .gdn_ord0 )* gdn_floats ; 1224gdn_step_norm_multi (stx ,hb + (size_t )first * C , (int )C ,gate + (size_t )first * HV , 1225beta + (size_t )first * HV ,z_ + (size_t )first * ZV , 1226 (const float * )wnm -> data ,EPS ,y_ + (size_t )first * ZV , 1227 (int )HK , (int )HV ,t - first ,nullptr ,cs ,0 ); 1228 } 1229 }else 1230gdn_step_norm_multi (state ,hb , (int )C ,gate ,beta ,z_ , (const float * )wnm -> data ,EPS ,y_ , (int )HK , 1231 (int )HV ,te ,self_commit ?one_ :nullptr ,cs ,tb ,g_qfuse () ? (void * )xq_ :nullptr ); 1232stamp (l ,6 ,grp ); 1233if (!g_qfuse ())native_quantize_q8_1 (y_ + (size_t )tb * ZV ,xq_ , (int )ZV ,n ,cs );// STRATA_QFUSE: done above 1234native_mmvq (wout -> native_type ,wout -> native_data ,xq_ ,bo_ + tb * N , (int )ZV , (int )N ,n ,cs ); 1235 }else { 1236// ======================= QSA ======================= 1237const int64_t qi = qsa_idx [(size_t )l ]; 1238const QsaState & st = ss .qsa_states [qi ]; 1239const WeightRef * wik = need (v ,"indexer.k_proj.weight" ,err ),* wq = need (v ,"attn_q.weight" ,err ), 1240* wk = need (v ,"attn_k.weight" ,err ),* wv = need (v ,"attn_v.weight" ,err ), 1241* wo = need (v ,"attn_output.weight" ,err ),* wiq = need (v ,"indexer.q_proj.weight" ,err ), 1242* wqn = need (v ,"attn_q_norm.weight" ,err ),* wkn = need (v ,"attn_k_norm.weight" ,err ), 1243* wiqn = need (v ,"indexer.q_norm.weight" ,err ),* wikn = need (v ,"indexer.k_norm.weight" ,err ); 1244if (!wik || !wq || !wk || !wv || !wo || !wiq || !wqn || !wkn || !wiqn || !wikn )return false; 1245if (!native_of (wq ,v .name ("attn_q.weight" ),err )|| !native_of (wk ,v .name ("attn_k.weight" ),err )|| 1246 !native_of (wv ,v .name ("attn_v.weight" ),err )|| !native_of (wo ,v .name ("attn_output.weight" ),err )) 1247return false; 1248// #783 PR-f (stuchapin909): the per-head RMSNorm and the rope in one launch, bit-identical to the pair 1249// (rope_parity check 6); STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes 1250const bool fuse_nr = native_qsa_enabled ()&& native_rope_enabled ()&& native_norm_rope_usable ((int )HD , (int )s .n_rot ); 1251auto norm_rope = [& ](float * data ,const WeightRef * norm ,int rows ,int cols ,const int32_t * pos ) { 1252if (fuse_nr && native_norm_rope_usable (cols , (int )s .n_rot )) { 1253native_qsa_rms_norm_rope (data ,cols , (const float * )norm -> data ,data ,rows ,cols , (int )s .n_rot ,EPS , 1254rope_scaling (),pos ,cs ); 1255return ; 1256 } 1257if (native_qsa_enabled ())native_qsa_rms_norm_weighted (data , (const float * )norm -> data ,data ,cols ,rows ,EPS ,cs ); 1258else rms_norm_weighted (data , (const float * )norm -> data ,rows ,cols ,EPS ,cs ); 1259if (native_rope_enabled ())native_rope_apply (data ,data ,rows ,cols , (int )s .n_rot ,rope_scaling (),pos ,cs ); 1260else rope_neox_apply (data ,data ,rows ,cols , (int )s .n_rot ,st .cos_tab ,st .sin_tab ,pos ,cs ); 1261 }; 1262float * idx_raw = idx_raw_L_ + (size_t )qi * MT * ID ; 1263// the per-token GEMVs / norms / RoPEs / copies of this layer as one launch over the 1264// window's rows each - row-wise identical arithmetic (STRATA_DEC_BATCH=0: token by token) 1265const bool qb = dec_batch && n > 1 && native_qsa_enabled ()&& native_rope_enabled ()&& !st .kv_q4 ; 1266if (!q8_attn )native_quantize_q8_1 (xm ,xq_ , (int )N ,n ,cs ); 1267if (qb )bf16_gemv_fp32_mmvf_multi (mixed_ + tb * N ,N , (const uint16_t * )wik -> data ,idx_raw + tb * ID ,ID ,N ,ID ,n ,cs ); 1268else for (int t = tb ;t < te ;++ t ) 1269bf16_gemv_fp32_mmvf (mixed_ + t * N , (const uint16_t * )wik -> data ,idx_raw + t * ID , (int )N , (int )ID ,cs ); 1270stamp (l ,7 ,grp ); 1271native_mmvq (wk -> native_type ,wk -> native_data ,xq_ ,kcur_ + tb * NKV * HD , (int )N , (int ) (NKV * HD ),n ,cs ); 1272native_mmvq (wv -> native_type ,wv -> native_data ,xq_ ,vcur_ + tb * NKV * HD , (int )N , (int ) (NKV * HD ),n ,cs ); 1273if (qb )norm_rope (kcur_ + tb * NKV * HD ,wkn , (int ) (n * NKV ), (int )HD ,pos_k + tb * NKV ); 1274else for (int t = tb ;t < te ;++ t )norm_rope (kcur_ + t * NKV * HD ,wkn , (int )NKV , (int )HD ,pos_ + t * NH ); 1275if (st .kv_rot ) {// K and V rotated before they are stored (kv_q4.hpp) 1276fwht256_inplace_cuda (kcur_ + tb * NKV * HD , (int64_t )n * NKV ,cs ); 1277fwht256_inplace_cuda (vcur_ + tb * NKV * HD , (int64_t )n * NKV ,cs ); 1278 }else if (st .kv_hybrid ) {// K8V4: only V is rotated 1279fwht256_inplace_cuda (vcur_ + tb * NKV * HD , (int64_t )n * NKV ,cs ); 1280 } 1281stamp (l ,8 ,grp ); 1282if (batch_rec_ ) {// snapshot each slot's indexer tail before its first proposed row 1283for (int t = tb ;t < te ;++ t ) 1284if (t == tb || brow_ [t ]!= brow_ [t - 1 ]) 1285copy_from_mapped (tail_snap_b_ + ((size_t )brow_ [t ]* nQall + qi )* TS , 1286slot_ss (t ).qsa_states [qi ].idx_tail ,TS ,cs ); 1287 }else 1288if (grp == 0 )copy_from_mapped (tail_snap_ + (size_t )qi * TS ,st .idx_tail ,TS ,cs ); 1289// #783 PR-d (stuchapin909): the window's K/V cells in one launch per pool instead of one per token (a 1290// batch's rows each have their own K/V, so that case keeps the loop) 1291if (dec_batch && !g_no_batch_kv && !batch_rec_ ) { 1292const int32_t * step_b = step_ + tb * kStepCount ; 1293const float * kc_b = kcur_ + tb * NKV * HD ; 1294const float * vc_b = vcur_ + tb * NKV * HD ; 1295if (st .kv_hybrid ) {// K8V4: the unused half's lanes folded onto the used pool (layer.cpp) 1296kv_append_q8_steps (st .k_q ,st .k_q ,st .k_scale ,st .k_scale ,st .page_table ,step_b ,kStepCount , 1297kc_b ,kc_b , (int ) (NKV * HD ),n ,s ,cs ,nullptr ); 1298kv_append_q4_steps (st .v_q4 ,st .v_q4 ,st .page_table ,step_b ,kStepCount ,n ,vc_b ,vc_b ,s ,cs , 1299nullptr ); 1300 }else if (st .kv_q4 ) 1301kv_append_q4_steps (st .k_q4 ,st .v_q4 ,st .page_table ,step_b ,kStepCount ,n ,kc_b ,vc_b ,s ,cs , 1302& st .host ); 1303else if (st .kv_int8 ) 1304kv_append_q8_steps (st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,st .page_table ,step_b ,kStepCount , 1305kc_b ,vc_b , (int ) (NKV * HD ),n ,s ,cs ,& st .host ); 1306else 1307for (int t = tb ;t < te ;++ t ) 1308kv_append_step (st .k_pool ,st .v_pool ,st .page_table ,step_ + t * kStepCount , 1309kcur_ + t * NKV * HD ,vcur_ + t * NKV * HD ,s ,cs ,& st .host ); 1310 }else 1311for (int t = tb ;t < te ;++ t ) { 1312const QsaState & st = slot_ss (t ).qsa_states [qi ];// the row's own K/V (ss's outside a batch) 1313const int32_t * step_t = step_ + t * kStepCount ; 1314if (st .kv_hybrid ) {// K8V4: the unused half's lanes folded onto the used pool (layer.cpp) 1315const KvHostPools hk = kv_hybrid_k_half (st .host ),hv = kv_hybrid_v_half (st .host ); 1316const bool mirror = st .host .present ();// streamed: the host copy too 1317kv_append_q8_step (st .k_q ,st .k_q ,st .k_scale ,st .k_scale ,st .page_table ,step_t , 1318kcur_ + t * NKV * HD ,kcur_ + t * NKV * HD ,s ,cs ,mirror ?& hk :nullptr ); 1319kv_append_q4_step (st .v_q4 ,st .v_q4 ,st .page_table ,step_t ,vcur_ + t * NKV * HD , 1320vcur_ + t * NKV * HD ,s ,cs ,mirror ?& hv :nullptr ); 1321 }else if (st .kv_q4 ) 1322kv_append_q4_step (st .k_q4 ,st .v_q4 ,st .page_table ,step_t ,kcur_ + t * NKV * HD , 1323vcur_ + t * NKV * HD ,s ,cs ,& st .host ); 1324else if (st .kv_int8 ) 1325kv_append_q8_step (st .k_q ,st .v_q ,st .k_scale ,st .v_scale ,st .page_table ,step_t , 1326kcur_ + t * NKV * HD ,vcur_ + t * NKV * HD ,s ,cs ,& st .host ); 1327else 1328kv_append_step (st .k_pool ,st .v_pool ,st .page_table ,step_t ,kcur_ + t * NKV * HD , 1329vcur_ + t * NKV * HD ,s ,cs ,& st .host ); 1330 } 1331if (dec_batch && !g_no_batch_kv && !batch_rec_ ) { 1332const QsaIndexerBuffers ib {st .idx_tail ,st .idx_dead ,st .idx_pooled ,st .idx_block_pos }; 1333native_qsa_indexer_append_steps (idx_raw + tb * ID ,step_ + tb * kStepCount + kStepPos ,kStepCount , 1334n ,0 , (const float * )wikn -> data ,EPS ,ib ,s ,st .max_cells , 1335rope_scaling (),cs ); 1336 }else { 1337for (int t = tb ;t < te ;++ t ) { 1338const QsaState & sx = slot_ss (t ).qsa_states [qi ]; 1339const QsaIndexerBuffers ib {sx .idx_tail ,sx .idx_dead ,sx .idx_pooled ,sx .idx_block_pos }; 1340native_qsa_indexer_append (idx_raw + t * ID ,step_ + t * kStepCount + kStepPos ,0 , 1341 (const float * )wikn -> data ,EPS ,ib ,s ,sx .max_cells , 1342rope_scaling (),cs ); 1343 } 1344 } 1345stamp (l ,9 ,grp ); 1346native_mmvq (wq -> native_type ,wq -> native_data ,xq_ ,qfull_ + tb * NH * 2 * HD , (int )N , (int ) (NH * 2 * HD ), 1347n ,cs ); 1348if (qb ) { 1349if (fuse_nr ) {// the q/gate split reads q straight out of the q|gate rows (stride 2 * HD) 1350native_qsa_rms_norm_rope (qfull_ + tb * NH * 2 * HD , (int ) (2 * HD ), (const float * )wqn -> data , 1351qcur_ + tb * NH * HD , (int ) (n * NH ), (int )HD , (int )s .n_rot ,EPS , 1352rope_scaling (),pos_ + tb * NH ,cs ); 1353 }else { 1354/* 1355DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous 1356memcpy API. While the origin API might be synchronous, it 1357depends on the type of operand memory, so you may need to 1358call wait() on event return by memcpy API to ensure 1359synchronization behavior. 1360*/ 1361if (DPCT_CHECK_ERROR (dpct::async_dpct_memcpy ( 1362qcur_ + tb * NH * HD , (size_t )HD * 4 , 1363qfull_ + tb * NH * 2 * HD , (size_t )HD * 2 * 4 , 1364 (size_t )HD * 4 , (size_t )(n * NH ), 1365 dpct::device_to_device ,* cs ))!= 0 ) { 1366err = "verify: the q/gate split failed" ; 1367return false; 1368 } 1369norm_rope (qcur_ + tb * NH * HD ,wqn , (int ) (n * NH ), (int )HD ,pos_ + tb * NH ); 1370 } 1371if (st .kv_rot )fwht256_inplace_cuda (qcur_ + tb * NH * HD , (int64_t )n * NH ,cs );// <Hq, Hk> = <q, k> 1372bf16_gemv_fp32_mmvf_multi (mixed_ + tb * N ,N , (const uint16_t * )wiq -> data ,qidx_ + tb * IQ * ID ,IQ * ID , 1373N ,IQ * ID ,n ,cs ); 1374norm_rope (qidx_ + tb * IQ * ID ,wiqn , (int ) (n * IQ ), (int )ID ,pos_i + tb * IQ ); 1375 }else { 1376for (int t = tb ;t < te ;++ t ) { 1377float * qc = qcur_ + t * NH * HD ; 1378if (fuse_nr ) { 1379native_qsa_rms_norm_rope (qfull_ + t * NH * 2 * HD , (int ) (2 * HD ), (const float * )wqn -> data ,qc , 1380 (int )NH , (int )HD , (int )s .n_rot ,EPS ,rope_scaling (),pos_ + t * NH ,cs ); 1381 }else { 1382/* 1383DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous 1384memcpy API. While the origin API might be synchronous, it 1385depends on the type of operand memory, so you may need to 1386call wait() on event return by memcpy API to ensure 1387synchronization behavior. 1388*/ 1389if (DPCT_CHECK_ERROR (dpct::async_dpct_memcpy ( 1390qc , (size_t )HD * 4 ,qfull_ + t * NH * 2 * HD , 1391 (size_t )HD * 2 * 4 , (size_t )HD * 4 , (size_t )NH , 1392 dpct::device_to_device ,* cs ))!= 0 ) { 1393err = "verify: the q/gate split failed" ; 1394return false; 1395 } 1396norm_rope (qc ,wqn , (int )NH , (int )HD ,pos_ + t * NH ); 1397 } 1398if (st .kv_rot )fwht256_inplace_cuda (qc ,NH ,cs );// <Hq, Hk> = <q, k> 1399 } 1400for (int t = tb ;t < te ;++ t ) { 1401float * qx = qidx_ + t * IQ * ID ; 1402bf16_gemv_fp32_mmvf (mixed_ + t * N , (const uint16_t * )wiq -> data ,qx , (int )N , (int ) (IQ * ID ),cs ); 1403norm_rope (qx ,wiqn , (int )IQ , (int )ID ,pos_ + t * NH ); 1404 } 1405 } 1406stamp (l ,10 ,grp ); 1407// STRATA_BATCH_ATTN_ROWS=1: the window's rows in ONE launch per step (scores with each row's own indexer 1408// keys, the top-k over all rows, attention with each row's own pools): the same per-row arithmetic. 1409// Not with KV streaming (qsa_kv_resolve has work per slot then). 1410static const bool attn_rows = [] { 1411const char * e = std::getenv ("STRATA_BATCH_ATTN_ROWS" ); 1412return e != nullptr && std::atoi (e )!= 0 ; 1413 }(); 1414bool rows_ok = batch_rec_ && attn_rows && te - tb <=kAttnRowsMax ; 1415for (int t = tb ;rows_ok && t < te ;++ t )rows_ok = slot_ss (t ).qsa_states [qi ].kv_mode != 1 ; 1416if (rows_ok ) { 1417const int n_rows = te - tb ; 1418QsaScoreRows sr ; 1419QsaAttnPoolsRows pr ; 1420sr .n = pr .n = n_rows ; 1421for (int t = tb ;t < te ;++ t ) { 1422const QsaState & sx = slot_ss (t ).qsa_states [qi ]; 1423sr .pooled [t - tb ]= sx .idx_pooled ; 1424sr .dead [t - tb ]= sx .idx_dead ; 1425pr .p [t - tb ]= qsa_attn_pools (sx ); 1426 } 1427qsa_block_scores_rows (sr ,qidx_ + tb * IQ * ID ,step_ + tb * kStepCount ,n_rows ,max_blocks_ ,s , 1428scores_ + (size_t )tb * max_blocks_ ,cs ); 1429qsa_block_topk (scores_ + (size_t )tb * max_blocks_ ,step_ + tb * kStepCount ,n_rows ,max_blocks_ ,cap_ , 1430s ,sel_ + (size_t )tb * cap_ ,cs ); 1431qsa_decode_attn_batch_rows (qcur_ + tb * NH * HD ,pr ,sel_ + (size_t )tb * cap_ ,step_ + tb * kStepCount , 1432cap_ ,s ,attn_scratch_ + (size_t )tb * attn_scratch_floats_ , 1433attn_ + tb * NH * HD ,n_rows ,cs ); 1434 }else 1435if (batch_rec_ ) {// each row selects and attends over its own slot's K/V 1436for (int t = tb ;t < te ;++ t ) { 1437const QsaState & sx = slot_ss (t ).qsa_states [qi ]; 1438qsa_block_scores (sx .idx_pooled ,sx .idx_dead ,qidx_ + t * IQ * ID ,step_ + t * kStepCount ,1 , 1439max_blocks_ ,s ,scores_ + (size_t )t * max_blocks_ ,cs ); 1440qsa_block_topk (scores_ + (size_t )t * max_blocks_ ,step_ + t * kStepCount ,1 ,max_blocks_ ,cap_ ,s , 1441sel_ + (size_t )t * cap_ ,cs ); 1442qsa_kv_resolve (sx ,* g_ ,sel_ + (size_t )t * cap_ ,step_ + t * kStepCount ,1 ,cap_ ,cs ); 1443const QsaAttnPools px = qsa_attn_pools (sx ); 1444qsa_decode_attn_batch (qcur_ + t * NH * HD ,px ,sel_ + (size_t )t * cap_ ,step_ + t * kStepCount , 1445cap_ ,s ,attn_scratch_ + (size_t )t * attn_scratch_floats_ , 1446attn_ + t * NH * HD ,1 ,cs ); 1447 } 1448 }else { 1449qsa_block_scores (st .idx_pooled ,st .idx_dead ,qidx_ + tb * IQ * ID ,step_ + tb * kStepCount ,n ,max_blocks_ , 1450s ,scores_ + (size_t )tb * max_blocks_ ,cs ); 1451qsa_block_topk (scores_ + (size_t )tb * max_blocks_ ,step_ + tb * kStepCount ,n ,max_blocks_ ,cap_ ,s , 1452sel_ + (size_t )tb * cap_ ,cs ); 1453stamp (l ,11 ,grp ); 1454// KV streaming: the n selections' blocks resident (device-side, inside the graph) 1455qsa_kv_resolve (st ,* g_ ,sel_ + (size_t )tb * cap_ ,step_ + tb * kStepCount ,n ,cap_ ,cs ); 1456stamp (l ,12 ,grp ); 1457const QsaAttnPools pools = qsa_attn_pools (st ); 1458qsa_decode_attn_batch (qcur_ + tb * NH * HD ,pools ,sel_ + (size_t )tb * cap_ ,step_ + tb * kStepCount ,cap_ , 1459s ,attn_scratch_ + (size_t )tb * attn_scratch_floats_ ,attn_ + tb * NH * HD ,n ,cs ); 1460 } 1461stamp (l ,13 ,grp ); 1462if (st .kv_rot || st .kv_hybrid )fwht256_inplace_cuda (attn_ + tb * NH * HD , (int64_t )n * NH ,cs );// back: H^-1 = H 1463if (qb )native_qsa_gate_apply (attn_ + tb * NH * HD ,qfull_ + tb * NH * 2 * HD ,attn32_ + tb * NH * HD , 1464 (int ) (n * NH ), (int )HD ,cs ); 1465else 1466for (int t = tb ;t < te ;++ t ) { 1467if (native_qsa_enabled ()) 1468native_qsa_gate_apply (attn_ + t * NH * HD ,qfull_ + t * NH * 2 * HD ,attn32_ + t * NH * HD , 1469 (int )NH , (int )HD ,cs ); 1470else 1471qsa_gate_apply_f32 (attn_ + t * NH * HD ,qfull_ + t * NH * 2 * HD ,s ,attn32_ + t * NH * HD ,cs ); 1472 } 1473stamp (l ,14 ,grp ); 1474native_quantize_q8_1 (attn32_ + tb * NH * HD ,xq_ , (int ) (NH * HD ),n ,cs ); 1475native_mmvq (wo -> native_type ,wo -> native_data ,xq_ ,bo_ + tb * N , (int ) (NH * HD ), (int )N ,n ,cs ); 1476 } 1477 }catch (const std::exception & e ) { 1478err = "verify layer " + std::to_string (l )+ ": " + e .what (); 1479return false; 1480 } 1481stamp (l ,16 ,grp ); 1482const bool q8_ffn = gr_read_group (1 , true,inj_ ,inj2_ );// true: nat_xq_ holds the MoE input's q8_1 (STRATA_QFUSE) 1483// with CPU experts in the window the shared expert forks off once the doorbell is published (it no longer 1484// competes with it for the GPU's first microseconds); STRATA_SH_FORK_LATE=0 forks at the top as before 1485static const bool sh_fork_late_env = [] { 1486const char * e = std::getenv ("STRATA_SH_FORK_LATE" ); 1487return !e || e [0 ]!= '0' ; 1488 }(); 1489const bool sh_fork = sh_stream_on ()&& !prof_on_ && !g_stepped && 1490sh_cs_ != & dpct::get_in_order_queue ()&& 1491ev_fork_ != nullptr && ev_join_ != nullptr ; 1492const bool sh_fork_late = sh_fork && sh_fork_late_env && !ar_on (); 1493 dpct::queue_ptr sh_stream = sh_fork ?sh_cs_ :cs ; 1494if (sh_fork && !sh_fork_late ) { 1495 dpct::sync_barrier (ev_fork_ ,cs ); 1496 (sh_cs_ )-> ext_oneapi_submit_barrier ({* ev_fork_ }); 1497 } 1498// the window's rows routed in 2 launches (one router GEMV reading the weight once, one 1499// top-10) instead of 2 per token; every row's arithmetic is the single-token call's (STRATA_DEC_BATCH=0: old) 1500const WeightRef * w_router = v .get ("ffn_gate_inp.weight" ); 1501// S26 STRATA_LFUSE=1: the shared expert's gate row rides in the router GEMV launch, its sigmoid + row scale 1502// move into the combine, gate + up share one launch (all bitwise; resident combine path, 2-8 rows only) 1503const WeightRef * w_sgi = lfuse_on (n )&& g_lfuse_gate () ?v .get ("ffn_gate_inp_shexp.weight" ) :nullptr ; 1504bool sg_ready = false; 1505if (dec_batch && n > 1 && w_router != nullptr && native_router_enabled ()&& (NE == 512 || NE == 256 )&& K == 10 ) { 1506try {// SYCL port: the fused multi-token router for 256 experts as well (it was 512-only) 1507if (w_sgi != nullptr ) 1508sg_ready = bf16_gemv_fp32_mmvf_multi_aux (mixed_ + tb * N ,N , (const uint16_t * )w_router -> data , 1509logits_ + tb * NE ,NE ,N ,NE ,n , 1510 (const uint16_t * )w_sgi -> data ,sh_g_ + tb ,1 ,cs ); 1511if (!sg_ready ) 1512bf16_gemv_fp32_mmvf_multi (mixed_ + tb * N ,N , (const uint16_t * )w_router -> data ,logits_ + tb * NE ,NE ,N , 1513NE ,n ,cs ); 1514native_router_top10_multi_ne (logits_ + tb * NE ,ids_ + tb * K ,w_ + tb * K ,n , (int )NE ,cs ); 1515 }catch (const std::exception & e ) {err = "verify router: " + std::string (e .what ());return false; } 1516#if defined(STRATA_HIP_GFX906 ) 1517} else if ( dec_batch ) { 1518// gfx906: the Coder's 256-expert router (the native router is 512 x 10 only) for the whole window in one 1519// multi-column BF16 projection and one top-k, bitwise the per-token calls (route_window_parity); ~3 ms 1520// of a ~55 ms verify window on 2x MI50. STRATA_ROUTE_PER_TOKEN=1: the per-token calls. 1521if (! moe_route_window ( wt , g , l , K , ss . moe , mixed_ + tb * N , logits_ + tb * NE , ids_ + tb * K , w_ + tb * K , n , 1522cs , err )) 1523return false; 1524#endif 1525} else 1526for ( int t = tb ; t < te ; ++ t ) { 1527MoEBuffers mb = ss . moe ; 1528mb . logits = logits_ + t * NE ; mb . ids = ids_ + t * K ; mb . weights = w_ + t * K ; 1529if (! moe_route ( wt , g , l , K , mb , mixed_ + t * N , cs , err , nullptr )) return false; 1530} 1531if ( expert_usage_counts_d_ ) 1532count_expert_routes ( cs , ids_ + tb * K , ( int )( n * K ), ( int ) l , 1533( int ) g . n_expert , expert_usage_counts_d_ ); 1534if ( ar_on ()) { 1535resident_plan ( ids_ + tb * K , n * ( int ) K , ( int ) K , hits_ . d_res + l * g . n_expert , ( int ) g . n_expert , 1536hits_ . cache_base , slot_off_d_ , ( long long ) hits_ . blob , 1537plan_ + ( size_t ) grp * ( size_t ) ( plan_i32_ + 16 ), ( long long ) max_t_ * K , nullptr , 0 , cs , m_plan_err_ ); 1538} else { 1539if ( device_plan_ ) // E-6: every routed expert resident: this group's plan without the host 1540resident_plan ( ids_ + tb * K , n * ( int ) K , ( int ) K , hits_ . d_res + l * g . n_expert , ( int ) g . n_expert , 1541hits_ . cache_base , slot_off_d_ , ( long long ) hits_ . blob , 1542plan_ + ( size_t ) grp * ( size_t ) ( plan_i32_ + 16 ), ( long long ) max_t_ * K , skip_ + grp , 1543( uint32_t ) (( l - lb_ ) * G + grp + 1 ), cs ); 1544#if defined( STRATA_USE_HIP ) 1545if ( g_doorbell_store ) // #649 A/B: the step's ring stored, not incremented over PCIe 1546doorbell_publish_value ( xm , ids_ + tb * K , w_ + tb * K , ( int64_t ) n * N , ( int64_t ) n * K , m_x_ + tb * N , 1547m_ids_ + tb * K , m_w_ + tb * K , m_seq_ , ( uint32_t ) (( l - lb_ ) * G + grp + 1 ), cs ); 1548else 1549#endif 1550// #578: the helper GPUs reduce with the routing weights - publish them; set_always_publish: the rows 1551// whatever the device's residency table says (pipelined windows) 1552if ( remote_opt_ || always_publish_ ) 1553doorbell_publish ( xm , ids_ + tb * K , w_ + tb * K , ( int64_t ) n * N , ( int64_t ) n * K , m_x_ + tb * N , 1554m_ids_ + tb * K , m_w_ + tb * K , m_seq_ , cs ); 1555else if (! lean ) { // (lean: nobody reads the doorbell) 1556const int32_t * layer_res = hits_ . d_res != nullptr ? ( hits_ . d_res + l * g . n_expert ) : nullptr ; 1557doorbell_publish_res ( xm , ids_ + tb * K , layer_res , ( int ) g . n_expert , ( int64_t ) n * N , ( int64_t ) n * K , 1558m_x_ + tb * N , m_ids_ + tb * K , m_seq_ , cs ); 1559} 1560if ( sh_fork_late ) { 1561dpct:: sync_barrier ( ev_fork_ , cs ); 1562( sh_cs_ ) -> ext_oneapi_submit_barrier ({ * ev_fork_ }); 1563} 1564if ( step_hook_ && ! step_hook_ ( l , grp )) { if ( err . empty ()) err = "verify: stepped serve failed" ; return false; } 1565} 1566stamp ( l , 17 , grp ); 1567bool qdedup = false; // STRATA_VERIFY_QDEDUP took effect: the experts' q8_1 image of xm is already made 1568{ 1569const WeightRef * wgi = need ( v , "ffn_gate_inp_shexp.weight" , err ), * wsg = need ( v , "ffn_gate_shexp.weight" , err ), 1570* wsu = need ( v , "ffn_up_shexp.weight" , err ), * wsd = need ( v , "ffn_down_shexp.weight" , err ); 1571if (! wgi || ! wsg || ! wsu || ! wsd ) return false; 1572if (! native_of ( wsg , v . name ( "ffn_gate_shexp.weight" ), err ) || ! native_of ( wsu , v . name ( "ffn_up_shexp.weight" ), err ) || 1573! native_of ( wsd , v . name ( "ffn_down_shexp.weight" ), err )) 1574return false; 1575NativeSharedWeights nsw ; 1576nsw . gate_type = wsg -> native_type ; nsw . gate_data = wsg -> native_data ; 1577nsw . up_type = wsu -> native_type ; nsw . up_data = wsu -> native_data ; 1578nsw . down_type = wsd -> native_type ; nsw . down_data = wsd -> native_data ; 1579nsw . q8_1 = sh_fork ? sh_xq_ : xq_ ; 1580// STRATA_VERIFY_QDEDUP=1 (not with the forked shared-expert stream, which quantizes into its own buffer): the 1581// experts' q8_1 image of xm is made first and the shared expert's gate/up read it (quantize_q8_1_rows and 1582// native_quantize_q8_1 write the same bytes) 1583qdedup = g_qdedup () && ! sh_fork && strata::kernels::cpu:: expert_layout (). native ; 1584if ( qdedup && ! q8_ffn ) quantize_q8_1_rows ( xm , n , N , nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 , cs ); 1585if (! shared_expert_native_bf16_enabled ()) { 1586if ( dec_batch ) f32_to_bf16_bulk ( mixed_ + tb * N , sh_bf16_ + tb * N , ( int64_t ) n * N , sh_stream ); // contiguous rows 1587else for ( int t = tb ; t < te ; ++ t ) f32_to_bf16_bulk ( mixed_ + t * N , sh_bf16_ + t * N , N , sh_stream ); 1588} 1589try { 1590shared_expert_multi ( n , xm , sh_bf16_ + tb * N , nsw , (const uint16_t * ) wgi -> data , sh_gate_ + ( size_t ) tb * g . n_ff , 1591sh_up_ + ( size_t ) tb * g . n_ff , sh_g_ + tb , shared_ + tb * N , N , g . n_ff , sh_stream , 1592qdedup ? (const void * ) ( nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 ) : nullptr , 1593( sg_ready ? 1 : 0 ) | ( lfuse_on ( n ) && g_lfuse_pair () ? 2 : 0 )); 1594sg_gated_ [ grp ] = sg_ready ; 1595} catch (const std:: exception & e ) { 1596err = std:: string ( "verify shared expert: " ) + e . what (); 1597return false; 1598} 1599if ( sh_fork ) dpct:: sync_barrier ( ev_join_ , sh_cs_ ); 1600} 1601if (strata::kernels::cpu:: expert_layout (). native ) { 1602// APR: Hadamard-folded gate/up take H (s * x); xm itself stays as it is (the shared expert above and the 1603// doorbell copy for the CPU pool, which rotates its own in native_quant_act). The q8_1 image of xm that 1604// STRATA_QFUSE / STRATA_VERIFY_QDEDUP may already have written is of the unrotated input, so a folded layer 1605// always rewrites it from the rotated rows (same stream, after the shared expert has read it). 1606const auto & f = strata::kernels::cpu:: expert_layout (). fmt [( size_t ) l ]; 1607if ( f . had_gu ) { // nat_xr_ exists: init carved it because this layer is folded (had_gu_any) 1608hadamard_rows ( xm , nat_xr_ + ( size_t ) tb * N , n , N , f . had_block , had_sx_ , cs ); 1609quantize_q8_1_rows ( nat_xr_ + ( size_t ) tb * N , n , N , nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 , cs ); 1610} else if (! qdedup && ! q8_ffn ) { 1611quantize_q8_1_rows ( xm , n , N , nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 , cs ); 1612} 1613} else 1614quantize_q8_0_scaled ( xm , hit_xq_ + ( size_t ) tb * ( N / 32 ) * 34 , hit_xs_ + ( size_t ) tb * ( N / 32 ), ( int64_t ) n * N , cs ); 1615stamp ( l , 18 , grp ); 1616return true; 1617}; 1618 1619// ---------------------------------------------------------------- post(l, group): experts, combine 1620static const bool fuse_head_gr_env = [] { 1621const char * e = std:: getenv ( "STRATA_FUSE_HEAD_GR" ); 1622return e && e [ 0 ] == '1' ; 1623}(); 1624const bool fuse_head_gr = fuse_head_gr_env && ( le_ == g . n_layers ) && ( head_ != nullptr && head_ -> loaded ()) && 1625! cvec (). covers ( g . n_layers - 1 ); 1626auto post = [ & ]( int64_t l , int grp ) -> bool { 1627const int tb = tb_ [ grp ], te = te_ [ grp ], n = te - tb ; 1628#ifdef STRATA_SYCL_WORKLOAD_TRACE 1629strata::workload_trace:: ContextGuard layer_context (strata::workload_trace:: context . position , n , l ); 1630#endif 1631strata::workload_trace:: Scope layer_trace ( "decode.layer.post" , cs , n , N ); 1632const uint32_t ring = ( uint32_t ) (( l - lb_ ) * G + grp + 1 ); 1633const int64_t cap = ( int64_t ) n * K , capx = ( int64_t ) max_t_ * K ; 1634int32_t * pl = plan_ + ( size_t ) grp * ( size_t ) ( plan_i32_ + 16 ); 1635const int32_t * p_counts = pl ; 1636const int32_t * p_start = pl + 4 ; 1637const int32_t * p_dst = p_start + capx + 1 ; 1638const int32_t * p_tok = p_dst + capx ; 1639const int64_t ptr_off = (( 4 + ( capx + 1 ) + 2 * capx ) + 1 ) & ~ 1ll ; 1640const unsigned long long * p_ptr = (const unsigned long long * ) ( pl + ptr_off ); 1641const unsigned long long * p_ptr2 = p_ptr + capx ; 1642const int32_t * p_start2 = pl + ptr_off + 4 * capx ; 1643float * hit_out = hit_out_ + ( size_t ) tb * K * N ; 1644float * parts_out = parts_ + ( size_t ) tb * K * N ; 1645const auto & lay = strata::kernels::cpu:: expert_layout (); 1646// plan v0.3 P6: the VRAM groups now; the PCIe groups once the copy engine has landed them in staging. 1647// `gy`: the native launch's groups side by side (0: cap, one block row per possible group). 1648auto grouped = [ & ](const unsigned long long * gp , const int32_t * gs , const int32_t * gn , int64_t gy , float * dst_buf ) { 1649if ( lay . native ) { 1650// the layer's GGUF formats (i-quant gate/up, Q2_0 / IQ4_NL down) 1651const auto & f = lay . fmt [( size_t ) l ]; 1652NativeExpertLayout L = native_expert_layout ( f . gu_type , f . d_type , f . n_embd , f . n_ff ); 1653if ( f . had_d ) { L . had_block = f . had_block ; L . d_signs = had_sh_ ; } // APR: h is rotated in there 1654if( b60_single_actor_requested () && b60_layout_requested ()){ 1655if(! lean || gy != 0 )throw std:: logic_error ( "B60 single staging needs the complete device plan" ); 1656b60_stage_single_experts ( const_cast < unsigned long long *> ( gp ), gn , int ( cap ), f . gu_type , size_t ( f . up_off ), size_t ( f . down_off ), size_t ( f . bytes ), cs ); 1657} 1658if (! b60_layout_requested () && gy == 0 && device_plan_ && env_on ( "STRATA_VERIFY_NO_HOST" ) && 1659env_on ( "STRATA_SYCL_EXPERT_STAGE" )) { 1660// NoHost device planning leaves no CPU/DMA owner of this existing workspace. 1661const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs ; 1662uint8_t * stage = staging_ + ( size_t )( grp * per ) * lay . max_blob ; 1663const char * batch_env = std:: getenv ( "STRATA_SYCL_EXPERT_STAGE_GROUPS" ); 1664const char * copy_env = std:: getenv ( "STRATA_SYCL_EXPERT_STAGE_COPY" ); 1665native_expert_grouped_staged ( L , gp , gs , gn , p_dst , p_tok , cap , cap , 1666nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 , hit_scratch_ , dst_buf , cs , 1667stage ,( size_t ) per * lay . max_blob , batch_env ? std:: atoi ( batch_env ) : 8 , 1668copy_env ? std:: atoi ( copy_env ) : 0 ); 1669} else { 1670native_expert_grouped ( L , gp , gs , gn , p_dst , p_tok , cap , cap , 1671nat_xq_ + ( size_t ) tb * ( N / 32 ) * 36 , hit_scratch_ , dst_buf , cs , gy ); 1672} 1673} else { 1674moe_grouped_s2 ( gp , gs , gn , p_dst , p_tok , cap , cap , hit_xq_ + ( size_t ) tb * ( N / 32 ) * 34 , 1675hit_xs_ + ( size_t ) tb * ( N / 32 ), hit_scratch_ , dst_buf , cs ); 1676} 1677}; 1678if ( ar_on ()) { 1679stamp ( l , 19 , grp ); 1680grouped ( p_ptr , p_start , p_counts , 0 , parts_out ); 1681stamp ( l , 20 , grp ); 1682} else { 1683if ( device_plan_ ) { // E-6: skipped when the device planned this group (all its experts resident) 1684if (! lean ) wait_flag_ge_or ( m_flagA_ , ring , skip_ + grp , cs ); 1685if (! lean ) copy_i32_from_mapped_unless ( pl , m_plan_ + ( size_t ) grp * ( size_t ) plan_i32_ , plan_i32_ , skip_ + grp , ring , cs ); 1686} else { 1687wait_flag_ge ( m_flagA_ , ring , cs ); // the pool published this group's GPU plan 1688copy_i32_from_mapped ( pl , m_plan_ + ( size_t ) grp * ( size_t ) plan_i32_ , plan_i32_ , cs ); 1689} 1690stamp ( l , 19 , grp ); 1691grouped ( p_ptr , p_start , p_counts , 0 , hit_out ); 1692stamp ( l , 20 , grp ); 1693// stepped mode: the plan copy + VRAM groups end a segment, so they run while the CPU computes its rows 1694if ( step_hook2_ && ! step_hook2_ ( l , grp )) { if ( err . empty ()) err = "verify: stepped split failed" ; return false; } 1695if ( device_plan_ ) { if (! lean ) wait_flag_ge_or ( m_flagB_ , ring , skip_ + grp , cs ); } 1696else wait_flag_ge ( m_flagB_ , ring , cs ); // the PCIe share is in staging (DMA) or mapped 1697if (! lean && sink_ . pcie_mode == 2 ) { // stage it with a copy kernel, then point at staging 1698const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs ; 1699uint8_t * stage = staging_ + ( size_t ) ( grp * per ) * lay . max_blob ; 1700fetch_blobs ( p_ptr2 , p_counts + 2 , stage , ( int64_t ) lay . blob_bytes ( l ), ( int ) per , cs ); 1701rebase_ptrs (( unsigned long long * ) p_ptr2 , p_counts + 2 , stage , ( int64_t ) lay . blob_bytes ( l ), cs ); 1702} 1703stamp ( l , 21 , grp ); 1704// the PCIe share is pcie_frac of the misses: a few groups when the cache is cold, usually none (always none at 1705// pcie_frac 0), so its launch is kPcieGroupRows block rows striding over the groups, not cap of them 1706if (! lean ) grouped ( p_ptr2 , p_start2 , p_counts + 2 , kPcieGroupRows , hit_out ); // (lean: the device plan leaves it empty) 1707stamp ( l , 22 , grp ); 1708if ( device_plan_ ) { // no CPU share when the device planned the group: its rows are zeros 1709if (! lean ) wait_flag_ge_or ( m_flag_ , ring , skip_ + grp , cs ); 1710copy_or_zero_from_mapped ( parts_out , m_ymiss_ + ( size_t ) tb * K * N , ( long long ) n * K * N , 1711skip_ + grp , ring , cs ); 1712} else { 1713wait_flag_ge ( m_flag_ , ring , cs ); // the CPU's share is in the mapped rows 1714stamp ( l , 23 , grp ); 1715if ( remote_opt_ ) // #578: the helper's rows come back reduced; skip them as well 1716remote_opt_ -> copy_rows ( parts_out , m_ymiss_ + ( size_t ) tb * K * N , tb , n , p_dst , p_counts + 1 , cs ); 1717else if ( dec_batch ) // only the CPU rows cross PCIe (p_dst[0, counts[1]) = the GPU's own rows) 1718copy_rows_from_mapped ( parts_out , m_ymiss_ + ( size_t ) tb * K * N , ( int64_t ) n * K , N , 1719p_dst , p_counts + 1 , cs ); 1720else 1721copy_from_mapped ( parts_out , m_ymiss_ + ( size_t ) tb * K * N , ( int64_t ) n * K * N , cs ); 1722} 1723moe_hit_add ( parts_out , hit_out , p_dst , p_counts + 1 , cap , N , cs ); 1724} 1725// Same condition as `sh_fork` above, which is per group and out of scope here: wait only when the fork 1726// actually ran (a wait on an event never recorded is a no-op, but saying it outright reads better). 1727if ( sh_stream_on () && ! prof_on_ && 1728sh_cs_ != & dpct:: get_in_order_queue () && ev_fork_ != nullptr && 1729ev_join_ != nullptr ) { 1730cs -> ext_oneapi_submit_barrier ({ * ev_join_ }); 1731} 1732if ( sg_gated_ [ grp ]) { // STRATA_LFUSE: the shared expert's gate was not applied: the combine applies it (all rows are hits) 1733try { 1734native_moe_combine_multi_hits_gated ( parts_out , w_ + tb * K , shared_ + tb * N , sh_g_ + tb , bo_ + tb * N , N , K , n , cs ); 1735} catch (const std:: exception & e ) { err = "verify combine: " + std:: string ( e . what ()); return false; } 1736} else 1737if ( dec_batch && n > 1 && native_moe_combine_enabled ()) { // one launch for the window's rows 1738try { 1739native_moe_combine_multi ( parts_ + ( size_t ) tb * K * N , w_ + tb * K , shared_ + tb * N , bo_ + tb * N , N , K , n , cs ); 1740} catch (const std:: exception & e ) { err = "verify combine: " + std:: string ( e . what ()); return false; } 1741} else 1742for ( int t = tb ; t < te ; ++ t ) { 1743MoEBuffers mb = ss . moe ; 1744mb . weights = w_ + t * K ; mb . shared = shared_ + t * N ; 1745if (! moe_combine_parts ( g , l , K , mb , parts_ + ( size_t ) t * K * N , bo_ + t * N , cs , err )) return false; 1746} 1747if ( remote_opt_ ) remote_opt_ -> combine ( bo_ + tb * N , y_dummy_ + tb * N , tb , n , 1748device_plan_ ? skip_ + grp : nullptr , ring , cs ); 1749stamp ( l , 24 , grp ); 1750if ( tap_on_ && ! batch_rec_ && l < ( int64_t ) tap_slot_ . size () && tap_slot_ [( size_t ) l ] >= 0 ) { 1751// the layer's completed output: R with this FFN half's write applied (the next layer's read would fold it), the mean of the hc streams, 1752// all rows of the group in one launch 1753const int64_t nt = ( int64_t ) tap_layers_ . size (); 1754strata::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 , 1755nt * N , n , N , ( int ) HC , cs ); 1756} 1757#ifdef STRATA_SYCL_WORKLOAD_TRACE 1758if ( auto audit = routing_audits . find ( this ); audit != routing_audits . end ()) 1759cs -> memcpy ( audit -> second -> slot ( l , grp ), pl , ( size_t ) plan_i32_ * sizeof( int32_t )); 1760#endif 1761if ( l == g . n_layers - 1 ) { 1762if (! fuse_head_gr ) { 1763if ( dec_batch && ! g_no_multi_gr ) gr_write_multi ( Rt ( tb ), bo_ + tb * N , inj2_ + tb * HC , gs , Rt ( tb ), n , cs ); 1764else for ( int t = tb ; t < te ; ++ t ) gr_write ( Rt ( t ), bo_ + t * N , inj2_ + t * HC , gs , Rt ( t ), cs ); 1765if ( cvec (). covers ( l )) cvec_apply ( Rt ( tb ), l , n , HC * N , nullptr , 0 , nullptr , 0 , false, cs ); 1766} 1767} else if ( cvec (). covers ( l )) { 1768cvec_apply ( Rt ( tb ), l , n , HC * N , bo_ + tb * N , N , inj2_ + tb * HC , HC , true, cs ); 1769} 1770return true; 1771}; 1772 1773for ( int grp = 0 ; grp < G ; ++ grp ) 1774if (! pre ( lb_ , grp )) return false; 1775for ( int64_t l = lb_ ; l < le_ ; ++ l ) 1776for ( int grp = 0 ; grp < G ; ++ grp ) { 1777if (! post ( l , grp )) return false; 1778if ( dbgR_ && grp == 0 ) { // recorded into the window graph as memcpy nodes 1779cs -> memcpy ( dbgR_ + ( size_t ) l * N , Rt ( 0 ), ( size_t ) N * 4 ); 1780cs -> memcpy ( dbgM_ + ( size_t ) l * N , mixed_ , ( size_t ) N * 4 ); 1781} 1782if ( l + 1 < le_ && ! pre ( l + 1 , grp )) return false; 1783} 1784if ( le_ < g . n_layers ) { // a layer split's earlier stage: hand the residual on, no head 1785float * hout = hand_out_ + ( size_t ) hrow0 * HB ; 1786copy_from_mapped ( hout , R_ , ( int64_t ) T * HC * N , cs ); 1787copy_from_mapped ( hout + ( size_t ) T * HC * N , bo_ , ( int64_t ) T * N , cs ); 1788copy_from_mapped ( hout + ( size_t ) T * ( HC + 1 ) * N , inj2_ , ( int64_t ) T * HC , cs ); 1789return true; 1790} 1791 1792// ---- the head, T columns, and the argmax of each 1793stamp ( g . n_layers , 0 , 0 ); 1794{ 1795const WeightRef * hn = wt . find ( "output_hc_norm.weight" ), * hd = wt . find ( "output_hc_down.weight" ), 1796* hu = wt . find ( "output_hc_up.weight" ); 1797if (! hn || ! hd || ! hu ) { err = "verify: an output_hc_* weight is missing" ; return false; } 1798// S25 (STRATA_HC_Q8=1): the final mixer from the GGUF's Q8_0 projections too, through the same multi read 1799// (no pending write, no inject) 1800bool b60_head_q8 = false; 1801const bool mix_q8 = hd -> hc_q8 != nullptr && hu -> hc_q8 != nullptr && head_ != nullptr && head_ -> loaded (); 1802if ( mix_q8 ) { 1803FusedGrArgs fa [ kFusedGrMaxT ]; 1804for ( int t = 0 ; t < T ; ++ t ) { 1805FusedGrArgs & a = fa [ t ]; 1806a . R = Rt ( t ); a . R_out = Rt ( t ); a . apply = false; 1807a . w_norm = (const float * ) hn -> data ; a . w_down = (const uint16_t * ) hd -> data ; 1808a . w_up = (const uint16_t * ) hu -> data ; a . w_inject = nullptr ; 1809a . q8_down = (const uint8_t * ) hd -> hc_q8 ; a . q8_up = (const uint8_t * ) hu -> hc_q8 ; 1810a . eps = EPS ; a . lo = lo_ + t * g . hc_lr ; a . rs = rs_ + t * HC ; 1811a . mixed = head_mixed_ + t * N ; if( b60_gr_q8_requested () && T == 1 ) a . q8_mixed = xq_ + size_t ( t ) * ( N / 32 ) * 36 ; 1812} 1813b60_head_q8 = fused_gr_read_multi ( fa , T , xn_ , cs ); 1814} 1815else if ( fuse_head_gr ) { 1816FusedGrArgs fa [ kFusedGrMaxT ]; 1817for ( int t = 0 ; t < T ; ++ t ) { 1818FusedGrArgs & a = fa [ t ]; 1819a . R = Rt ( t ); a . R_out = Rt ( t ); a . apply = true; 1820a . bo_prev = bo_ + t * N ; a . inj_prev = inj2_ + t * HC ; 1821a . w_norm = (const float * ) hn -> data ; 1822a . w_down = (const uint16_t * ) hd -> data ; 1823a . w_up = (const uint16_t * ) hu -> data ; 1824a . w_inject = nullptr ; 1825a . eps = EPS ; 1826a . lo = lo_ + t * g . hc_lr ; 1827a . rs = rs_ + t * HC ; 1828a . inject_out = head_inj_ ; 1829a . mixed = head_mixed_ + t * N ; if( b60_gr_q8_requested () && T == 1 ) a . q8_mixed = xq_ + size_t ( t ) * ( N / 32 ) * 36 ; 1830} 1831b60_head_q8 = fused_gr_read_multi ( fa , T , xn_ , cs ); 1832} else if ( head_mix_multi_enabled () && head_ != nullptr && head_ -> loaded ()) { 1833// the final mixer, the window's tokens in one read (fused_gr_read_multi without the pending write: the 1834// last layer's write was done above; its sums are gr_read's) 1835if ( hn -> kind != WeightKind :: F32 || hd -> kind != WeightKind :: Bf16InF32 || hu -> kind != WeightKind :: Bf16InF32 ) { 1836err = "verify: the output_hc_* weights have the wrong engine forms" ; 1837return false; 1838} 1839FusedGrArgs fa [ kFusedGrMaxT ]; 1840for ( int t = 0 ; t < T ; ++ t ) { 1841fa [ t ]. R = Rt ( t ); fa [ t ]. R_out = Rt ( t ); fa [ t ]. apply = false; 1842fa [ t ]. w_norm = (const float * ) hn -> data ; fa [ t ]. w_down = (const uint16_t * ) hd -> data ; 1843fa [ t ]. w_up = (const uint16_t * ) hu -> data ; fa [ t ]. eps = EPS ; 1844fa [ t ]. lo = lo_ + t * g . hc_lr ; fa [ t ]. rs = rs_ + t * HC ; fa [ t ]. mixed = head_mixed_ + t * N ; if( b60_gr_q8_requested () && T == 1 ) fa [ t ]. q8_mixed = xq_ + size_t ( t ) * ( N / 32 ) * 36 ; 1845} 1846b60_head_q8 = fused_gr_read_multi ( fa , T , xn_ , cs ); 1847} else { 1848for ( int t = 0 ; t < T ; ++ t ) { 1849BlockBuffers bb = ss . block ; 1850bb . R = Rt ( t ); 1851bb . mixed = head_mixed_ + t * N ; 1852if ( head_ != nullptr && head_ -> loaded ()) { 1853if (! lm_head_mix ( wt , g , bb , cs , err )) return false; 1854} else if (! lm_head ( wt , g , bb , head_logits_ + ( size_t ) t * n_vocab_ , cs , err )) { 1855return false; 1856} 1857} 1858} 1859if ( head_ != nullptr && head_ -> loaded ()) { 1860try { 1861if(! b60_head_q8 ) native_quantize_q8_1 ( head_mixed_ , xq_ , ( int ) N , T , cs ); 1862native_mmvq ( head_ -> type (), head_ -> weights (), xq_ , head_logits_ , ( int ) N , ( int ) n_vocab_ , T , cs ); 1863} catch (const std:: exception & e ) { 1864err = std:: string ( "verify head: " ) + e . what (); 1865return false; 1866} 1867} 1868// Greedy, the default, is recorded here as before (no extra launch or sync per window). A request that 1869// samples or penalizes is sampled again host-side after the replay (run()) with its own parameters and a 1870// fresh draw counter: a captured sampler would bake them in and replay the same draws forever. 1871if ( argmax_rows_wanted ()) { // sm_80 to sm_89: the pick over many blocks a row (bitwise the one-block kernel's) 1872argmax_rows ( head_logits_ , T , ( int ) n_vocab_ , arg_scratch_ , m_out_ , cs ); 1873} else { 1874SamplerParams sp ; 1875sp . greedy = true; 1876sp . temperature = 0.0f ; 1877sample_tokens ( head_logits_ , T , ( int ) n_vocab_ , nullptr , 0 , sp , m_out_ , cs ); 1878} 1879} 1880stamp ( g . n_layers , 1 , 0 ); 1881return true; 1882} 1883 1884// SYCL port: a failed queue wait reported as what it was. DPCT_CHECK_ERROR keeps only "error" from the SYCL 1885// exception and drops the device, which made a pipelined-window failure on a layer split impossible to place: 1886// the same text came from either card and from any of the four verifiers. These two helpers say which. 1887static dpct:: err0 queue_wait_diag (sycl:: queue * cs , int dev , const char * what ) { 1888if ( cs == nullptr ) return dpct:: default_error ; 1889try { 1890cs -> wait (); 1891return dpct:: success ; 1892} catch (std:: exception const & e ) { 1893std:: string qdev = "<unknown>" ; 1894try { qdev = cs -> get_device (). get_info < sycl::info::device:: name > (); } catch (...) {} 1895std:: fprintf ( stderr , "strata verify: %s: the queue wait failed on verifier device %d (queue device: %s): %s\n" , 1896what , dev , qdev . c_str (), e . what ()); 1897std:: fflush ( stderr ); 1898return dpct:: default_error ; 1899} 1900} 1901 1902std:: string Verifier :: profile_report () { 1903if (! prof_on_ || prof_windows_ == 0 ) return std:: string (); 1904static const char * names [ kProfPer ] = { "-" , "hc-read0" , "q8+qkv/q-idx gemv" , "conv" , "ab" , "z" , "rec" , "q8+kv-idx" , 1905"k/v+norm-rope" , "kv+idx append" , "q+q-idx" , "scores+topk" , "kv-resolve" , 1906"attention" , "gate" , "" , "out-proj" , "hc-read1+router" , "shared+quant" , 1907"waitA" , "VRAM hits" , "waitB" , "PCIe grp" , "waitCPU" , "copy+combine" , 1908"(gap)" , "head" , " hc0 norm" , " hc0 down" , " hc0 up" , "" , "" , "" }; 1909std:: string out ; 1910char b [ 80 ]; 1911double total = 0 ; 1912for ( int k = 0 ; k < 2 ; ++ k ) { 1913out += k == 0 ? " GDN layers:" : " | QSA layers:" ; 1914for ( int i = 0 ; i < kProfPer ; ++ i ) { 1915if ( prof_sum_ [ k ][ i ] <= 0 ) continue; 1916total += prof_sum_ [ k ][ i ]; 1917std:: snprintf ( b , sizeof b , " %s %.2f" , names [ i ], prof_sum_ [ k ][ i ] / 1e6 / ( double ) prof_windows_ ); 1918out += b ; 1919} 1920} 1921std:: snprintf ( b , sizeof b , " | total %.2f ms/window over %lld windows" , total / 1e6 / ( double ) prof_windows_ , ( long long ) prof_windows_ ); 1922out += b ; 1923for ( auto & r : prof_sum_ ) for ( double & d : r ) d = 0 ; 1924prof_windows_ = 0 ; 1925return out ; 1926} 1927 1928// #871: is the zero-doorbell graph right for the next window? Only while every expert of [lb_, le_) is in VRAM now 1929// (the host table is the one the device copy was uploaded from; a loan, a VRAM shrink or a swap in flight has 1930// marked some -1). Not: the doorbell graph, which asks the pool for what the device does not hold. 1931void Verifier :: refresh_ar () { 1932if (! all_resident_ || h_res_ == nullptr || g_ == nullptr ) return; 1933const int64_t ne = g_ -> n_expert ; 1934const int32_t * r = h_res_ + lb_ * ne ; 1935const int64_t n = ( le_ < 0 ? g_ -> n_layers : le_ ) * ne - lb_ * ne ; 1936int32_t lo = 0 ; 1937for ( int64_t i = 0 ; i < n ; ++ i ) lo = std:: min ( lo , r [ i ]); 1938const bool off = lo < 0 ; 1939if ( off != ar_off_ ) { 1940ar_off_ = off ; 1941std:: fprintf ( stderr , "strata verify: layers [%lld, %lld) %s\n" , ( long long ) lb_ , ( long long ) ( le_ < 0 ? g_ -> n_layers : le_ ), 1942off ? "have experts out of VRAM (a prompt loan, a shrink or a swap): the doorbell graph runs the windows" 1943: "are 100% VRAM resident again: the zero-doorbell graph" ); 1944} 1945} 1946 1947bool Verifier :: capture_segments ( int T , std:: string & err ) try { 1948if (! seg_ [ T ]. empty ()) return true; 1949// every segment's payload is read after the segment drained: its publishes store plainly (elementwise.dp.cpp) 1950struct PlainPayload { 1951PlainPayload () { strata::kernels:: doorbell_plain_payload (! window_host_uncached ()); } 1952~ PlainPayload () { strata::kernels:: doorbell_plain_payload (false); } 1953} plain_payload ; 1954namespace sx = sycl::ext::oneapi::experimental; 1955auto close_segment = [ & ]() -> bool { 1956dpct::experimental:: command_graph_ptr gph = nullptr ; 1957dpct::experimental:: end_recording ( cs_ , & gph ); 1958if ( gph == nullptr ) { err = "verify: segment capture produced no graph" ; return false; } 1959seg_ [ T ]. push_back (new sx:: command_graph < sx::graph_state:: executable > ( gph -> finalize ())); 1960delete gph ; 1961return true; 1962}; 1963auto boundary = [ & ]( int64_t l , int grp , char kind ) -> bool { 1964if (! close_segment ()) return false; 1965seg_at_ [ T ]. push_back ({ l , grp }); 1966seg_kind_ [ T ]. push_back ( kind ); 1967dpct::experimental:: begin_recording ( cs_ ); 1968return true; 1969}; 1970dpct::experimental:: begin_recording ( cs_ ); 1971step_hook_ = [ & ]( int64_t l , int grp ) { return boundary ( l , grp , 1 ); }; 1972static const bool split_on = [] { const char * e = std:: getenv ( "STRATA_VERIFY_SPLIT" ); return !( e && e [ 0 ] == '0' ); }(); 1973if ( split_on ) step_hook2_ = [ & ]( int64_t l , int grp ) { return boundary ( l , grp , 0 ); }; 1974std:: string rerr ; 1975const bool ok = record_window ( T , cs_ , rerr ); 1976step_hook_ = nullptr ; 1977step_hook2_ = nullptr ; 1978const bool closed = close_segment (); 1979if (! ok || ! closed ) { 1980for ( auto * e : seg_ [ T ]) delete e ; 1981seg_ [ T ]. clear (); seg_at_ [ T ]. clear (); seg_kind_ [ T ]. clear (); 1982if ( err . empty ()) err = "verify: segment capture: " + rerr ; 1983return false; 1984} 1985if (std:: getenv ( "STRATA_VERIFY_NODES" ) != nullptr ) 1986std:: fprintf ( stderr , "strata verify: the %d-token window as %zu graph segments\n" , T , seg_ [ T ]. size ()); 1987return true; 1988} 1989catch (sycl:: exception const & exc ) { 1990err = std:: string ( "verify: segment capture: " ) + exc . what (); 1991return false; 1992} 1993 1994bool Verifier :: capture ( int T , std:: string & err ) try { 1995// stepped mode: the doorbell window as segments; the all-resident (zero-doorbell) graph has no serves and is 1996// captured whole below, its one host flag raised before launch (run) 1997if ( g_stepped && ! ar_on () && std:: getenv ( "STRATA_VERIFY_EAGER" ) == nullptr ) return capture_segments ( T , err ); 1998dpct::experimental:: command_graph_exec_ptr & exec_t = 1999ar_off_ ? exec_nr_ [ T ] : exec_ [ T ]; 2000if ( exec_t != nullptr ) return true; 2001if (std:: getenv ( "STRATA_VERIFY_EAGER" ) != nullptr ) return true; // SYCL port: no graph, run() replays the body 2002if ( DPCT_CHECK_ERROR (dpct::experimental:: begin_recording ( cs_ )) != 0 ) { 2003err = "verify: begin capture failed" ; 2004return false; 2005} 2006std:: string rerr ; 2007const bool ok = record_window ( T , cs_ , rerr ); 2008dpct::experimental:: command_graph_ptr graph = nullptr ; 2009const dpct:: err0 ce = 2010DPCT_CHECK_ERROR (dpct::experimental:: end_recording ( cs_ , & graph )); 2011if (! ok ) { 2012if ( graph ) delete ( graph ); 2013err = rerr ; 2014return false; 2015} 2016/* 2017DPCT1000: Error handling if-stmt was detected but could not be rewritten. 2018*/ 2019if ( ce != 0 ) { 2020/* 2021DPCT1009: SYCL reports errors using exceptions and does not use error 2022codes. Please replace the "get_error_string_dummy(...)" with a real 2023error-handling function. 2024*/ 2025/* 2026DPCT1001: The statement could not be removed. 2027*/ 2028err = std:: string ( "verify: end capture: " ) + 2029dpct:: get_error_string_dummy ( ce ); 2030return false; 2031} 2032if (std:: getenv ( "STRATA_VERIFY_NODES" ) != nullptr ) { // what the window graph holds 2033size_t nn = 0 ; 2034dpct::experimental:: get_nodes ( graph , nullptr , & nn ); 2035std:: vector < dpct::experimental:: node_ptr > nodes ( nn ); 2036dpct::experimental:: get_nodes ( graph , nodes . data (), & nn ); 2037std:: map < std:: string , int > kinds ; 2038for (dpct::experimental:: node_ptr nd : nodes ) { 2039sycl::ext::oneapi::experimental:: node_type ty ; 2040ty = nd -> get_type (); 2041std:: string name = "type" + std:: to_string (( int ) ty ); 2042if ( ty == sycl::ext::oneapi::experimental::node_type:: kernel ) { 2043name = "kernel" ; // SYCL: no kernel-name introspection on graph nodes 2044} else if ( ty == sycl::ext::oneapi::experimental::node_type:: memcpy ) 2045name = "memcpy" ; 2046else if ( ty == sycl::ext::oneapi::experimental::node_type:: memset ) 2047name = "memset" ; 2048++ kinds [ name ]; 2049} 2050std:: vector < std:: pair < int , std:: string >> v ; 2051for ( auto & [ k2 , c ] : kinds ) v . push_back ({ c , k2 }); 2052std:: sort ( v . rbegin (), v . rend ()); 2053std:: fprintf ( stderr , "strata verify: the %d-token window graph has %zu nodes:" , T , nn ); 2054for ( size_t i = 0 ; i < v . size () && i < 40 ; ++ i ) std:: fprintf ( stderr , " %d x %.60s;" , v [ i ]. first , v [ i ]. second . c_str ()); 2055std:: fprintf ( stderr , "\n" ); 2056} 2057const dpct:: err0 ie = DPCT_CHECK_ERROR ( 2058exec_t = new sycl::ext::oneapi::experimental:: command_graph < 2059sycl::ext::oneapi::experimental::graph_state:: executable > ( 2060graph -> finalize ())); 2061delete ( graph ); 2062/* 2063DPCT1000: Error handling if-stmt was detected but could not be rewritten. 2064*/ 2065if ( ie != 0 ) { 2066/* 2067DPCT1009: SYCL reports errors using exceptions and does not use error 2068codes. Please replace the "get_error_string_dummy(...)" with a real 2069error-handling function. 2070*/ 2071/* 2072DPCT1001: The statement could not be removed. 2073*/ 2074err = std:: string ( "verify: instantiate: " ) + 2075dpct:: get_error_string_dummy ( ie ); 2076return false; 2077} 2078/* 2079DPCT1007: Migration of cudaGraphUpload is not supported. 2080*/ 2081const dpct:: err0 ue = 0 ; // no cudaGraphUpload on SYCL: a finalized command_graph is already resident 2082const dpct:: err0 us = DPCT_CHECK_ERROR ( cs_ -> wait ()); 2083std:: fprintf ( 2084stderr , 2085"strata verify: captured the %d-token window (upload %s, sync %s)\n" , T , 2086/* 2087DPCT1009: SYCL reports errors using exceptions and does not use error 2088codes. Please replace the "get_error_string_dummy(...)" with a real 2089error-handling function. 2090*/ 2091dpct:: get_error_string_dummy ( ue ), dpct:: get_error_string_dummy ( us )); 2092return true; 2093} 2094catch (sycl:: exception const & exc ) { 2095std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 2096<< ", line:" << __LINE__ << std:: endl ; 2097std:: exit ( 1 ); 2098} 2099 2100bool Verifier :: capture_commit (std:: string & err ) try { 2101if ( commit_exec_ != nullptr ) return true; 2102using namespace strata:: kernels ; 2103const ModelGeometry & g = * g_ ; 2104SessionState & ss = * ss_ ; 2105const QsaShapes s = shapes_of ( g ); 2106const int64_t C = g . ssm_conv_channels , HV = g . ssm_v_heads , ID = g . idx_key_dim , MT = max_t_ ; 2107const uint64_t gdn_floats = ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size + 2108( uint64_t ) g . ssm_conv_channels * ( g . ssm_d_conv - 1 ); 2109const int64_t TS = ( s . idx_block - 1 ) * ID ; 2110const int64_t HS = ( int64_t ) NG_HIST * NG_HC_DIM ; 2111if ( DPCT_CHECK_ERROR (dpct::experimental:: begin_recording ( cs_ )) != 0 ) { 2112err = "verify: begin commit capture failed" ; 2113return false; 2114} 2115bool ok = true; 2116try { 2117copy_i32_from_mapped ( commit_ , m_commit_ , 2 + MT , cs_ ); 2118int64_t qsa_index = 0 , gdn_index = 0 ; 2119for ( int64_t l = 0 ; l < lb_ ; ++ l ) ( is_qsa_layer ( g , l ) ? qsa_index : gdn_index ) += 1 ; 2120for ( int64_t l = lb_ ; l < le_ && ok ; ++ l ) { 2121const LayerView v ( * wt_ , l ); 2122if (! is_qsa_layer ( g , l )) { 2123const WeightRef * wnm = need ( v , "ssm_norm.weight" , err ); 2124if (! wnm ) { ok = false; break; } 2125float * state = ss . gdn_state + ( size_t ) ( gdn_index - ss . gdn_ord0 ) * gdn_floats ; 2126float * conv = state + ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size ; 2127const float * qkv = qkv_L_ + ( size_t ) gdn_index * MT * C ; 2128gdn_conv_commit ( conv , qkv , ( int ) C , commit_ , cs_ ); 2129static const bool state_only = [] { const char * e = std:: getenv ( "STRATA_SYCL_GDN_STATE_COMMIT" ); return e && e [ 0 ] == '1' ; }(); 2130if( state_only ) 2131gdn_commit_state_multi ( state , h_L_ + ( size_t ) gdn_index * MT * C ,( int ) C , 2132gate_L_ + ( size_t ) gdn_index * MT * HV , beta_L_ + ( size_t ) gdn_index * MT * HV , 2133( int ) g . ssm_k_heads ,( int ) HV ,( int ) MT , commit_ , cs_ ); 2134else { 2135gdn_step_norm_multi ( state , h_L_ + ( size_t ) gdn_index * MT * C , ( int ) C , gate_L_ + ( size_t ) gdn_index * MT * HV , 2136beta_L_ + ( size_t ) gdn_index * MT * HV , z_ , (const float * ) wnm -> data , EPS , y_dummy_ , 2137( int ) g . ssm_k_heads , ( int ) HV , ( int ) MT , commit_ , cs_ , 2138( int ) MT ); // S26: t_out_begin = MT - the replay's outputs (y_dummy_) are never read 2139} 2140++ gdn_index ; 2141} else { 2142const QsaState & st = ss . qsa_states [ qsa_index ]; 2143const WeightRef * wikn = need ( v , "indexer.k_norm.weight" , err ); 2144if (! wikn ) { ok = false; break; } 2145copy_from_mapped ( st . idx_tail , tail_snap_ + ( size_t ) qsa_index * TS , TS , cs_ ); 2146const QsaIndexerBuffers ib { st . idx_tail , st . idx_dead , st . idx_pooled , st . idx_block_pos }; 2147if (! g_no_batch_kv ) { 2148native_qsa_indexer_append_steps ( idx_raw_L_ + ( size_t ) qsa_index * MT * ID , commit_ + 2 , 1 , ( int ) MT , 0 , 2149(const float * ) wikn -> data , EPS , ib , s , st . max_cells , rope_scaling (), cs_ ); 2150} else { 2151for ( int64_t t = 0 ; t < MT ; ++ t ) 2152native_qsa_indexer_append ( idx_raw_L_ + ( size_t ) ( qsa_index * MT + t ) * ID , commit_ + 2 + t , 0 , 2153(const float * ) wikn -> data , EPS , ib , s , st . max_cells , 2154rope_scaling (), cs_ ); 2155} 2156++ qsa_index ; 2157} 2158} 2159if ( ok && ss . ple . ready () && ple_stage ()) copy_indexed ( ss . ple . hist , hist_snap_ , HS , commit_ + 1 , HS , cs_ ); 2160} catch (const std:: exception & e ) { 2161err = std:: string ( "verify commit: " ) + e . what (); 2162ok = false; 2163} 2164dpct::experimental:: command_graph_ptr graph = nullptr ; 2165const dpct:: err0 ce = 2166DPCT_CHECK_ERROR (dpct::experimental:: end_recording ( cs_ , & graph )); 2167if (! ok ) { 2168if ( graph ) delete ( graph ); 2169return false; 2170} 2171if ( ce != 0 || 2172DPCT_CHECK_ERROR ( 2173commit_exec_ = new sycl::ext::oneapi::experimental:: command_graph < 2174sycl::ext::oneapi::experimental::graph_state:: executable > ( 2175graph -> finalize ())) != 0 ) { 2176if ( graph ) delete ( graph ); 2177/* 2178DPCT1009: SYCL reports errors using exceptions and does not use error 2179codes. Please replace the "get_error_string_dummy(...)" with a real 2180error-handling function. 2181*/ 2182err = std:: string ( "verify: commit capture: " ) + 2183dpct:: get_error_string_dummy ( ce ); 2184return false; 2185} 2186delete ( graph ); 2187return true; 2188} 2189catch (sycl:: exception const & exc ) { 2190std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 2191<< ", line:" << __LINE__ << std:: endl ; 2192std:: exit ( 1 ); 2193} 2194 2195void Verifier :: stage_inputs ( int T , const int32_t * tokens , int64_t pos0 ) { 2196using namespace strata:: kernels ; 2197const ModelGeometry & g = * g_ ; 2198const QsaShapes s = shapes_of ( g ); 2199int32_t * const pk = h_pos_ + ( size_t ) max_t_ * g . n_head ; 2200int32_t * const pi = pk + ( size_t ) max_t_ * g . n_head_kv ; 2201for ( int t = 0 ; t < T ; ++ t ) { 2202h_tok_ [ t ] = tokens [ t ]; 2203qsa_step_fill ( h_step_ + t * kStepCount , pos0 + t , s ); 2204const int32_t pos_t = ( int32_t ) ( pos0 + t ); 2205for ( int64_t h = 0 ; h < g . n_head ; ++ h ) h_pos_ [ t * g . n_head + h ] = pos_t ; 2206for ( int64_t h = 0 ; h < g . n_head_kv ; ++ h ) pk [ t * g . n_head_kv + h ] = pos_t ; 2207for ( int64_t h = 0 ; h < g . idx_q_heads ; ++ h ) pi [ t * g . idx_q_heads + h ] = pos_t ; 2208} 2209* (volatile uint32_t * ) h_seq_ = 0 ; 2210for ( int _i = 1 ; _i <= 8 ; ++ _i ) ((volatile uint32_t * ) h_seq_ )[ _i ] = 0 ; /* + the payload tags/checksums */ 2211* (volatile uint32_t * ) h_flag_ = 0 ; 2212* (volatile uint32_t * ) h_flagA_ = 0 ; 2213* (volatile uint32_t * ) h_flagB_ = 0 ; 2214std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2215last_t_ = T ; 2216last_pos0_ = pos0 ; 2217for ( int t = 0 ; t < T ; ++ t ) last_tokens_ [ t ] = tokens [ t ]; 2218staged_ = true; 2219} 2220 2221void Verifier :: collect_profile () { 2222if (std:: getenv ( "STRATA_VERIFY_EAGER" ) == nullptr ) { // eager (SYCL port): prof_h_ already holds the host clocks 2223// SYCL port: the stamps are written by kernels on THIS verifier's stream, so the readback has to ride the 2224// same stream. The device's default queue is neither ordered after the window nor necessarily this 2225// stage's device (a layer split), so reading there could return the previous window's stamps or another 2226// card's memory - which is why the table was only ever printed in the eager mode before. 2227const strata::core:: OnDevice on_device ( device_ ); 2228cs_ -> memcpy ( prof_h_ . data (), prof_ , prof_h_ . size () * 8 ). wait (); 2229} 2230accumulate_profile ( prof_h_ . data ()); 2231if ( prof_S_ > 0 ) { // a batch window: its table (run() prints only its own windows) 2232static const long long every = [] { 2233const char * e = std:: getenv ( "STRATA_VERIFY_PROFILE_EVERY" ); 2234return e ? std:: atoll ( e ) : 0LL ; 2235}(); 2236if ( every > 0 && prof_windows_ >= every ) { 2237std:: fprintf ( stderr , "verify stages batch window of %d rows (ms/window over %lld, GPU clock):%s\n" , prof_S_ , 2238( long long ) prof_windows_ , profile_report (). c_str ()); 2239std:: fflush ( stderr ); 2240} 2241} 2242} 2243 2244void Verifier :: accumulate_profile (const unsigned long long * stamps ) { 2245const ModelGeometry & g = * g_ ; 2246const int64_t L = g . n_layers ; 2247auto at = [ & ]( int64_t l , int i ) { return stamps [( size_t ) ( l * kProfPer + i )]; }; 2248// D8: the derived columns below read stamps the hc-read kernels write themselves or the next 2249// layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns - 2250// which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now 2251// contributes nothing. 2252const auto gap = []( unsigned long long to , unsigned long long from ) { 2253return ( from != 0 && to != 0 && to >= from ) ? ( double ) ( to - from ) : 0.0 ; 2254}; 2255// only this stage's layers [lb_, le_) are ever stamped (a layer split); the head only on the last stage 2256for ( int64_t l = lb_ ; l < le_ ; ++ l ) { 2257const int kind = is_qsa_layer ( g , l ) ? 1 : 0 ; 2258unsigned long long prev = at ( l , 0 ); 2259for ( int i = 1 ; i <= 24 ; ++ i ) { 2260const unsigned long long x = at ( l , i ); 2261if ( x == 0 || x < prev ) continue; 2262prof_sum_ [ kind ][ i ] += ( double ) ( x - prev ); 2263prev = x ; 2264} 2265if ( l + 1 < le_ ) prof_sum_ [ kind ][ 25 ] += gap ( at ( l + 1 , 0 ), at ( l , 24 )); 2266const 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 )); 2267if ( dn > 0 && dd > 0 && du > 0 ) { // the split exists: show it split, not twice 2268prof_sum_ [ kind ][ 27 ] += dn ; // hc-read0: norm 2269prof_sum_ [ kind ][ 28 ] += dd ; // down 2270prof_sum_ [ kind ][ 29 ] += du ; // up (through both halves, as before) 2271prof_sum_ [ kind ][ 1 ] -= gap ( at ( l , 1 ), at ( l , 0 )); // (hc-read0 shown split) 2272} 2273} 2274if ( le_ == L ) prof_sum_ [ 0 ][ 26 ] += gap ( at ( L , 1 ), at ( L , 0 )); 2275++ prof_windows_ ; 2276} 2277 2278bool Verifier :: run ( int T , const int32_t * tokens , int64_t pos0 , PoolMultiFn pool , 2279void * user , int32_t * out , std:: string & err ) try { 2280using namespace strata:: kernels ; 2281strata::kprof:: phase ( "decode" ); 2282prof_S_ = 0 ; 2283const OnDevice on_device ( device_ ); 2284last_batch_ = false; 2285if ( T < 1 || T > max_t_ ) { err = "verify: window size out of range" ; return false; } 2286const ModelGeometry & g = * g_ ; 2287SessionState & ss = * ss_ ; 2288if ( released_ . load ()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine" ; return false; } 2289if ( pos0 + T > ss . qsa_states [ ss . qsa_primary ()]. max_cells ) { err = "verify: the window runs past the context" ; return false; } 2290refresh_ar (); 2291if (! capture ( T , err ) || ! capture_commit ( err )) return false; 2292VDBG ( "captured; staging\n" ); 2293const Clock :: time_point t0 = Clock :: now (); 2294if (! staged_ ) stage_inputs ( T , tokens , pos0 ); 2295staged_ = false; 2296const bool do_ple = ss . ple . ready () && ple_stage (); 2297uint32_t ple_rows [ kVerifyMaxT * PLE_N_HEADS ]; 2298if ( do_ple ) { 2299int32_t prev [ 2 ] = { ss . ple_prev [ 0 ], ss . ple_prev [ 1 ]}; 2300for ( int t = 0 ; t < T ; ++ t ) { 2301ngram_rows ( & tokens [ t ], prev , 1 , ss . ple . consts , ple_rows + t * PLE_N_HEADS ); 2302prev [ 0 ] = prev [ 1 ]; 2303prev [ 1 ] = tokens [ t ]; 2304ss . ple . table -> prefetch_rows ( ple_rows + t * PLE_N_HEADS ); 2305} 2306} 2307if ( trace_h_ != nullptr ) std:: memset ( trace_h_ , 0 , trace_n_ * 8 ); // #649: this window's breadcrumbs only 2308if (std:: FILE * sf = state_hash_file ()) { // debug only (STRATA_STATE_HASH_FILE) 2309cs_ -> wait (); 2310const uint64_t gf = ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size + 2311( uint64_t ) g . ssm_conv_channels * ( g . ssm_d_conv - 1 ); 2312std:: vector < char > hb (std:: max < uint64_t > ( gf * 4 , 1u << 20 )); 2313for ( int64_t i = 0 ; i < ss . gdn_alloc ; ++ i ) { 2314cs_ -> memcpy ( hb . data (), ss . gdn_state + ( size_t ) i * gf , gf * 4 ). wait (); 2315if (const char * dp = std:: getenv ( "STRATA_STATE_DUMP" ); dp != nullptr && windows == 0 && i < 4 ) { // raw state of the first GDN layers 2316const std:: string fn = std:: string ( dp ) + "_gdn" + std:: to_string ( ss . gdn_ord0 + i ) + ".bin" ; 2317if (std:: FILE * df = std:: fopen ( fn . c_str (), "wb" )) { std:: fwrite ( hb . data (), 1 , gf * 4 , df ); std:: fclose ( df ); } 2318} 2319std:: fprintf ( sf , "%lld gdn %lld %016llx\n" , ( long long ) windows , ( long long ) ( ss . gdn_ord0 + i ), 2320( unsigned long long ) layer_hash_fnv ( hb . data (), gf * 4 )); 2321} 2322const int64_t pages = ( pos0 + 3 ) / 4 ; 2323for ( int64_t i = 0 ; i < ss . qsa_alloc ; ++ i ) { 2324const QsaState & q = ss . qsa_states [ i ]; 2325if (! q . kv_int8 || q . k_q == nullptr ) continue; 2326const size_t kb = ( size_t ) pages * g . n_head_kv * 4 * g . head_dim ; 2327uint64_t h = 1469598103934665603ull ; 2328auto mix = [ & ](const void * dev , size_t bytes ) { 2329if ( bytes > hb . size ()) hb . resize ( bytes ); 2330cs_ -> memcpy ( hb . data (), dev , bytes ). wait (); 2331h ^= layer_hash_fnv ( hb . data (), bytes ); h *= 1099511628211ull ; 2332}; 2333mix ( q . k_q , kb ); mix ( q . v_q , kb ); mix ( q . k_scale , kb / 64 * 2 ); mix ( q . v_scale , kb / 64 * 2 ); 2334std:: fprintf ( sf , "%lld qsa %lld %016llx\n" , ( long long ) windows , ( long long ) ( ss . qsa_ord0 + i ), ( unsigned long long ) h ); 2335} 2336std:: fflush ( sf ); 2337} 2338std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2339if ( expert_usage_counts_d_ ) 2340cs_ -> memset ( expert_usage_counts_d_ , 0 , expert_usage_counts_h_ . size () * sizeof( uint32_t )); 2341trace_ev ( "WINDOW" , -1 , -1 , pos0 * 16 + T ); 2342ms_host += ms_since ( t0 ); 2343VDBG ( "staged; launching\n" ); 2344static Clock :: time_point t_prev_end ; // SYCL port timing: where does a round's wall clock go? 2345const Clock :: time_point t_launch = Clock :: now (); 2346if ( ar_on () && h_plan_err_ != nullptr ) * (volatile uint32_t * ) h_plan_err_ = 0 ; 2347{ // SYCL port: on an Arc A750 the first window after other GPU work (a prefill, the previous request) never 2348// started when it was launched behind that work still in flight on another queue (no GPU breadcrumb, 20 s 2349// timeout, the engine dies). Letting the other queues drain before every window removes it (9 of 9 three-request runs pass; before, almost all 2350// failed; the gap rule alone (=2) did not help, so it is the windows after each other, not only the first). The cost is 2351// the overlap of a window with the previous commit's tail. STRATA_WINDOW_SYNC=1 always drains, =0 never, =2 the gap rule; the default is 1 on an i915 card, 0 elsewhere. 2352// #2194: the same never-starting first window on an Arc A770 under xe (main thread in this function's stepped 2353// serve, queue::wait, no xe reset) - an Alchemist card, whatever its driver. Reproduced on the A750 with 2354// STRATA_WINDOW_SYNC=0 (stepped, --resident-experts, IQ3_XXS): 1 of 6 runs hung there (same stack), against 0 of 11 2355// with the drain. So the default drain is per GPU generation now: every Alchemist card (i915 or xe), as before 2356// every i915 card; Battlemage and the others are unchanged (0). 2357static const char * wv = std:: getenv ( "STRATA_WINDOW_SYNC" ); 2358static const int wmode = wv ? std:: atoi ( wv ) 2359: (( intel_i915_gpu () || strata:: intel_gpu_gen ( cs_ -> get_device ()) == strata:: IntelGpuGen :: Alchemist ) ? 1 : 0 ); 2360const bool first_or_gap = t_prev_end . time_since_epoch (). count () == 0 || ( t_launch - t_prev_end ) > std::chrono:: milliseconds ( 20 ); 2361if ( wmode == 1 || ( wmode == 2 && first_or_gap )) dpct:: get_current_device (). queues_wait_and_throw (); 2362} 2363// STRATA_VERIFY_STEPPED (Arc A-series): the doorbell window runs as segments with the CPU experts served at the 2364// queue boundaries between them (no mid-kernel host signalling); the all-resident graph gets its one flag (the PLE 2365// rows are in place) before launch. 2366const bool stepped_run = g_stepped && ! ar_on () && std:: getenv ( "STRATA_VERIFY_EAGER" ) == nullptr && ! seg_ [ T ]. empty (); 2367const bool stepped_ar = g_stepped && ar_on () && !( g_test_stall > 0 && windows + 1 == g_test_stall ); 2368if ( stepped_ar ) { 2369if ( do_ple ) { 2370const Clock :: time_point tp = Clock :: now (); 2371if (! ss . ple . table -> gather_batch ( ple_rows , ( size_t ) T , h_ple_ , err )) return false; 2372std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2373_mm_sfence (); 2374ms_host += ms_since ( tp ); 2375} 2376* (volatile uint32_t * ) h_flag_ = 1 ; 2377std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2378} 2379dpct:: err0 le = 0 ; 2380if ( stepped_run ) { 2381if ( remote_opt_ ) { err = "verify: STRATA_VERIFY_STEPPED does not serve --remote-expert-opt" ; return false; } 2382const int Gs = groups_ [ T ] > 0 ? groups_ [ T ] : 1 ; 2383double st_wait = 0 , st_pool = 0 ; 2384std:: vector < char > submitted ( seg_ [ T ]. size (), 0 ); 2385// one serve: segment i drained (the ring's payload is in mapped memory); run the pool - on a helper thread 2386// when `nxt` is a split segment, which is submitted as soon as the pool publishes its plan (flag A) - then 2387// raise flags B and M before the following segment is submitted 2388auto serve = [ & ]( int64_t l , int grp , size_t nxt ) -> bool { 2389const Clock :: time_point a = Clock :: now (); 2390cs_ -> wait (); 2391const Clock :: time_point b = Clock :: now (); 2392const uint32_t want = ( uint32_t ) (( l - lb_ ) * Gs + grp + 1 ); 2393if ( * (volatile uint32_t * ) h_seq_ < want ) { 2394err = "verify (stepped): layer " + std:: to_string ( l ) + " did not ring after its queue drained (seq " + 2395std:: to_string ( * (volatile uint32_t * ) h_seq_ ) + ", want " + std:: to_string ( want ) + ")" ; 2396return false; 2397} 2398cur_layer_ = want - 1 ; 2399set_plan_slot ( grp ); 2400const int tb = grp == 0 ? 0 : ( T + 1 ) / 2 , n = ( Gs == 2 ? ( grp == 0 ? ( T + 1 ) / 2 : T ) : T ) - tb ; 2401auto run_pool = [ & ]() { 2402if ( pool != nullptr ) 2403pool ( user , h_x_ + ( size_t ) tb * g . n_embd , h_ids_ + ( size_t ) tb * ss . k , n , ss . k , 2404h_ymiss_ + ( size_t ) tb * ss . k * g . n_embd , l ); 2405}; 2406auto empty_plan = [ & ]() { // the pool did not publish a plan: an empty one 2407sink_ . counts [ 0 ] = 0 ; sink_ . counts [ 1 ] = 0 ; sink_ . counts [ 2 ] = 0 ; 2408sink_ . start [ 0 ] = 0 ; sink_ . start2 [ 0 ] = 0 ; 2409std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2410* (volatile uint32_t * ) h_flagA_ = want ; 2411}; 2412// segment nxt ends at a split point: it is the plan copy + VRAM groups, whose only host wait is flag A 2413const bool split = nxt < seg_kind_ [ T ]. size () && seg_kind_ [ T ][ nxt ] == 0 ; 2414static const bool pipe = [] { const char * e = std:: getenv ( "STRATA_VERIFY_PIPE" ); return !( e && e [ 0 ] == '0' ); }(); 2415if ( pipe && split ) { 2416std:: atomic < bool > done {false}; 2417std:: string herr ; 2418try { 2419const int helper_cpu = pipe_helper_cpu (); 2420std:: thread th ([ & , helper_cpu ]() { 2421#if defined( __linux__ ) 2422if ( helper_cpu >= 0 ) { 2423cpu_set_t s ; 2424CPU_ZERO ( & s ); 2425CPU_SET ( helper_cpu , & s ); 2426( void ) pthread_setaffinity_np ( pthread_self (), sizeof s , & s ); 2427} 2428#endif 2429try { run_pool (); } catch (const std:: exception & e ) { herr = e . what (); } 2430done . store (true, std:: memory_order_release ); 2431}); 2432while (! done . load (std:: memory_order_acquire ) && * (volatile uint32_t * ) h_flagA_ != want ) 2433std::this_thread:: yield (); 2434if ( done . load (std:: memory_order_acquire ) && * (volatile uint32_t * ) h_flagA_ != want ) empty_plan (); 2435cs_ -> ext_oneapi_graph ( * seg_ [ T ][ nxt ]); // flag A is up: its waits pass 2436submitted [ nxt ] = 1 ; 2437th . join (); 2438} catch (const std:: exception & e ) { err = std:: string ( "verify: pipelined serve: " ) + e . what (); return false; } 2439if (! herr . empty ()) { err = "verify: pool: " + herr ; return false; } 2440} else { 2441run_pool (); 2442std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2443if ( * (volatile uint32_t * ) h_flagA_ != want ) empty_plan (); 2444} 2445copy_ -> wait (); // fetch_dma's copies and its flag-B host task 2446std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2447raise_flag ( h_flagB_ , want ); 2448if ( want == 1 && do_ple ) { // layer 1's pre copies h_ple_ after layer 0's wait on the M flag 2449const Clock :: time_point tp = Clock :: now (); 2450if (! ss . ple . table -> gather_batch ( ple_rows , ( size_t ) T , h_ple_ , err )) return false; 2451ms_host += ms_since ( tp ); 2452} 2453std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2454_mm_sfence (); 2455* (volatile uint32_t * ) h_flag_ = want ; 2456std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2457st_wait += std::chrono:: duration < double , std:: milli > ( b - a ). count (); 2458st_pool += ms_since ( b ); 2459return true; 2460}; 2461try { 2462for ( size_t i = 0 ; i < seg_ [ T ]. size () && le == 0 ; ++ i ) { 2463const bool has_entry = i < seg_at_ [ T ]. size (); 2464if (! submitted [ i ]) cs_ -> ext_oneapi_graph ( * seg_ [ T ][ i ]); // (a split segment: its serve submitted it) 2465if ( has_entry && seg_kind_ [ T ][ i ] == 1 && ! serve ( seg_at_ [ T ][ i ]. first , seg_at_ [ T ][ i ]. second , i + 1 )) { 2466if ( err . empty ()) err = "verify: stepped serve failed" ; 2467le = 1 ; 2468} 2469} 2470} catch (const std:: exception & e ) { err = std:: string ( "verify (stepped): " ) + e . what (); le = 1 ; } 2471ms_wait += st_wait ; 2472ms_pool += st_pool ; 2473if ( le != 0 ) return false; 2474} else { 2475le = (std:: getenv ( "STRATA_VERIFY_EAGER" ) != nullptr ) 2476? ( record_window ( T , cs_ , err ) ? 0 : 1 ) // SYCL port: eager replay of the window body 2477: DPCT_CHECK_ERROR (( cs_ ) -> ext_oneapi_graph ( * ( ar_off_ ? exec_nr_ [ T ] : exec_ [ T ]))); 2478} 2479/* 2480DPCT1009: SYCL reports errors using exceptions and does not use error 2481codes. Please replace the "get_error_string_dummy(...)" with a real 2482error-handling function. 2483*/ 2484/* 2485DPCT1001: The statement could not be removed. 2486*/ 2487/* 2488DPCT1000: Error handling if-stmt was detected but could not be rewritten. 2489*/ 2490trace_ev ( "LAUNCHED" , -1 , -1 , ( int64_t ) le ); 2491if ( le != 0 ) { 2492err = 2493std:: string ( "verify: launch: " ) + dpct:: get_error_string_dummy ( le ); 2494return false; 2495} 2496( void ) DPCT_CHECK_ERROR ((( cs_ ) -> ext_oneapi_empty ())); 2497VDBG ( "launched\n" ); 2498volatile uint32_t * const seq = h_seq_ ; 2499volatile uint32_t * const flag = h_flag_ ; 2500const int G = groups_ [ T ] > 0 ? groups_ [ T ] : 1 ; 2501const int gtb [ 2 ] = { 0 , ( T + 1 ) / 2 }, gte [ 2 ] = { G == 2 ? ( T + 1 ) / 2 : T , T }; 2502// SYCL port: with every routed expert resident the GPU takes its own plan (`device_plan_`) and skips every 2503// host flag, so the host has nothing to do per layer - and on this platform a kernel's writes to host-mapped 2504// memory are not reliably visible while the graph runs (measured: the ring is seen late or not at all), 2505// so waiting on them per layer fails. STRATA_VERIFY_NO_HOST=1 waits for the whole window instead. Only for 2506// an all-resident cache: a missed expert would leave the GPU waiting for a plan that never comes. 2507static const bool no_host = [] { const char * v = std:: getenv ( "STRATA_VERIFY_NO_HOST" ); return v && * v && std:: strcmp ( v , "0" ) != 0 ; }(); 2508const int64_t steps = ( le_ - lb_ ) * G ; 2509const bool test_stall = g_test_stall > 0 && windows + 1 == g_test_stall ; // #267 test hook (off: false) 2510if ( stepped_run || stepped_ar ) { 2511// the stepped window already served every layer (or the all-resident one had its flag before launch) 2512} else if ( ar_on () && ! test_stall ) { 2513if ( do_ple ) { 2514const Clock :: time_point tp = Clock :: now (); 2515if (! ss . ple . table -> gather_batch ( ple_rows , ( size_t ) T , h_ple_ , err )) return false; 2516std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2517_mm_sfence (); 2518* flag = 1 ; 2519ms_host += ms_since ( tp ); 2520} else { 2521* flag = 1 ; 2522} 2523} else 2524for ( int64_t k = 0 ; ! no_host && k < steps ; ++ k ) { 2525const int64_t l = lb_ + k / G ; 2526const int grp = ( int ) ( k % G ); 2527const uint32_t want = ( uint32_t ) ( k + 1 ); 2528const Clock :: time_point a = Clock :: now (); 2529auto last_flush = a ; 2530uint32_t spins = 0 ; 2531progress_at ( "verify window: waiting for the GPU to reach layer" , l ); 2532while ( * seq < want ) { 2533_mm_pause (); 2534if (( ++ spins & 1023u ) != 0 ) continue; 2535const auto now = Clock :: now (); 2536if ( now - last_flush > std::chrono:: microseconds ( 2000 )) { 2537last_flush = now ; 2538// SYCL port fix: cudaStreamQuery's answer (0 finished, 1 still running) was lost in the migration 2539// (DPCT_CHECK_ERROR of ext_oneapi_empty() is always 0), so ANY wait over 2 ms was reported as 2540// "graph finished". Layers whose GPU time exceeds 2 ms (host-mirrored experts read over PCIe) failed that way. 2541const dpct:: err0 q = cs_ -> ext_oneapi_empty () ? 0 : 1 ; 2542if ( q != 1 && * seq < want ) { 2543trace_ev ( "NEVER-RANG" , k , l , ( int64_t ) q ); 2544trace_dump ( stderr ); 2545err = "verify: layer " + std:: to_string ( l ) + 2546" never rang (" + 2547/* 2548DPCT1009: SYCL reports errors using exceptions and 2549does not use error codes. Please replace the 2550"get_error_string_dummy(...)" with a real 2551error-handling function. 2552*/ 2553( q == 0 2554? std:: string ( "graph finished" ) 2555: std:: string (dpct:: get_error_string_dummy ( q ))) + 2556")" ; 2557return false; 2558} 2559} 2560if ( now - a > strata_ring_timeout ()) { 2561// #267: the caller ends the engine; no spin kernel may outlive it 2562trace_ev ( "TIMEOUT" , k , l , ( int64_t ) ! cs_ -> ext_oneapi_empty ()); // SYCL port: 1 = still running 2563if ( g_trace ) { 2564diag ( stderr ); // the words and the breadcrumbs before the release ... 2565const bool drained = release_gpu_waits ( 5000 ); 2566trace_dump ( stderr ); // ... and after it: did the GPU move once its waits were raised? 2567err = "verify: timed out at layer " + std:: to_string ( l ) + released_note ( drained ); 2568return false; 2569} 2570err = "verify: timed out at layer " + std:: to_string ( l ) + released_note ( release_gpu_waits ( 5000 )); 2571return false; 2572} 2573} 2574const Clock :: time_point b = Clock :: now (); 2575if ( g_trace ) trace_ev ( "RANG" , k , l , ( int64_t ) std::chrono:: duration_cast < std::chrono:: microseconds > ( b - a ). count ()); 2576VDBG ( "layer %lld rang\n" , ( long long ) l ); 2577cur_layer_ = want - 1 ; 2578set_plan_slot ( grp ); 2579const int tb = gtb [ grp ], n = gte [ grp ] - gtb [ grp ]; 2580// the ring can arrive before its payload (elementwise.hpp): the pool must read a whole one 2581if (!strata::kernels:: doorbell_wait_payload ( h_seq_ , h_x_ + ( size_t ) tb * g . n_embd , ( int64_t ) n * g . n_embd , 2582h_ids_ + ( size_t ) tb * ss . k , h_w_ + ( size_t ) tb * ss . k , 2583( int64_t ) n * ss . k , want )) { 2584err = "verify: layer " + std:: to_string ( l ) + " rang but its payload never arrived whole" ; 2585return false; 2586} 2587progress_at ( "verify window: the CPU experts of layer" , l ); 2588if ( remote_opt_ ) remote_opt_ -> begin ( h_w_ + ( size_t ) tb * ss . k , tb , n ); 2589if ( pool != nullptr ) 2590pool ( user , h_x_ + ( size_t ) tb * g . n_embd , h_ids_ + ( size_t ) tb * ss . k , n , ss . k , 2591h_ymiss_ + ( size_t ) tb * ss . k * g . n_embd , l ); 2592if ( remote_opt_ ) remote_opt_ -> end (); 2593if (std:: FILE * lf = layer_hash_file ()) { // debug only (STRATA_LAYER_HASH_FILE) 2594std:: fprintf ( lf , "%lld %lld %d %016llx %016llx %016llx %016llx\n" , ( long long ) windows , ( long long ) l , n , 2595( unsigned long long ) layer_hash_fnv ( h_x_ + ( size_t ) tb * g . n_embd , ( size_t ) n * g . n_embd * 4 ), 2596( unsigned long long ) layer_hash_fnv ( h_ids_ + ( size_t ) tb * ss . k , ( size_t ) n * ss . k * 4 ), 2597( unsigned long long ) layer_hash_fnv ( h_w_ + ( size_t ) tb * ss . k , ( size_t ) n * ss . k * 4 ), 2598( unsigned long long ) layer_hash_fnv ( h_ymiss_ + ( size_t ) tb * ss . k * g . n_embd , ( size_t ) n * ss . k * g . n_embd * 4 )); 2599std:: fflush ( lf ); 2600} 2601VDBG ( "layer %lld served\n" , ( long long ) l ); 2602if ( g_trace ) trace_ev ( * (volatile uint32_t * ) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET" , k , l , 2603( int64_t ) ms_since ( b )); // aux: ms the CPU experts took 2604progress_tick (); 2605std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2606_mm_sfence (); 2607if ( * (volatile uint32_t * ) h_flagA_ != want ) { // the pool did not publish a plan: an empty one 2608sink_ . counts [ 0 ] = 0 ; 2609sink_ . counts [ 1 ] = 0 ; 2610sink_ . counts [ 2 ] = 0 ; 2611sink_ . start [ 0 ] = 0 ; 2612sink_ . start2 [ 0 ] = 0 ; 2613std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2614* (volatile uint32_t * ) h_flagA_ = want ; 2615raise_flag ( h_flagB_ , want ); 2616} 2617// Layer 1's pre(1, 0) copies h_ple_ -> ple_ after Layer 0's wait_flag_ge(m_flag_, 1). 2618// By collecting PLE here at k == 0 (after publishing flagA/flagB for Layer 0 so the GPU can run 2619// Layer 0's VRAM experts, and before raising *flag = 1), the NVMe PLE reads overlap with both 2620// MtpDrafter::draft and Layer 0's attention + router + expert execution! 2621if ( k == 0 && do_ple ) { 2622const Clock :: time_point tp = Clock :: now (); 2623if (! ss . ple . table -> gather_batch ( ple_rows , ( size_t ) T , h_ple_ , err )) return false; 2624std:: atomic_thread_fence (std:: memory_order_seq_cst ); 2625_mm_sfence (); 2626ms_host += ms_since ( tp ); 2627} 2628if (!( test_stall && k + 1 == steps )) * flag = want ; 2629ms_wait += std::chrono:: duration < double , std:: milli > ( b - a ). count (); 2630ms_pool += ms_since ( b ); 2631} 2632// (#646 staged the next stage's inputs here; 0.1.39b keeps the layer split's order: each stage stages its own) 2633progress_at ( "verify window: waiting for the GPU to finish the window (flags A/B/M raised)" , ( int64_t ) T ); 2634// #267: a window the GPU never finishes (a spin kernel that never sees its flag) holds the host here; the stall 2635// watchdog then releases every verifier's GPU waits (release_live_verifiers) before it ends the engine, so no 2636// spin kernel outlives the process. The wait itself stays a blocking sync (a polling wait cost decode upstream). 2637trace_ev ( "SYNC" , -1 , -1 , 0 ); 2638const dpct:: err0 se = queue_wait_diag ( cs_ , device_ , "window sync" ); 2639trace_ev ( "SYNCED" , -1 , -1 , ( int64_t ) se ); 2640const Clock :: time_point t_done = Clock :: now (); 2641if (std:: getenv ( "STRATA_VERIFY_DEBUG" ) != nullptr ) { 2642std:: fprintf ( stderr , "verify dbg: T=%d window: since previous window %.1f ms, staging %.1f ms, gpu %.1f ms\n" , T , 2643t_prev_end . time_since_epoch (). count () ? std::chrono:: duration < double , std:: milli > ( t0 - t_prev_end ). count () : 0.0 , 2644std::chrono:: duration < double , std:: milli > ( t_launch - t0 ). count (), 2645std::chrono:: duration < double , std:: milli > ( t_done - t_launch ). count ()); 2646} 2647t_prev_end = t_done ; 2648/* 2649DPCT1009: SYCL reports errors using exceptions and does not use error 2650codes. Please replace the "get_error_string_dummy(...)" with a real 2651error-handling function. 2652*/ 2653/* 2654DPCT1001: The statement could not be removed. 2655*/ 2656/* 2657DPCT1000: Error handling if-stmt was detected but could not be rewritten. 2658*/ 2659if ( se != 0 ) { 2660err = std:: string ( "verify: " ) + dpct:: get_error_string_dummy ( se ); 2661return false; 2662} 2663if ( expert_usage_counts_d_ ) { 2664if (! expert_usage_counter_ || expert_usage_counter_ -> size () != expert_usage_counts_h_ . size ()) 2665throw std:: runtime_error ( "mirror adaptive expert usage is unbound" ); 2666cs_ -> memcpy ( expert_usage_counts_h_ . data (), expert_usage_counts_d_ , 2667expert_usage_counts_h_ . size () * sizeof( uint32_t )). wait_and_throw (); 2668uint64_t total = 0 ; 2669for ( uint32_t count : expert_usage_counts_h_ ) total += count ; 2670if ( total != ( uint64_t )( le_ - lb_ ) * ( uint64_t ) T * ( uint64_t ) ss . k ) 2671throw std:: runtime_error ( "mirror adaptive route histogram coverage mismatch" ); 2672// Match the CPU usage counter's scalar increment order. 2673static const bool presence = [] { const char * e = std:: getenv ( "STRATA_SYCL_ADAPT_WINDOW_PRESENCE" ); return e && e [ 0 ] == '1' ; }(); 2674for ( size_t i = 0 ; i < expert_usage_counts_h_ . size (); ++ i ) { 2675const uint32_t count = presence ? ( expert_usage_counts_h_ [ i ] > 0 ? 1u : 0u ) : expert_usage_counts_h_ [ i ]; 2676for ( uint32_t n = 0 ; n < count ; ++ n ) ( * expert_usage_counter_ )[ i ] += 1.f ; 2677} 2678} 2679#ifdef STRATA_SYCL_WORKLOAD_TRACE 2680if ( auto found = routing_audits . find ( this ); found != routing_audits . end ()) { 2681auto & audit = * found -> second ; 2682const int64_t capx = ( int64_t ) max_t_ * ss . k ; 2683const int64_t ptr_off = (( 4 + capx + 1 + 2 * capx ) + 1 ) & ~ 1ll ; 2684const auto & layout = strata::kernels::cpu:: expert_layout (); 2685if (! layout . native ) throw std:: runtime_error ( "routing audit requires native expert layout" ); 2686for ( int64_t layer = lb_ ; layer < le_ ; ++ layer ) for ( int group = 0 ; group < G ; ++ group ) { 2687const int32_t * data = audit . slot ( layer , group ); 2688const int32_t * starts = data + 4 ; 2689const int32_t * dst = starts + capx + 1 ; 2690const int32_t * tok = dst + capx ; 2691const auto * pointers = reinterpret_cast < const unsigned long long *> ( data + ptr_off ); 2692const int n = gte [ group ] - gtb [ group ], expected = n * ( int ) ss . k ; 2693if ( data [ 0 ] < 0 || data [ 0 ] > expected || data [ 1 ] != expected || data [ 2 ] != 0 || starts [ 0 ] != 0 || starts [ data [ 0 ]] != expected ) 2694throw std:: runtime_error ( "routing audit: incomplete resident plan" ); 2695const auto & format = layout . fmt [( size_t ) layer ]; 2696std:: vector < bool > seen (( size_t ) expected , false); 2697std:: fprintf ( audit . output , "{\"kind\":\"expert_plan\",\"raw_ns\":%lld,\"position\":%lld,\"T\":%d,\"layer\":%lld,\"group\":%d,\"rows\":%d,\"GU_type\":%d,\"down_type\":%d,\"n_embd\":%lld,\"n_ff\":%lld,\"gu_row_bytes\":%llu,\"down_row_bytes\":%llu,\"groups\":%d,\"entries\":%d,\"pcie_plan_groups\":%d,\"plans\":[" , 2698( long long )strata::workload_trace:: trace_ns (), ( long long ) pos0 , T , ( long long ) layer , group , n , 2699format . gu_type , format . d_type , ( long long ) format . n_embd , ( long long ) format . n_ff , 2700( unsigned long long ) format . gu_row , ( unsigned long long ) format . d_row , data [ 0 ], data [ 1 ], data [ 2 ]); 2701for ( int index = 0 ; index < data [ 0 ]; ++ index ) { 2702const int begin = starts [ index ], end = starts [ index + 1 ]; 2703if ( begin < 0 || end <= begin || end > expected || end - begin > n ) 2704throw std:: runtime_error ( "routing audit: invalid group range" ); 2705const auto allocation = sycl:: get_pointer_type ( reinterpret_cast < const void *> ( pointers [ index ]), cs_ -> get_context ()); 2706const char * residency = allocation == sycl::usm::alloc:: device ? "device" : allocation == sycl::usm::alloc:: host ? "host" : allocation == sycl::usm::alloc:: shared ? "shared" : "unknown" ; 2707std:: fprintf ( audit . output , "%s{\"count\":%d,\"allocation\":\"%s\",\"pointer\":%llu,\"dst\":[" , index ? "," : "" , end - begin , residency , pointers [ index ]); 2708for ( int e = begin ; e < end ; ++ e ) { 2709if ( dst [ e ] < 0 || dst [ e ] >= expected || seen [( size_t ) dst [ e ]] || tok [ e ] < 0 || tok [ e ] >= T ) 2710throw std:: runtime_error ( "routing audit: invalid entry mapping" ); 2711seen [( size_t ) dst [ e ]] = true; 2712std:: fprintf ( audit . output , "%s%d" , e == begin ? "" : "," , dst [ e ]); 2713} 2714std:: fprintf ( audit . output , "],\"tok\":[" ); 2715for ( int e = begin ; e < end ; ++ e ) std:: fprintf ( audit . output , "%s%d" , e == begin ? "" : "," , tok [ e ]); 2716std:: fprintf ( audit . output , "]}" ); 2717} 2718if (std:: find ( seen . begin (), seen . end (), false) != seen . end ()) throw std:: runtime_error ( "routing audit: missing entry" ); 2719std:: fprintf ( audit . output , "]}\n" ); 2720} 2721std:: fflush ( audit . output ); 2722} 2723#endif 2724if ( no_host && std:: getenv ( "STRATA_VERIFY_DEBUG" ) != nullptr ) { // SYCL port: what the window left behind 2725const int Gd = groups_ [ T ] > 0 ? groups_ [ T ] : 1 ; 2726std:: vector < uint32_t > sk (( size_t ) Gd , 0 ); 2727std:: vector < int32_t > id0 (( size_t ) ss . k , 0 ); 2728std:: vector < int32_t > res0 (( size_t ) 16 , 0 ); 2729cs_ -> memcpy ( sk . data (), skip_ , sk . size () * 4 ). wait (); 2730cs_ -> memcpy ( id0 . data (), ids_ , id0 . size () * 4 ). wait (); 2731cs_ -> memcpy ( res0 . data (), hits_ . d_res , res0 . size () * 4 ). wait (); 2732std:: fprintf ( stderr , "verify dbg: window T=%d: host seq=%u (expected %lld), skip[]=" , T , * (volatile uint32_t * ) h_seq_ , 2733( long long ) (( le_ - lb_ ) * Gd )); 2734for ( int i = 0 ; i < Gd ; ++ i ) std:: fprintf ( stderr , " %u" , sk [( size_t ) i ]); 2735std:: vector < float > w0 (( size_t ) ss . k , 0.f ); 2736cs_ -> memcpy ( w0 . data (), w_ , w0 . size () * 4 ). wait (); 2737std:: fprintf ( stderr , "; layer-0 weights:" ); 2738for ( size_t i = 0 ; i < w0 . size (); ++ i ) std:: fprintf ( stderr , " %.3g" , w0 [ i ]); 2739std:: fprintf ( stderr , "; layer-0 ids:" ); 2740for ( size_t i = 0 ; i < id0 . size (); ++ i ) std:: fprintf ( stderr , " %d" , id0 [ i ]); 2741std:: fprintf ( stderr , "; d_res[0..15]:" ); 2742for ( size_t i = 0 ; i < res0 . size (); ++ i ) std:: fprintf ( stderr , " %d" , res0 [ i ]); 2743std:: fprintf ( stderr , "; out[0..3]: %d %d %d %d\n" , ((volatile int32_t * ) h_out_ )[ 0 ], ((volatile int32_t * ) h_out_ )[ 1 ], 2744((volatile int32_t * ) h_out_ )[ 2 ], ((volatile int32_t * ) h_out_ )[ 3 ]); 2745auto stat = [ & ](const char * what , const float * dev , size_t n ) { // token 0's vector: where do the zeros begin? 2746std:: vector < float > v ( n , 0.f ); 2747cs_ -> memcpy ( v . data (), dev , n * 4 ). wait (); 2748double sum = 0 , mx = 0 ; size_t nonfinite = 0 ; 2749for ( float x : v ) { if (!std:: isfinite ( x )) { ++ nonfinite ; continue; } sum += std:: fabs ( x ); mx = std:: max ( mx , ( double ) std:: fabs ( x )); } 2750std:: fprintf ( stderr , "verify dbg: %-8s n=%zu mean|.|=%.4g max|.|=%.4g nonfinite=%zu first4=%g %g %g %g\n" , what , n , 2751sum / ( double ) n , mx , nonfinite , v [ 0 ], v [ 1 ], v [ 2 ], v [ 3 ]); 2752}; 2753if ( dbgR_ ) { 2754const size_t N = ( size_t ) g . n_embd ; 2755std:: vector < float > r (( size_t ) g . n_layers * N ), m (( size_t ) g . n_layers * N ); 2756cs_ -> memcpy ( r . data (), dbgR_ , r . size () * 4 ). wait (); 2757cs_ -> memcpy ( m . data (), dbgM_ , m . size () * 4 ). wait (); 2758for ( int64_t l = 0 ; l < g . n_layers ; ++ l ) { 2759double sr = 0 , sm = 0 ; size_t nr = 0 , nm = 0 ; 2760for ( size_t i = 0 ; i < N ; ++ i ) { 2761const float x = r [( size_t ) l * N + i ], y = m [( size_t ) l * N + i ]; 2762if (std:: isfinite ( x )) sr += std:: fabs ( x ); else ++ nr ; 2763if (std:: isfinite ( y )) sm += std:: fabs ( y ); else ++ nm ; 2764} 2765std:: fprintf ( stderr , "verify dbg: layer %2lld %s R mean|.|=%.4g nonfinite=%zu mixed mean|.|=%.4g nonfinite=%zu\n" , 2766( long long ) l , is_qsa_layer ( g , l ) ? "QSA" : "GDN" , sr / N , nr , sm / N , nm ); 2767} 2768} 2769{ // the device plan of the last layer group and the MoE parts it produced (token 0) 2770std:: vector < int32_t > pc ( 4 , 0 ); 2771cs_ -> memcpy ( pc . data (), plan_ , 16 ). wait (); 2772std:: fprintf ( stderr , "verify dbg: plan (last layer, grp 0): groups=%d entries=%d pcie=%d\n" , pc [ 0 ], pc [ 1 ], pc [ 2 ]); 2773} 2774stat ( "parts_" , parts_ , ( size_t ) ss . k * g . n_embd ); 2775stat ( "hit_out_" , hit_out_ , ( size_t ) ss . k * g . n_embd ); 2776stat ( "shared_" , shared_ , ( size_t ) g . n_embd ); 2777stat ( "emb_" , emb_ , ( size_t ) g . n_embd ); 2778stat ( "ple_" , ple_ , ( size_t ) g . n_embd ); 2779stat ( "R_" , R_ , ( size_t ) g . n_embd ); 2780stat ( "mixed_" , mixed_ , ( size_t ) g . n_embd ); 2781} 2782if ( ar_on () && h_plan_err_ != nullptr && * (volatile uint32_t * ) h_plan_err_ != 0 ) { // #871: refresh_ar saw the table whole 2783* (volatile uint32_t * ) h_plan_err_ = 0 ; 2784err = "verify: the all-resident plan met an expert that is not in VRAM (the residency table changed during the window)" ; 2785return false; 2786} 2787commit_pending_ = false; 2788progress_at ( "verify window: waiting for the expert copies" , ( int64_t ) T ); 2789if ( copy_used_ ) { 2790copy_ -> wait (); // no host function of this window may raise flag B in 2791// the next one 2792copy_used_ = false; 2793} 2794strata::kprof:: window_end ( "decode" ); // STRATA_KPROF=1 (with STRATA_VERIFY_EAGER=1): this window's per-kernel times 2795if ( prof_on_ && G == 1 ) { // the window's GPU stage stamps 2796collect_profile (); 2797if (std:: getenv ( "STRATA_VERIFY_EAGER" ) != nullptr ) // SYCL port: the stage table per window, host-clocked 2798std:: fprintf ( stderr , "verify stages T=%d (ms/window):%s\n" , T , profile_report (). c_str ()); 2799else { 2800// SYCL port: the same table from the GPU's own clock, averaged over N windows, so a decode can be 2801// attributed without the eager mode's drain per stamp (which measures host gaps, not kernel time). 2802// STRATA_VERIFY_PROFILE=1 STRATA_VERIFY_PROFILE_EVERY=32. 2803static const long long every = [] { 2804const char * e = std:: getenv ( "STRATA_VERIFY_PROFILE_EVERY" ); 2805return e ? std:: atoll ( e ) : 0LL ; 2806}(); 2807if ( every > 0 && prof_windows_ >= every ) { 2808std:: fprintf ( stderr , "verify stages T=%d (ms/window over %lld, GPU clock):%s\n" , T , 2809( long long ) prof_windows_ , profile_report (). c_str ()); 2810std:: fflush ( stderr ); 2811} 2812} 2813} 2814// ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's 2815// own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to 2816// the POSITION it samples, not to how the text was cut into windows, so a seed replays the same text whatever 2817// the drafts were. Exact: a rejected row's draw is discarded, and no kept decision depends on a reused draw. 2818if ( le_ < g . n_layers ) { // a layer split's earlier stage: the hand-off is written (synced above) 2819++ windows ; 2820return next_ == nullptr || next_ -> run ( T , tokens , pos0 , pool , next_user_ , out , err ); 2821} 2822const bool sampled = ! sampling_ . greedy && sampling_ . temperature > 0.0f ; 2823if ( head_sampling_ && ( sampled || hist_d_ != nullptr )) { 2824SamplerParams sp = sampling_ ; 2825sp . counter = ( uint64_t ) pos0 ; 2826sample_tokens ( head_logits_ , T , ( int ) n_vocab_ , hist_d_ , hist_len_ , sp , m_out_ , cs_ ); 2827if ( DPCT_CHECK_ERROR ( cs_ -> wait ()) != 28280 ) { // m_out_ is the mapped h_out_: synced, it is readable 2829err = "verify: the head sampling failed" ; 2830return false; 2831} 2832} 2833for ( int t = 0 ; t < T ; ++ t ) out [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 2834// STRATA_LOGITS_DUMP=<path> (debug tap, off by default; src/core/verify.cpp's, for the gate-2 judge of the Qwen4 shapes): the window's 2835// logits as the sampler saw them, written AFTER the window (synchronised above). One record is 2836// {int32 magic, int32 T, int32 n_vocab, int32 record, int64 position}, then T * n_vocab FP32 rows; row 0 is the window's first position. 2837if (const char * logits_path = std:: getenv ( "STRATA_LOGITS_DUMP" )) { 2838static std:: FILE * lf = std:: fopen ( logits_path , "wb" ); 2839static int32_t lrec = 0 ; 2840if ( lf != nullptr ) { 2841std:: vector < float > h (( size_t ) T * ( size_t ) n_vocab_ ); 2842dpct:: get_in_order_queue (). memcpy ( h . data (), head_logits_ , h . size () * sizeof( float )). wait (); 2843const int32_t hdr [ 4 ] = { 0x53474F4C /*"LOGS"*/ , T , ( int32_t ) n_vocab_ , lrec ++ }; 2844const int64_t hpos = pos0 ; 2845std:: fwrite ( hdr , sizeof hdr , 1 , lf ); 2846std:: fwrite ( & hpos , sizeof hpos , 1 , lf ); 2847std:: fwrite ( h . data (), sizeof( float ), h . size (), lf ); 2848std:: fflush ( lf ); 2849} 2850} 2851if (static const bool dbg = std:: getenv ( "STRATA_DBG_NAN" ) != nullptr ; dbg ) { // debug: the first non-finite head 2852static bool reported = false; 2853if (! reported ) { 2854std:: vector < float > h (( size_t ) T * ( size_t ) n_vocab_ ); 2855dpct:: get_in_order_queue () 2856. memcpy ( h . data (), head_logits_ , h . size () * 4 ) 2857. wait (); 2858for ( int t = 0 ; t < T && ! reported ; ++ t ) { 2859int64_t bad = 0 ; 2860for ( int64_t v = 0 ; v < n_vocab_ ; ++ v ) bad += !std:: isfinite ( h [( size_t ) t * n_vocab_ + v ]); 2861if ( bad ) { 2862reported = true; 2863std:: fprintf ( stderr , "strata dbg: verify window at position %lld, row %d: %lld of %lld logits non-finite " 2864"(token out %d)\n" , ( long long ) pos0 , t , ( long long ) bad , ( long long ) n_vocab_ , out [ t ]); 2865} 2866} 2867} 2868} 2869VDBG ( "window done\n" ); 2870++ windows ; 2871progress_at ( "decode" ); 2872progress_beat (); 2873return true; 2874} 2875catch (sycl:: exception const & exc ) { 2876std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 2877<< ", line:" << __LINE__ << std:: endl ; 2878std:: exit ( 1 ); 2879} 2880 2881void Verifier :: set_plan_slot ( int grp ) { 2882const int64_t cap = sink_ . cap ; 2883int32_t * base = h_plan_ + ( size_t ) grp * ( size_t ) plan_i32_ ; 2884const int64_t i32 = 4 + ( cap + 1 ) + cap + cap ; 2885const int64_t ptr_off = ( i32 + 1 ) & ~ 1ll ; 2886sink_ . counts = base ; 2887sink_ . start = base + 4 ; 2888sink_ . dst = sink_ . start + cap + 1 ; 2889sink_ . tok = sink_ . dst + cap ; 2890sink_ . ptr = ( unsigned long long * ) ( base + ptr_off ); 2891sink_ . ptr2 = sink_ . ptr + cap ; 2892sink_ . start2 = base + ptr_off + 4 * cap ; 2893const int G = last_batch_ ? 1 : ( groups_ [ last_t_ ] > 0 ? groups_ [ last_t_ ] : 1 ); 2894const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs ; 2895sink_ . staging = ( unsigned long long ) ( staging_ + ( size_t ) ( grp * per ) * strata::kernels::cpu:: expert_layout (). max_blob ); 2896sink_ . staging_cap = per ; 2897} 2898 2899// Flag B only rises: a host function of an earlier layer may run after a later layer already raised it directly. 2900void Verifier :: raise_flag ( uint32_t * flag , uint32_t value ) { 2901volatile long * f = (volatile long * ) flag ; 2902#if defined( _WIN32 ) 2903long cur = * f ; 2904while (( uint32_t ) cur < value ) { 2905const long prev = _InterlockedCompareExchange ( f , ( long ) value , cur ); 2906if ( prev == cur ) break; 2907cur = prev ; 2908} 2909#else 2910uint32_t cur = __atomic_load_n (( uint32_t * ) flag , __ATOMIC_SEQ_CST ); 2911while ( cur < value && ! __atomic_compare_exchange_n (( uint32_t * ) flag , & cur , value , false, __ATOMIC_SEQ_CST , __ATOMIC_SEQ_CST )) {} 2912#endif 2913} 2914 2915// Plan v0.3 P6: the PCIe share by DMA. The copy engine moves the blobs while the CPU computes its own share and the 2916// GPU its VRAM experts; a host function raises flag B when they have landed (the graph waits for it before the PCIe 2917// groups). Staging is split between the two token groups of a split window. 2918void Verifier :: fetch_dma ( void * ctx , const uint8_t * const * src , int n , 2919size_t bytes ) try { 2920Verifier * v = ( Verifier * ) ctx ; 2921const uint32_t want = v -> cur_layer_ + 1 ; 2922if ( n <= 0 ) { raise_flag ( v -> h_flagB_ , want ); return; } 2923v -> copy_used_ = true; 2924uint8_t * stage = ( uint8_t * ) v -> sink_ . staging ; // this group's half in a split window 2925// STRATA_DMA_BATCH (midhatn's #807, F12): the group's independent uploads as one cudaMemcpyBatchAsync. Mode 0 is 2926// the loop the engine always ran, errors unchecked (it never stops the engine). A batch mode whose uploads 2927// cannot be submitted stops the engine: flag B must not release the consumers to expert weights that were never 2928// copied. 2929const int batch_mode = strata::core:: dma_batch_mode (); 2930if ( batch_mode == 0 ) { 2931/* 2932DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 2933While the origin API might be synchronous, it depends on the type of 2934operand memory, so you may need to call wait() on event return by memcpy 2935API to ensure synchronization behavior. 2936*/ 2937for ( int i = 0 ; i < n ; ++ i ) 2938v -> copy_ -> memcpy ( stage + ( size_t ) i * bytes , src [ i ], bytes ); 2939} else { 2940const auto copied = strata::core:: copy_expert_blobs ( stage , src , n , bytes , v -> copy_ , batch_mode ); 2941/* 2942DPCT1000: Error handling if-stmt was detected but could not be 2943rewritten. 2944*/ 2945if ( copied != 0 ) { 2946/* 2947DPCT1009: SYCL reports errors using exceptions and does not use 2948error codes. Please replace the "get_error_string_dummy(...)" with a 2949real error-handling function. 2950*/ 2951std:: fprintf ( stderr , "strata DMA: expert upload failed: %s\n" , 2952dpct:: get_error_string_dummy ( copied )); 2953/* 2954DPCT1001: The statement could not be removed. 2955*/ 2956std:: fflush ( stderr ); 2957v -> release_gpu_waits ( 5000 ); 2958std:: abort (); 2959} 2960} 2961FlagSet & fs = v -> flag_sets_ [ v -> cur_layer_ % (sizeof v -> flag_sets_ / sizeof v -> flag_sets_ [ 0 ])]; 2962fs . flag = v -> h_flagB_ ; 2963fs . value = want ; 2964FlagSet * fsp = & fs ; 2965v -> copy_ -> submit ([ & ](sycl:: handler & cgh ) { 2966cgh . host_task ([ = ]() { raise_flag ( fsp -> flag , fsp -> value ); }); 2967}); 2968} 2969catch (sycl:: exception const & exc ) { 2970std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 2971<< ", line:" << __LINE__ << std:: endl ; 2972std:: exit ( 1 ); 2973} 2974 2975void Verifier :: publish_plan ( void * ctx ) { 2976Verifier * v = ( Verifier * ) ctx ; 2977_mm_sfence (); 2978* (volatile uint32_t * ) v -> h_flagA_ = v -> cur_layer_ + 1 ; 2979} 2980 2981bool Verifier :: window_logprobs (const int32_t * targets , int T , int64_t pos0 , int32_t extra_id , std:: FILE * out , 2982std:: string & err ) try { 2983if ( next_ != nullptr ) return next_ -> window_logprobs ( targets , T , pos0 , extra_id , out , err ); 2984const OnDevice on_device ( device_ ); 2985if ( head_logits_ == nullptr || n_vocab_ <= 0 || T <= 0 || targets == nullptr || out == nullptr ) { 2986err = "window_logprobs: no head logits for this window" ; 2987return false; 2988} 2989// run() synchronized cs_ before returning, so the head of this window is complete 2990std:: vector < float > h (( size_t ) T * ( size_t ) n_vocab_ ); 2991cs_ -> memcpy ( h . data (), head_logits_ , h . size () * sizeof( float )). wait (); 2992for ( int t = 0 ; t < T ; ++ t ) { 2993const float * row = h . data () + ( size_t ) t * ( size_t ) n_vocab_ ; 2994const int32_t tgt = targets [ t ]; 2995if ( tgt < 0 || ( int64_t ) tgt >= n_vocab_ ) continue; 2996int64_t top = 0 ; 2997for ( int64_t v = 1 ; v < n_vocab_ ; ++ v ) 2998if ( row [ v ] > row [ top ]) top = v ; 2999const double maxv = row [ top ]; 3000const bool has_extra = extra_id >= 0 && ( int64_t ) extra_id < n_vocab_ ; 3001double sum = 0.0 , sum_without = 0.0 ; // the second skips extra_id: no cancellation when it holds ~all mass 3002for ( int64_t v = 0 ; v < n_vocab_ ; ++ v ) { 3003const double e = std:: exp (( double ) row [ v ] - maxv ); 3004sum += e ; 3005if ( v != ( int64_t ) extra_id ) sum_without += e ; 3006} 3007const double lse = maxv + std:: log ( sum ); 3008const double extra = has_extra ? ( double ) row [ extra_id ] - lse : NAN ; 3009const double without = has_extra && tgt != extra_id && sum_without > 0.0 3010? ( double ) row [ tgt ] - ( maxv + std:: log ( sum_without )) : NAN ; 3011std:: fprintf ( out , "%lld\t%d\t%.9f\t%lld\t%.9f\t%d\t%.9f\t%.9f" , ( long long ) ( pos0 + t ), ( int ) tgt , 3012( double ) row [ tgt ] - lse , ( long long ) top , maxv - lse , ( int ) ( top == ( int64_t ) tgt ), extra , 3013without ); 3014// STRATA_LOGPOS_TOPK=K: the K most likely tokens and their log-probabilities too (`id:logprob`), for a 3015// top-k comparison with another engine on the same tokens (docs/UNSLOTH_Q4.md) 3016static const int topk = [] { 3017const char * v = std:: getenv ( "STRATA_LOGPOS_TOPK" ); 3018return v != nullptr ? std:: max ( 0 , std:: min ( 256 , std:: atoi ( v ))) : 0 ; 3019}(); 3020if ( topk > 0 ) { 3021std:: vector < int32_t > order (( size_t ) n_vocab_ ); 3022for ( int64_t v = 0 ; v < n_vocab_ ; ++ v ) order [( size_t ) v ] = ( int32_t ) v ; 3023std:: partial_sort ( order . begin (), order . begin () + topk , order . end (), 3024[ & ]( int32_t a , int32_t b ) { return row [ a ] > row [ b ]; }); 3025for ( int j = 0 ; j < topk ; ++ j ) 3026std:: fprintf ( out , "\t%d:%.6f" , order [( size_t ) j ], ( double ) row [ order [( size_t ) j ]] - lse ); 3027} 3028std:: fprintf ( out , "\n" ); 3029} 3030std:: fflush ( out ); 3031return true; 3032} catch (sycl:: exception const & e ) { 3033err = std:: string ( "window_logprobs: " ) + e . what (); 3034return false; 3035} 3036 3037namespace { bool g_commit_async = false; } 3038void Verifier :: set_commit_async ( bool on ) { g_commit_async = on && std:: getenv ( "STRATA_COMMIT_SYNC" ) == nullptr ; } 3039 3040bool Verifier :: commit ( int n_keep , std:: string & err ) try { 3041const OnDevice on_device ( device_ ); 3042if ( n_keep < 1 || n_keep > last_t_ ) { err = "verify: commit count out of range" ; return false; } 3043const Clock :: time_point t0 = Clock :: now (); 3044h_commit_ [ 0 ] = n_keep ; 3045h_commit_ [ 1 ] = n_keep - 1 ; 3046for ( int t = 0 ; t < max_t_ ; ++ t ) h_commit_ [ 2 + t ] = t < n_keep ? ( int32_t ) ( last_pos0_ + t ) : -1 ; 3047if ( last_t_ == 1 && one_token_self_commit () && ! self_commit_off_ ) { 3048// a one-token window has advanced the state itself (record_window): no commit graph 3049} else { 3050std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3051const dpct:: err0 le = 3052DPCT_CHECK_ERROR (( cs_ ) -> ext_oneapi_graph ( * commit_exec_ )); 3053/* 3054DPCT1009: SYCL reports errors using exceptions and does not use error 3055codes. Please replace the "get_error_string_dummy(...)" with a real 3056error-handling function. 3057*/ 3058/* 3059DPCT1001: The statement could not be removed. 3060*/ 3061/* 3062DPCT1000: Error handling if-stmt was detected but could not be 3063rewritten. 3064*/ 3065if ( le != 0 ) { 3066err = std:: string ( "verify: commit launch: " ) + 3067dpct:: get_error_string_dummy ( le ); 3068return false; 3069} 3070// set_commit_async: no wait here - the next window runs on the same stream after it, and the drafter (its own 3071// stream) reads only this window's final rows and its own K/V. h_commit_ is next written after the next window's 3072// results are read, i.e. after this graph has run. Everything else waits on commit_done_ (wait_commit). 3073if (! g_commit_async || next_ != nullptr ) { 3074const dpct:: err0 se = DPCT_CHECK_ERROR ( cs_ -> wait ()); 3075/* 3076DPCT1009: SYCL reports errors using exceptions and does not use 3077error codes. Please replace the "get_error_string_dummy(...)" with a 3078real error-handling function. 3079*/ 3080/* 3081DPCT1001: The statement could not be removed. 3082*/ 3083/* 3084DPCT1000: Error handling if-stmt was detected but could not be 3085rewritten. 3086*/ 3087if ( se != 0 ) { 3088err = std:: string ( "verify: commit: " ) + 3089dpct:: get_error_string_dummy ( se ); 3090return false; 3091} 3092} else { 3093/* 3094DPCT1024: The original code returned the error code that was 3095further consumed by the program logic. This original code was 3096replaced with 0. You may need to rewrite the program logic consuming 3097the error code. 3098*/ 3099const dpct:: err0 re = 3100DPCT_CHECK_ERROR (dpct:: sync_barrier ( commit_done_ , cs_ )); 3101/* 3102DPCT1009: SYCL reports errors using exceptions and does not use 3103error codes. Please replace the "get_error_string_dummy(...)" with a 3104real error-handling function. 3105*/ 3106/* 3107DPCT1001: The statement could not be removed. 3108*/ 3109/* 3110DPCT1000: Error handling if-stmt was detected but could not be 3111rewritten. 3112*/ 3113if ( re != 0 ) { 3114err = std:: string ( "verify: commit event: " ) + 3115dpct:: get_error_string_dummy ( re ); 3116return false; 3117} 3118( void ) DPCT_CHECK_ERROR ((( cs_ ) -> ext_oneapi_empty ())); 3119commit_pending_ = true; 3120} 3121} 3122if ( ple_stage ()) // stages that share one session must advance it once 3123for ( int t = 0 ; t < n_keep ; ++ t ) { 3124ss_ -> ple_prev [ 0 ] = ss_ -> ple_prev [ 1 ]; 3125ss_ -> ple_prev [ 1 ] = last_tokens_ [ t ]; 3126} 3127ms_commit += ms_since ( t0 ); 3128return next_ == nullptr || next_ -> commit ( n_keep , err ); 3129} 3130catch (sycl:: exception const & exc ) { 3131std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3132<< ", line:" << __LINE__ << std:: endl ; 3133std:: exit ( 1 ); 3134} 3135 3136bool Verifier :: wait_commit (std:: string & err ) try { 3137if ( commit_pending_ ) { 3138const OnDevice on_device ( device_ ); 3139commit_pending_ = false; 3140const dpct:: err0 se = DPCT_CHECK_ERROR ( commit_done_ -> wait_and_throw ()); 3141/* 3142DPCT1009: SYCL reports errors using exceptions and does not use error 3143codes. Please replace the "get_error_string_dummy(...)" with a real 3144error-handling function. 3145*/ 3146/* 3147DPCT1001: The statement could not be removed. 3148*/ 3149/* 3150DPCT1000: Error handling if-stmt was detected but could not be 3151rewritten. 3152*/ 3153if ( se != 0 ) { 3154err = std:: string ( "verify: commit: " ) + 3155dpct:: get_error_string_dummy ( se ); 3156return false; 3157} 3158} 3159return next_ == nullptr || next_ -> wait_commit ( err ); 3160} 3161catch (sycl:: exception const & exc ) { 3162std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3163<< ", line:" << __LINE__ << std:: endl ; 3164std:: exit ( 1 ); 3165} 3166 3167// SYCL port: capture every window graph now (one per window size) instead of on first use, so the first request 3168// does not pay for them (a 2,400-node graph takes tens of ms to finalize on this backend). 3169bool Verifier :: warm (std:: string & err ) { 3170for ( int T = 1 ; T <= max_t_ ; ++ T ) 3171if (! capture ( T , err )) return false; 3172return true; 3173} 3174 3175// ================================ BATCH WINDOWS (see init_slots) ================================ 3176 3177bool Verifier :: init_slots (const std:: vector < SessionState *> & slots , 3178std:: string & err ) try { 3179const OnDevice on_device ( device_ ); 3180if ( g_ == nullptr || ss_ == nullptr ) { err = "verify: init_slots before init" ; return false; } 3181if ( slots . empty ()) { 3182err = "verify: init_slots needs at least one session" ; 3183return false; 3184} 3185for ( SessionState * x : slots ) { 3186if ( x == nullptr || x -> layer_lo != ss_ -> layer_lo || x -> layer_hi != ss_ -> layer_hi || 3187x -> max_cells != ss_ -> max_cells || x -> gdn_ord0 != ss_ -> gdn_ord0 || x -> qsa_ord0 != ss_ -> qsa_ord0 ) { 3188err = "verify: a slot's session is not carved like the stage's own (layer range, context)" ; 3189return false; 3190} 3191} 3192const strata::kernels:: QsaShapes s = shapes_of ( * g_ ); 3193const int64_t S = ( int64_t ) slots . size (), CB = 2 + max_t_ ; 3194const int64_t TS = ( s . idx_block - 1 ) * g_ -> idx_key_dim , nQ = g_ -> n_qsa_layers (); 3195void * d = nullptr ; 3196if (! mapped (( size_t ) ( S * CB * 4 + 16 ), ( void ** ) & h_commitb_ , ( void ** ) & m_commitb_ )) { 3197err = "verify: the batch commit staging failed" ; 3198return false; 3199} 3200const uint64_t a = (( uint64_t ) S * CB * 4 + 255 ) & ~ 255ull ; 3201if ( DPCT_CHECK_ERROR ( 3202d = ( void * )sycl:: malloc_device ( 3203a + ( uint64_t ) S * std:: max < int64_t > ( nQ , 1 ) * TS * 4 , 3204dpct:: get_in_order_queue ())) != 0 ) { 3205err = "verify: the batch buffers do not fit" ; 3206return false; 3207} 3208arena_b_ = d ; 3209commitb_ = ( int32_t * ) d ; 3210tail_snap_b_ = ( float * ) (( uint8_t * ) d + a ); 3211slots_ = slots ; 3212slot_sp_ . assign ( slots . size (), sampling_ ); // greedy until set_slot_sampling 3213slot_tail_ . assign ( slots . size (), {}); 3214std:: fprintf ( stderr , "strata verify: batch windows of up to %lld sequences (layers [%lld, %lld))\n" , ( long long ) S , 3215( long long ) lb_ , ( long long ) le_ ); 3216return true; 3217} 3218catch (sycl:: exception const & exc ) { 3219std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3220<< ", line:" << __LINE__ << std:: endl ; 3221std:: exit ( 1 ); 3222} 3223 3224bool Verifier :: capture_batch (const int * rows , int S , int hbase , 3225std:: string & err ) try { 3226dpct::experimental:: command_graph_exec_ptr & ex = 3227exec_bm_ [ bkey ( rows , S , hbase )]; 3228if ( ex != nullptr ) return true; 3229if ( DPCT_CHECK_ERROR (dpct::experimental:: begin_recording ( cs_ )) != 0 ) { 3230err = "verify: begin batch capture failed" ; 3231return false; 3232} 3233batch_rec_ = true; 3234row_base_ = hbase ; 3235for ( int t = 0 ; t < S ; ++ t ) brow_ [ t ] = rows [ t ]; 3236std:: string rerr ; 3237const bool ok = record_window ( S , cs_ , rerr ); 3238batch_rec_ = false; 3239row_base_ = 0 ; 3240dpct::experimental:: command_graph_ptr graph = nullptr ; 3241const dpct:: err0 ce = 3242DPCT_CHECK_ERROR (dpct::experimental:: end_recording ( cs_ , & graph )); 3243if (! ok || ce != 0 ) { 3244if ( graph ) delete ( graph ); 3245/* 3246DPCT1009: SYCL reports errors using exceptions and does not use error 3247codes. Please replace the "get_error_string_dummy(...)" with a real 3248error-handling function. 3249*/ 3250err = ! ok ? rerr 3251: std:: string ( "verify: end batch capture: " ) + 3252dpct:: get_error_string_dummy ( ce ); 3253return false; 3254} 3255const dpct:: err0 ie = DPCT_CHECK_ERROR ( 3256ex = new sycl::ext::oneapi::experimental:: command_graph < 3257sycl::ext::oneapi::experimental::graph_state:: executable > ( 3258graph -> finalize ())); 3259delete ( graph ); 3260/* 3261DPCT1009: SYCL reports errors using exceptions and does not use error 3262codes. Please replace the "get_error_string_dummy(...)" with a real 3263error-handling function. 3264*/ 3265/* 3266DPCT1001: The statement could not be removed. 3267*/ 3268/* 3269DPCT1000: Error handling if-stmt was detected but could not be rewritten. 3270*/ 3271if ( ie != 0 ) { 3272err = std:: string ( "verify: batch instantiate: " ) + 3273dpct:: get_error_string_dummy ( ie ); 3274return false; 3275} 3276/* 3277DPCT1007: Migration of cudaGraphUpload is not supported. 3278*/ 3279// no cudaGraphUpload on SYCL: a finalized command_graph is already resident 3280cs_ -> wait (); 3281std:: string list ; 3282for ( int t = 0 ; t < S ; ++ t ) list += ( t ? "," : "" ) + std:: to_string ( rows [ t ]); 3283std:: fprintf ( stderr , "strata verify: captured the batch window over slots %s\n" , list . c_str ()); 3284return true; 3285} 3286catch (sycl:: exception const & exc ) { 3287std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3288<< ", line:" << __LINE__ << std:: endl ; 3289std:: exit ( 1 ); 3290} 3291 3292bool Verifier :: capture_commit_batch (const int * rows , int S , int hbase , 3293std:: string & err ) try { 3294dpct::experimental:: command_graph_exec_ptr & cex = 3295commit_bm_ [ bkey ( rows , S , hbase )]; 3296if ( cex != nullptr ) return true; 3297using namespace strata:: kernels ; 3298const ModelGeometry & g = * g_ ; 3299const QsaShapes s = shapes_of ( g ); 3300const 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_ ; 3301const int64_t CB = 2 + MT , nQ = g . n_qsa_layers (); 3302const uint64_t gdn_floats = ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size + 3303( uint64_t ) g . ssm_conv_channels * ( g . ssm_d_conv - 1 ); 3304const int64_t TS = ( s . idx_block - 1 ) * ID ; 3305const int64_t HS = ( int64_t ) NG_HIST * NG_HC_DIM ; 3306if ( DPCT_CHECK_ERROR (dpct::experimental:: begin_recording ( cs_ )) != 0 ) { 3307err = "verify: begin batch commit capture failed" ; 3308return false; 3309} 3310bool ok = true; 3311try { 3312for ( int t = 0 ; t < S ; ++ t ) 3313if ( t == 0 || rows [ t ] != rows [ t - 1 ]) 3314copy_i32_from_mapped ( commitb_ + ( size_t ) rows [ t ] * CB , m_commitb_ + ( size_t ) rows [ t ] * CB , CB , cs_ ); 3315int64_t qsa_index = 0 , gdn_index = 0 ; 3316for ( int64_t l = 0 ; l < lb_ ; ++ l ) ( is_qsa_layer ( g , l ) ? qsa_index : gdn_index ) += 1 ; 3317for ( int64_t l = lb_ ; l < le_ && ok ; ++ l ) { 3318const LayerView v ( * wt_ , l ); 3319if (! is_qsa_layer ( g , l )) { 3320const WeightRef * wnm = need ( v , "ssm_norm.weight" , err ); 3321if (! wnm ) { ok = false; break; } 3322static const bool gdn_groups_on = [] { // STRATA_BATCH_GDN_GROUPS=1: the one-row groups in one launch 3323const char * e = std:: getenv ( "STRATA_BATCH_GDN_GROUPS" ); 3324return e != nullptr && std:: atoi ( e ) != 0 ; 3325}(); 3326bool one_row = S <= 8 ; 3327for ( int t = 1 ; one_row && t < S ; ++ t ) one_row = rows [ t ] != rows [ t - 1 ]; 3328GdnGroups gg ; 3329for ( int t = 0 ; t < S ;) { 3330const int first = t ; 3331while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 3332SessionState & sx = * slots_ [( size_t ) rows [ first ]]; 3333const int32_t * keep = commitb_ + ( size_t ) rows [ first ] * CB ; 3334float * state = sx . gdn_state + ( size_t ) ( gdn_index - sx . gdn_ord0 ) * gdn_floats ; 3335float * conv = state + ( uint64_t ) g . ssm_state_size * g . ssm_v_heads * g . ssm_state_size ; 3336gdn_conv_commit ( conv , qkv_L_ + ( size_t ) gdn_index * MT * C + ( size_t ) first * C , 3337( int ) C , keep , cs_ ); 3338if ( gdn_groups_on && one_row ) { 3339gg . state [ gg . n ] = state ; 3340gg . keep [ gg . n ] = keep ; 3341gg . first [ gg . n ] = first ; 3342gg . ntok [ gg . n ] = 1 ; 3343++ gg . n ; 3344continue; 3345} 3346gdn_step_norm_multi ( state , h_L_ + ( size_t ) gdn_index * MT * C + ( size_t ) first * C , ( int ) C , 3347gate_L_ + ( size_t ) gdn_index * MT * HV + ( size_t ) first * HV , 3348beta_L_ + ( size_t ) gdn_index * MT * HV + ( size_t ) first * HV , 3349z_ + ( size_t ) first * ZV , (const float * ) wnm -> data , EPS , 3350y_dummy_ + ( size_t ) first * ZV , ( int ) g . ssm_k_heads , 3351( int ) HV , t - first , keep , cs_ , 3352t - first > 1 ? t - first : 0 ); // a 1-row group keeps the 0.1.39 kernel 3353} 3354if ( gg . n > 0 ) 3355gdn_step_norm_groups ( gg , h_L_ + ( size_t ) gdn_index * MT * C , ( int ) C , 3356gate_L_ + ( size_t ) gdn_index * MT * HV , beta_L_ + ( size_t ) gdn_index * MT * HV , 3357z_ , (const float * ) wnm -> data , EPS , y_dummy_ , ( int ) g . ssm_k_heads , ( int ) HV , true, 3358cs_ ); 3359++ gdn_index ; 3360} else { 3361const WeightRef * wikn = need ( v , "indexer.k_norm.weight" , err ); 3362if (! wikn ) { ok = false; break; } 3363for ( int t = 0 ; t < S ;) { 3364const int first = t ; 3365while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 3366const QsaState & st = slots_ [( size_t ) rows [ first ]] -> qsa_states [ qsa_index ]; 3367copy_from_mapped ( st . idx_tail , tail_snap_b_ + (( size_t ) rows [ first ] * nQ + qsa_index ) * TS , 3368TS , cs_ ); 3369const QsaIndexerBuffers ib { st . idx_tail , st . idx_dead , st . idx_pooled , st . idx_block_pos }; 3370for ( int u = first ; u < t ; ++ u ) 3371native_qsa_indexer_append ( idx_raw_L_ + ( size_t ) ( qsa_index * MT + u ) * ID , 3372commitb_ + ( size_t ) rows [ first ] * CB + 2 + ( u - first ), 33730 , (const float * ) wikn -> data , EPS , ib , s , st . max_cells , 3374rope_scaling (), cs_ ); 3375} 3376++ qsa_index ; 3377} 3378} 3379if ( ok && ss_ -> ple . ready () && ple_stage ()) 3380for ( int t = 0 ; t < S ;) { 3381const int first = t ; 3382while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 3383copy_indexed ( slots_ [( size_t ) rows [ first ]] -> ple_hist , hist_snap_ + ( size_t ) first * HS , 3384HS , commitb_ + ( size_t ) rows [ first ] * CB + 1 , HS , cs_ ); 3385} 3386} catch (const std:: exception & e ) { 3387err = std:: string ( "verify batch commit: " ) + e . what (); 3388ok = false; 3389} 3390dpct::experimental:: command_graph_ptr graph = nullptr ; 3391const dpct:: err0 ce = 3392DPCT_CHECK_ERROR (dpct::experimental:: end_recording ( cs_ , & graph )); 3393if (! ok ) { 3394if ( graph ) delete ( graph ); 3395return false; 3396} 3397if ( ce != 0 || 3398DPCT_CHECK_ERROR ( 3399cex = new sycl::ext::oneapi::experimental:: command_graph < 3400sycl::ext::oneapi::experimental::graph_state:: executable > ( 3401graph -> finalize ())) != 0 ) { 3402if ( graph ) delete ( graph ); 3403/* 3404DPCT1009: SYCL reports errors using exceptions and does not use error 3405codes. Please replace the "get_error_string_dummy(...)" with a real 3406error-handling function. 3407*/ 3408err = std:: string ( "verify: batch commit capture: " ) + 3409dpct:: get_error_string_dummy ( ce ); 3410return false; 3411} 3412delete ( graph ); 3413return true; 3414} 3415catch (sycl:: exception const & exc ) { 3416std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3417<< ", line:" << __LINE__ << std:: endl ; 3418std:: exit ( 1 ); 3419} 3420 3421bool Verifier :: stage_batch (const int * rows , int S , int hbase , 3422const int32_t * tokens , const int64_t * pos , 3423std:: string & err ) try { 3424using namespace strata:: kernels ; 3425if ( S < 1 || S > max_t_ || hbase < 0 || 3426( next_ != nullptr && hbase + S > ( int ) slots_ . size ())) { 3427err = "verify: batch rows out of range (init_slots)" ; 3428return false; 3429} 3430for ( int t = 0 ; t < S ; ++ t ) { 3431if ( rows [ t ] < 0 || rows [ t ] >= ( int ) slots_ . size ()) { 3432err = "verify: a batch row's slot is out of range" ; 3433return false; 3434} 3435for ( int u = 0 ; u < t - 1 ; ++ u ) 3436if ( rows [ u ] == rows [ t ] && rows [ t - 1 ] != rows [ t ]) { 3437err = "verify: a slot's proposed rows must be contiguous" ; 3438return false; 3439} 3440if ( t > 0 && rows [ t ] == rows [ t - 1 ] && pos [ t ] != pos [ t - 1 ] + 1 ) { 3441err = "verify: proposed rows must have consecutive positions" ; 3442return false; 3443} 3444if ( t > 0 && rows [ t ] == rows [ t - 1 ] && next_ != nullptr ) { 3445err = "verify: grouped slot rows do not support a layer split yet" ; 3446return false; 3447} 3448} 3449if ( released_ . load ()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine" ; return false; } 3450const ModelGeometry & g = * g_ ; 3451for ( int t = 0 ; t < S ; ++ t ) 3452if ( pos [ t ] < 0 || pos [ t ] + 1 > slots_ [( size_t ) rows [ t ]] -> max_cells ) { 3453err = "verify: slot " + std:: to_string ( rows [ t ]) + " runs past its context" ; 3454return false; 3455} 3456refresh_ar (); 3457// --batch-mtp only (limit 0 = 0.1.39: no eviction): slot rotation creates new layouts; bound the captured graph 3458// pairs, evicting the least recently used layout. 3459if ( batch_graph_limit_ > 0 ) { 3460const auto key = bkey ( rows , S , hbase ); 3461if ( exec_bm_ . find ( key ) == exec_bm_ . end () && exec_bm_ . size () >= batch_graph_limit_ ) { 3462if ( DPCT_CHECK_ERROR ( cs_ -> wait ()) != 0 ) { 3463err = "verify: synchronizing before batch graph eviction failed" ; 3464return false; 3465} 3466auto old = exec_bm_ . begin (); 3467uint64_t oldest = UINT64_MAX ; 3468for ( auto it = exec_bm_ . begin (); it != exec_bm_ . end (); ++ it ) { 3469const auto u = bm_used_ . find ( it -> first ); 3470const uint64_t t = u == bm_used_ . end () ? 0 : u -> second ; 3471if ( t < oldest ) { oldest = t ; old = it ; } 3472} 3473const auto old_key = old -> first ; 3474if ( old -> second ) delete ( old -> second ); 3475exec_bm_ . erase ( old ); 3476bm_used_ . erase ( old_key ); 3477auto commit_old = commit_bm_ . find ( old_key ); 3478if ( commit_old != commit_bm_ . end ()) { 3479if ( commit_old -> second ) delete ( commit_old -> second ); 3480commit_bm_ . erase ( commit_old ); 3481} 3482} 3483bm_used_ [ key ] = ++ bm_tick_ ; 3484} 3485if (! capture_batch ( rows , S , hbase , err ) || ! capture_commit_batch ( rows , S , hbase , err )) return false; 3486const Clock :: time_point t0 = Clock :: now (); 3487const QsaShapes s = shapes_of ( g ); 3488for ( int t = 0 ; t < S ; ++ t ) { 3489h_tok_ [ t ] = tokens [ t ]; 3490qsa_step_fill ( h_step_ + t * kStepCount , pos [ t ], s ); 3491for ( int64_t h = 0 ; h < g . n_head ; ++ h ) h_pos_ [ t * g . n_head + h ] = ( int32_t ) pos [ t ]; 3492int32_t * pk = h_pos_ + ( size_t ) max_t_ * g . n_head ; 3493int32_t * pi = pk + ( size_t ) max_t_ * g . n_head_kv ; 3494for ( int64_t h = 0 ; h < g . n_head_kv ; ++ h ) pk [ t * g . n_head_kv + h ] = ( int32_t ) pos [ t ]; 3495for ( int64_t h = 0 ; h < g . idx_q_heads ; ++ h ) pi [ t * g . idx_q_heads + h ] = ( int32_t ) pos [ t ]; 3496} 3497if ( ss_ -> ple . ready () && ple_stage ()) { 3498uint32_t ple_rows [ kVerifyMaxT * PLE_N_HEADS ]; // (not `rows`: that is the slots of the window's rows) 3499for ( int t = 0 ; t < S ; ++ t ) { 3500const SessionState & sx = * slots_ [( size_t ) rows [ t ]]; 3501int32_t prev [ 2 ] = { sx . ple_prev [ 0 ], sx . ple_prev [ 1 ]}; 3502if ( t > 0 && rows [ t ] == rows [ t - 1 ]) { 3503prev [ 0 ] = t > 1 && rows [ t - 2 ] == rows [ t ] ? tokens [ t - 2 ] : sx . ple_prev [ 1 ]; 3504prev [ 1 ] = tokens [ t - 1 ]; 3505} 3506ngram_rows ( & tokens [ t ], prev , 1 , ss_ -> ple . consts , ple_rows + t * PLE_N_HEADS ); 3507} 3508if (! ss_ -> ple . table -> gather_batch ( ple_rows , ( size_t ) S , h_ple_ , err )) return false; 3509} 3510// Each slot owns a contiguous group. The default commit keeps all its rows; speculative 3511// decoding may change the prefix length after comparing the draft with these picks. 3512const int64_t CB = 2 + max_t_ ; 3513for ( int t = 0 ; t < S ;) { 3514const int first = t ; 3515while ( t < S && rows [ t ] == rows [ first ]) ++ t ; 3516int32_t * c = h_commitb_ + ( size_t ) rows [ first ] * CB ; 3517c [ 0 ] = t - first ; 3518c [ 1 ] = t - first - 1 ; 3519for ( int64_t j = 0 ; j < max_t_ ; ++ j ) 3520c [ 2 + j ] = j < t - first ? ( int32_t ) pos [ first + j ] : -1 ; 3521} 3522* (volatile uint32_t * ) h_seq_ = 0 ; 3523for ( int _i = 1 ; _i <= 8 ; ++ _i ) ((volatile uint32_t * ) h_seq_ )[ _i ] = 0 ; /* + the payload tags/checksums */ 3524* (volatile uint32_t * ) h_flag_ = 0 ; 3525* (volatile uint32_t * ) h_flagA_ = 0 ; 3526* (volatile uint32_t * ) h_flagB_ = 0 ; 3527std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3528last_t_ = S ; 3529for ( int t = 0 ; t < S ; ++ t ) last_rows_ [ t ] = rows [ t ]; 3530row_base_ = hbase ; // the graphs' key (and nothing else) reads it until the next stage_batch 3531last_batch_ = true; 3532for ( int t = 0 ; t < S ; ++ t ) { last_tokens_ [ t ] = tokens [ t ]; last_pos_b_ [ t ] = pos [ t ]; } 3533ms_host += ms_since ( t0 ); 3534return true; 3535} 3536catch (sycl:: exception const & exc ) { 3537std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3538<< ", line:" << __LINE__ << std:: endl ; 3539std:: exit ( 1 ); 3540} 3541 3542bool Verifier :: run_slots ( int S , const int32_t * tokens , const int64_t * pos , PoolMultiFn pool , void * user , int32_t * out , 3543std:: string & err ) { 3544int rows [ 8 ] = {}; 3545for ( int t = 0 ; t < S && t < 8 ; ++ t ) rows [ t ] = t ; 3546return run_slot_rows ( rows , S , tokens , pos , pool , user , out , err ); 3547} 3548 3549bool Verifier :: run_slot_rows (const int * rows , int S , const int32_t * tokens , 3550const int64_t * pos , PoolMultiFn pool , void * user , 3551int32_t * out , std:: string & err ) try { 3552using namespace strata:: kernels ; 3553const OnDevice on_device ( device_ ); 3554const ModelGeometry & g = * g_ ; 3555prof_S_ = S ; 3556if (! stage_batch ( rows , S , 0 , tokens , pos , err )) return false; 3557const dpct:: err0 le = 3558DPCT_CHECK_ERROR (( cs_ ) -> ext_oneapi_graph ( * exec_bm_ [ bkey ( rows , S , 0 )])); 3559/* 3560DPCT1009: SYCL reports errors using exceptions and does not use error 3561codes. Please replace the "get_error_string_dummy(...)" with a real 3562error-handling function. 3563*/ 3564/* 3565DPCT1001: The statement could not be removed. 3566*/ 3567/* 3568DPCT1000: Error handling if-stmt was detected but could not be rewritten. 3569*/ 3570if ( le != 0 ) { 3571err = std:: string ( "verify: batch launch: " ) + 3572dpct:: get_error_string_dummy ( le ); 3573return false; 3574} 3575( void ) DPCT_CHECK_ERROR ((( cs_ ) -> ext_oneapi_empty ())); 3576volatile uint32_t * const seq = h_seq_ ; 3577volatile uint32_t * const flag = h_flag_ ; 3578const int64_t steps = le_ - lb_ ; 3579// #646: a stage whose every expert is resident plans on the device and raises no host doorbells, so the 3580// per-layer spin below has nothing to wait for: without the PLE flag the graph finishes with the ring silent 3581// ("verify batch: layer K never rang (graph finished)" - K is that stage's first layer), and with it the graph 3582// sits on the PLE wait until the 20 s timeout. As run() does: raise the PLE flag the graph's first wait reads, 3583// let the graph run to the end, and skip the host's per-layer service (there is nothing to serve). 3584if ( all_resident_ ) { 3585if ( ss_ -> ple . ready () && ple_stage ()) { 3586std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3587_mm_sfence (); 3588* flag = 1 ; 3589} 3590const dpct:: err0 se = DPCT_CHECK_ERROR ( cs_ -> wait ()); 3591/* 3592DPCT1009: SYCL reports errors using exceptions and does not use error 3593codes. Please replace the "get_error_string_dummy(...)" with a real 3594error-handling function. 3595*/ 3596/* 3597DPCT1001: The statement could not be removed. 3598*/ 3599/* 3600DPCT1000: Error handling if-stmt was detected but could not be 3601rewritten. 3602*/ 3603if ( se != 0 ) { 3604err = 3605std:: string ( "verify batch: " ) + dpct:: get_error_string_dummy ( se ); 3606return false; 3607} 3608copy_ -> wait (); 3609if ( prof_on_ ) collect_profile (); 3610++ windows ; 3611if ( le_ < g . n_layers ) return next_ == nullptr || next_ -> run_slot_rows ( rows , S , tokens , pos , pool , next_user_ , out , err ); 3612if (! sample_rows ( S , err )) return false; 3613for ( int t = 0 ; t < S ; ++ t ) out [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 3614progress_at ( "decode" ); 3615progress_beat (); 3616return true; 3617} 3618for ( int64_t k = 0 ; k < steps ; ++ k ) { 3619const int64_t l = lb_ + k ; 3620const uint32_t want = ( uint32_t ) ( k + 1 ); 3621const Clock :: time_point a = Clock :: now (); 3622auto last_flush = a ; 3623uint32_t spins = 0 ; 3624progress_at ( "verify batch: waiting for the GPU to reach layer" , l ); 3625while ( * seq < want ) { 3626_mm_pause (); 3627if (( ++ spins & 1023u ) != 0 ) continue; 3628const auto now = Clock :: now (); 3629if ( now - last_flush > std::chrono:: microseconds ( 2000 )) { 3630last_flush = now ; 3631const dpct:: err0 q = cs_ -> ext_oneapi_empty () ? 0 : 1 ; 3632if ( q != 1 && * seq < want ) { 3633err = "verify batch: layer " + std:: to_string ( l ) + 3634" never rang (" + 3635/* 3636DPCT1009: SYCL reports errors using exceptions and 3637does not use error codes. Please replace the 3638"get_error_string_dummy(...)" with a real 3639error-handling function. 3640*/ 3641( q == 0 3642? std:: string ( "graph finished" ) 3643: std:: string (dpct:: get_error_string_dummy ( q ))) + 3644")" ; 3645return false; 3646} 3647} 3648if ( now - a > strata_ring_timeout ()) { 3649err = "verify batch: timed out at layer " + std:: to_string ( l ) + released_note ( release_gpu_waits ( 5000 )); 3650return false; 3651} 3652} 3653const Clock :: time_point b = Clock :: now (); 3654cur_layer_ = want - 1 ; 3655set_plan_slot ( 0 ); 3656progress_at ( "verify batch: the CPU experts of layer" , l ); 3657if ( pool != nullptr ) pool ( user , h_x_ , h_ids_ , S , ss_ -> k , h_ymiss_ , l ); 3658progress_tick (); 3659std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3660_mm_sfence (); 3661if ( * (volatile uint32_t * ) h_flagA_ != want ) { // the pool did not publish a plan: an empty one 3662sink_ . counts [ 0 ] = 0 ; 3663sink_ . counts [ 1 ] = 0 ; 3664sink_ . counts [ 2 ] = 0 ; 3665sink_ . start [ 0 ] = 0 ; 3666sink_ . start2 [ 0 ] = 0 ; 3667std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3668* (volatile uint32_t * ) h_flagA_ = want ; 3669raise_flag ( h_flagB_ , want ); 3670} 3671* flag = want ; 3672ms_wait += std::chrono:: duration < double , std:: milli > ( b - a ). count (); 3673ms_pool += ms_since ( b ); 3674} 3675const dpct:: err0 se = DPCT_CHECK_ERROR ( cs_ -> wait ()); 3676/* 3677DPCT1009: SYCL reports errors using exceptions and does not use error 3678codes. Please replace the "get_error_string_dummy(...)" with a real 3679error-handling function. 3680*/ 3681/* 3682DPCT1001: The statement could not be removed. 3683*/ 3684/* 3685DPCT1000: Error handling if-stmt was detected but could not be rewritten. 3686*/ 3687if ( se != 0 ) { 3688err = std:: string ( "verify batch: " ) + dpct:: get_error_string_dummy ( se ); 3689return false; 3690} 3691copy_ -> wait (); 3692if ( prof_on_ ) collect_profile (); 3693++ windows ; 3694if ( le_ < g . n_layers ) return next_ == nullptr || next_ -> run_slot_rows ( rows , S , tokens , pos , pool , next_user_ , out , err ); 3695if (! sample_rows ( S , err )) return false; 3696for ( int t = 0 ; t < S ; ++ t ) out [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 3697progress_at ( "decode" ); 3698progress_beat (); 3699return true; 3700} 3701catch (sycl:: exception const & exc ) { 3702std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3703<< ", line:" << __LINE__ << std:: endl ; 3704std:: exit ( 1 ); 3705} 3706 3707bool Verifier :: commit_slots (std:: string & err ) { 3708std:: vector < int > keep ( slots_ . size (), 0 ); 3709for ( int t = 0 ; t < last_t_ ; ++ t ) ++ keep [( size_t ) last_rows_ [ t ]]; 3710return commit_slot_prefixes ( keep . data (), err ); 3711} 3712 3713bool Verifier :: commit_slot_prefixes (const int * keep , std:: string & err ) try { 3714const OnDevice on_device ( device_ ); 3715if (! last_batch_ || last_t_ < 1 ) { err = "verify: commit_slots without a batch window" ; return false; } 3716const int S = last_t_ ; 3717const Clock :: time_point t0 = Clock :: now (); 3718const int64_t CB = 2 + max_t_ ; 3719// One prefix per slot: rejected draft rows must not enter recurrent state. 3720for ( int t = 0 ; t < S ;) { 3721const int first = t ; 3722while ( t < S && last_rows_ [ t ] == last_rows_ [ first ]) ++ t ; 3723const int n = keep [ last_rows_ [ first ]]; 3724if ( n < 1 || n > t - first ) { 3725err = "verify: accepted prefix is outside its slot group" ; 3726return false; 3727} 3728int32_t * c = h_commitb_ + ( size_t ) last_rows_ [ first ] * CB ; 3729c [ 0 ] = n ; 3730c [ 1 ] = n - 1 ; 3731for ( int j = 0 ; j < max_t_ ; ++ j ) 3732c [ 2 + j ] = j < n ? ( int32_t ) last_pos_b_ [ first + j ] : -1 ; 3733} 3734std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3735const dpct:: err0 le = DPCT_CHECK_ERROR ( 3736( cs_ ) -> ext_oneapi_graph ( * commit_bm_ [ bkey ( last_rows_ , S , row_base_ )])); 3737/* 3738DPCT1009: SYCL reports errors using exceptions and does not use error 3739codes. Please replace the "get_error_string_dummy(...)" with a real 3740error-handling function. 3741*/ 3742/* 3743DPCT1001: The statement could not be removed. 3744*/ 3745/* 3746DPCT1000: Error handling if-stmt was detected but could not be rewritten. 3747*/ 3748if ( le != 0 ) { 3749err = std:: string ( "verify: batch commit launch: " ) + 3750dpct:: get_error_string_dummy ( le ); 3751return false; 3752} 3753const dpct:: err0 se = DPCT_CHECK_ERROR ( cs_ -> wait ()); 3754/* 3755DPCT1009: SYCL reports errors using exceptions and does not use error 3756codes. Please replace the "get_error_string_dummy(...)" with a real 3757error-handling function. 3758*/ 3759/* 3760DPCT1001: The statement could not be removed. 3761*/ 3762/* 3763DPCT1000: Error handling if-stmt was detected but could not be rewritten. 3764*/ 3765if ( se != 0 ) { 3766err = std:: string ( "verify: batch commit: " ) + 3767dpct:: get_error_string_dummy ( se ); 3768return false; 3769} 3770if ( ple_stage ()) 3771for ( int t = 0 ; t < S ;) { 3772const int first = t ; 3773while ( t < S && last_rows_ [ t ] == last_rows_ [ first ]) ++ t ; 3774SessionState & sx = * slots_ [( size_t ) last_rows_ [ first ]]; 3775for ( int u = first ; u < first + keep [ last_rows_ [ first ]]; ++ u ) { 3776sx . ple_prev [ 0 ] = sx . ple_prev [ 1 ]; 3777sx . ple_prev [ 1 ] = last_tokens_ [ u ]; 3778} 3779} 3780ms_commit += ms_since ( t0 ); 3781return next_ == nullptr || next_ -> commit_slot_prefixes ( keep , err ); 3782} 3783catch (sycl:: exception const & exc ) { 3784std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3785<< ", line:" << __LINE__ << std:: endl ; 3786std:: exit ( 1 ); 3787} 3788 3789bool Verifier :: sample_rows ( int S , std:: string & err ) try { 3790bool any = false; 3791constexpr int kSlotHistMax = 4096 ; // serve's kPenaltyWindowCap 3792std:: vector < int32_t > hrows ; 3793std:: vector < const int32_t *> tails ( slots_ . size (), nullptr ); 3794std:: vector < int64_t > n_tails ( slots_ . size (), 0 ); 3795for ( 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 (); } 3796for ( int t = 0 ; t < S ; ++ t ) { 3797strata::kernels:: SamplerParams sp = slot_sp_ [( size_t ) last_rows_ [ t ]]; 3798const bool pen = sp . penalty_last_n > 0 && ( sp . penalty_repeat != 1.0f || sp . penalty_freq != 0.0f || sp . penalty_present != 0.0f ); 3799if (( sp . greedy || sp . temperature <= 0.0f ) && ! pen ) continue; // a plain greedy slot keeps the window's argmax token untouched 3800sp . counter = ( uint64_t ) last_pos_b_ [ t ]; // Philox(seed, position): the solo window's draw for this position 3801const int32_t * hist = nullptr ; 3802int hlen = 0 ; 3803if ( pen ) { 3804// the slot's reply tail plus its tokens in this window up to row t (slot_penalty_rows), staged on the device like a solo window's 3805hlen = std:: min ( sp . penalty_last_n , kSlotHistMax ); 3806const size_t need = ( size_t ) S * ( size_t ) hlen ; 3807hrows . assign ( need , -1 ); 3808strata::kernels:: slot_penalty_rows ( last_rows_ , last_tokens_ , S , tails . data (), n_tails . data (), hlen , hrows . data ()); 3809const OnDevice on_hist ( device_ ); 3810if ( slot_hist_cap_ < need ) { 3811if ( slot_hist_d_ != nullptr ) sycl:: free ( slot_hist_d_ , * cs_ ); 3812slot_hist_d_ = sycl:: malloc_device < int32_t > ( need , * cs_ ); 3813if ( slot_hist_d_ == nullptr ) { slot_hist_cap_ = 0 ; err = "verify batch: the penalty-history allocation failed" ; return false; } 3814slot_hist_cap_ = need ; 3815} 3816cs_ -> memcpy ( slot_hist_d_ + ( size_t ) t * ( size_t ) hlen , hrows . data () + ( size_t ) t * ( size_t ) hlen , ( size_t ) hlen * sizeof( int32_t )). wait (); // (waited: the host rows are rebuilt for the next row) 3817hist = slot_hist_d_ + ( size_t ) t * ( size_t ) hlen ; 3818} else { 3819sp . penalty_last_n = 0 ; 3820} 3821strata::kernels:: sample_tokens ( head_logits_ + ( size_t ) t * ( size_t ) n_vocab_ , 1 , ( int ) n_vocab_ , hist , hlen , sp , 3822m_out_ + t , cs_ ); 3823any = true; 3824} 3825if ( any && DPCT_CHECK_ERROR ( cs_ -> wait ()) != 0 ) { 3826err = "verify batch: the row sampling failed" ; return false; 3827} 3828return true; 3829} 3830catch (sycl:: exception const & exc ) { 3831std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3832<< ", line:" << __LINE__ << std:: endl ; 3833std:: exit ( 1 ); 3834} 3835 3836bool Verifier :: batch_launch ( int base , int S , const int32_t * tokens , 3837const int64_t * pos , std:: string & err ) try { 3838const OnDevice on_device ( device_ ); 3839if ( b_running_ ) { err = "verify: batch_launch while this stage is busy" ; return false; } 3840int rows [ 8 ] = {}; 3841for ( int t = 0 ; t < S && t < 8 ; ++ t ) rows [ t ] = base + t ; 3842if (! stage_batch ( rows , S , base , tokens , pos , err )) return false; 3843dpct:: err0 le = DPCT_CHECK_ERROR ( 3844( cs_ ) -> ext_oneapi_graph ( * exec_bm_ [ bkey ( rows , S , base )])); 3845if ( le == 0 ) le = DPCT_CHECK_ERROR (( cs_ ) -> ext_oneapi_graph ( * commit_bm_ [ bkey ( 3846rows , S , base )])); // right behind it: every row is kept 3847/* 3848DPCT1009: SYCL reports errors using exceptions and does not use error 3849codes. Please replace the "get_error_string_dummy(...)" with a real 3850error-handling function. 3851*/ 3852/* 3853DPCT1001: The statement could not be removed. 3854*/ 3855/* 3856DPCT1000: Error handling if-stmt was detected but could not be rewritten. 3857*/ 3858if ( le != 0 ) { 3859err = std:: string ( "verify: batch launch: " ) + 3860dpct:: get_error_string_dummy ( le ); 3861return false; 3862} 3863( void ) DPCT_CHECK_ERROR ((( cs_ ) -> ext_oneapi_empty ())); 3864if ( ple_stage ()) // the host's side of the commit (the hash's last two tokens) 3865for ( int t = 0 ; t < S ; ++ t ) { 3866SessionState & sx = * slots_ [( size_t ) rows [ t ]]; 3867sx . ple_prev [ 0 ] = sx . ple_prev [ 1 ]; 3868sx . ple_prev [ 1 ] = tokens [ t ]; 3869} 3870b_running_ = true; 3871b_k_ = 0 ; 3872b_steps_ = le_ - lb_ ; 3873b_last_ = Clock :: now (); 3874return true; 3875} 3876catch (sycl:: exception const & exc ) { 3877std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3878<< ", line:" << __LINE__ << std:: endl ; 3879std:: exit ( 1 ); 3880} 3881 3882int Verifier :: batch_poll ( PoolMultiFn pool , void * user , std:: string & err ) try { 3883if (! b_running_ ) return 1 ; 3884const OnDevice on_device ( device_ ); 3885volatile uint32_t * const seq = h_seq_ ; 3886const int S = last_t_ ; 3887// #646: an all-resident stage's graph raises no host doorbells (see run_slot_rows): nothing to serve per layer, 3888// so the poll is just "has the graph finished" - except the PLE flag, which the graph's first wait reads and 3889// only the host can raise (the same raise run_slot_rows makes). 3890if ( all_resident_ && ss_ -> ple . ready () && ple_stage ()) { 3891std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3892_mm_sfence (); 3893* h_flag_ = 1 ; 3894} 3895while (! all_resident_ && b_k_ < b_steps_ ) { 3896const uint32_t want = ( uint32_t ) ( b_k_ + 1 ); 3897if ( * seq < want ) { 3898const auto now = Clock :: now (); 3899if ( now - b_last_ > std::chrono:: milliseconds ( 2 )) { 3900const dpct:: err0 q = cs_ -> ext_oneapi_empty () ? 0 : 1 ; 3901if ( q != 1 && * seq < want ) { 3902err = "verify batch: layer " + std:: to_string ( lb_ + b_k_ ) + 3903" never rang (" + 3904/* 3905DPCT1009: SYCL reports errors using exceptions and 3906does not use error codes. Please replace the 3907"get_error_string_dummy(...)" with a real 3908error-handling function. 3909*/ 3910( q == 0 3911? std:: string ( "graph finished" ) 3912: std:: string (dpct:: get_error_string_dummy ( q ))) + 3913")" ; 3914b_running_ = false; 3915return -1 ; 3916} 3917if ( now - b_last_ > strata_ring_timeout ()) { 3918err = "verify batch: timed out at layer " + std:: to_string ( lb_ + b_k_ ) + released_note ( release_gpu_waits ( 5000 )); 3919b_running_ = false; 3920return -1 ; 3921} 3922} 3923return 0 ; 3924} 3925const Clock :: time_point b = Clock :: now (); 3926cur_layer_ = want - 1 ; 3927set_plan_slot ( 0 ); 3928if ( pool != nullptr ) pool ( user , h_x_ , h_ids_ , S , ss_ -> k , h_ymiss_ , lb_ + b_k_ ); 3929progress_tick (); 3930std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3931_mm_sfence (); 3932if ( * (volatile uint32_t * ) h_flagA_ != want ) { // the pool did not publish a plan: an empty one 3933sink_ . counts [ 0 ] = 0 ; 3934sink_ . counts [ 1 ] = 0 ; 3935sink_ . counts [ 2 ] = 0 ; 3936sink_ . start [ 0 ] = 0 ; 3937sink_ . start2 [ 0 ] = 0 ; 3938std:: atomic_thread_fence (std:: memory_order_seq_cst ); 3939* (volatile uint32_t * ) h_flagA_ = want ; 3940raise_flag ( h_flagB_ , want ); 3941} 3942* (volatile uint32_t * ) h_flag_ = want ; 3943ms_pool += ms_since ( b ); 3944b_last_ = Clock :: now (); 3945++ b_k_ ; 3946} 3947const dpct:: err0 q = cs_ -> ext_oneapi_empty () ? 0 : 1 ; 3948/* 3949DPCT1001: The statement could not be removed. 3950*/ 3951/* 3952DPCT1002: Special case error handling if-stmt was detected. You may need 3953to rewrite this code. 3954*/ 3955if ( q == 1 ) return 0 ; 3956/* 3957DPCT1009: SYCL reports errors using exceptions and does not use error 3958codes. Please replace the "get_error_string_dummy(...)" with a real 3959error-handling function. 3960*/ 3961/* 3962DPCT1001: The statement could not be removed. 3963*/ 3964/* 3965DPCT1000: Error handling if-stmt was detected but could not be rewritten. 3966*/ 3967if ( q != 0 ) { 3968err = std:: string ( "verify batch: " ) + dpct:: get_error_string_dummy ( q ); 3969b_running_ = false; 3970return -1 ; 3971} 3972const dpct:: err0 qc = DPCT_CHECK_ERROR ( 3973(( copy_ ) -> ext_oneapi_empty ())); // no host function of this window may 3974// raise flag B in the next 3975/* 3976DPCT1001: The statement could not be removed. 3977*/ 3978/* 3979DPCT1002: Special case error handling if-stmt was detected. You may need 3980to rewrite this code. 3981*/ 3982if ( qc == 1 ) return 0 ; 3983if ( prof_on_ ) collect_profile (); 3984if ( last_stage ()) { 3985if (! sample_rows ( S , err )) { b_running_ = false; return -1 ; } 3986for ( int t = 0 ; t < S ; ++ t ) b_out_ [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 3987} 3988++ windows ; 3989b_running_ = false; 3990progress_beat (); 3991return 1 ; 3992} 3993catch (sycl:: exception const & exc ) { 3994std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 3995<< ", line:" << __LINE__ << std:: endl ; 3996std:: exit ( 1 ); 3997} 3998 3999bool Verifier :: copy_logits ( int t , float * host ) const { 4000if ( next_ != nullptr ) return next_ -> copy_logits ( t , host ); // a layer split: the head is on the last stage 4001if ( head_logits_ == nullptr || host == nullptr || t < 0 || n_vocab_ <= 0 ) return false; 4002try { 4003cs_ -> memcpy ( host , head_logits_ + ( size_t ) t * ( size_t ) n_vocab_ , ( size_t ) n_vocab_ * sizeof( float )). wait (); 4004} catch (sycl:: exception const & ) { 4005return false; 4006} 4007return true; 4008} 4009 4010// ================================ PIPELINED WINDOWS (see verify.hpp) ================================ 4011// 4012// The window is run()'s, step for step: the same graph, the same staging, the same per-layer service (the PLE rows 4013// gathered while layer 0 is served, the zero-doorbell graph's one flag), the same commit graph. Only the waits are 4014// split up: the host polls instead of spinning, so it can serve the other stage's window in between. 4015 4016namespace { 4017double now_ms () { return std::chrono:: duration < double , std:: milli > ( Clock :: now (). time_since_epoch ()). count (); } 4018} // namespace 4019 4020void Verifier :: diag_pipelined (std:: FILE * f , const char * name ) const { 4021auto rd = [](const uint32_t * p ) { return p ? * (const volatile uint32_t * ) p : 0u ; }; 4022auto ev = [](dpct:: event_ptr e ) { 4023try { 4024if ( e == nullptr ) return "none" ; 4025const dpct:: err0 q = dpct:: sycl_event_query ( e ); 4026return q == 0 ? "done" : q == 1 ? "PENDING" : "error" ; 4027} 4028catch (sycl:: exception const & exc ) { 4029std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 4030<< ", line:" << __LINE__ << std:: endl ; 4031std:: exit ( 1 ); 4032} 4033}; 4034std:: fprintf ( f , " %s: %s T=%d pos %lld served %lld/%lld; GPU rang %u, flags served %u A %u B %u; window event %s, " 4035"commit event %s (commit launched %d)\n" , name , fl_active_ ? "IN FLIGHT" : "idle" , last_t_ , 4036( long long ) last_pos0_ , ( long long ) fl_k_ , ( long long ) fl_total_ , rd ( h_seq_ ), rd ( h_flag_ ), rd ( h_flagA_ ), 4037rd ( h_flagB_ ), ev ( ev_done_ ), ev ( ev_commit_ ), ( int ) commit_live_ ); 4038} 4039 4040bool Verifier :: capture_all (std:: string & err ) try { 4041const OnDevice on_device ( device_ ); 4042if ( g_ == nullptr ) { err = "verify: capture_all before init" ; return false; } 4043if ( remote_opt_ != nullptr ) { err = "verify: pipelined windows do not serve --remote-expert-opt" ; return false; } 4044if ( released_ . load ()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine" ; return false; } 4045for ( int T = 1 ; T <= max_t_ ; ++ T ) 4046if (! capture ( T , err )) return false; 4047if (! capture_commit ( err )) return false; 4048if (( ev_done_ == nullptr && 4049DPCT_CHECK_ERROR ( ev_done_ = new sycl:: event ()) != 0 ) || 4050( ev_commit_ == nullptr && 4051DPCT_CHECK_ERROR ( ev_commit_ = new sycl:: event ()) != 0 )) { 4052err = "verify: event create failed" ; 4053return false; 4054} 4055if ( prof_on_ && prof_pin_ == nullptr && 4056/* 4057DPCT1048: The original value cudaHostAllocDefault is not meaningful in 4058the migrated code and was removed or replaced with 0. You may need to 4059check the migrated code. 4060*/ 4061DPCT_CHECK_ERROR ( prof_pin_ = ( unsigned long long * )sycl:: malloc_host ( 4062prof_h_ . size () * 8 , dpct:: get_in_order_queue ())) != 40630 ) { 4064prof_pin_ = nullptr ; // the pipelined windows go unprofiled 4065/* 4066DPCT1026: The call to cudaGetLastError was removed because this 4067functionality is redundant in SYCL. 4068*/ 4069} 4070pl_ple_rows_ . assign (( size_t ) strata::kernels:: kVerifyMaxT * strata::kernels:: PLE_N_HEADS , 0u ); 4071return true; 4072} 4073catch (sycl:: exception const & exc ) { 4074std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 4075<< ", line:" << __LINE__ << std:: endl ; 4076std:: exit ( 1 ); 4077} 4078 4079// The host staging of a pipelined window: run()'s (stage_inputs), and its PLE rows from `ple_prev` with their pages 4080// prefetched (they are gathered into the mapped rows when layer 0 is served, as run() does). 4081void Verifier :: pl_stage ( int T , const int32_t * tokens , int64_t pos0 , const int32_t ple_prev [ 2 ]) { 4082using namespace strata:: kernels ; 4083stage_inputs ( T , tokens , pos0 ); 4084staged_ = false; // a later run() stages its own window 4085SessionState & ss = * ss_ ; 4086fl_ple_ = ss . ple . ready () && ple_stage (); 4087if ( fl_ple_ ) { 4088int32_t prev [ 2 ] = { ple_prev [ 0 ], ple_prev [ 1 ]}; 4089for ( int t = 0 ; t < T ; ++ t ) { 4090ngram_rows ( & tokens [ t ], prev , 1 , ss . ple . consts , pl_ple_rows_ . data () + t * PLE_N_HEADS ); 4091prev [ 0 ] = prev [ 1 ]; 4092prev [ 1 ] = tokens [ t ]; 4093ss . ple . table -> prefetch_rows ( pl_ple_rows_ . data () + t * PLE_N_HEADS ); 4094} 4095} 4096pl_prev_ [ 0 ] = ple_prev [ 0 ]; 4097pl_prev_ [ 1 ] = ple_prev [ 1 ]; 4098} 4099 4100bool Verifier :: prestage ( int T , const int32_t * tokens , int64_t pos0 , const int32_t ple_prev [ 2 ], std:: string & err ) { 4101if ( fl_active_ ) { err = "verify: a window is in flight on this verifier" ; return false; } 4102if ( T < 1 || T > max_t_ ) { err = "verify: window size out of range" ; return false; } 4103if ( pl_ple_rows_ . empty ()) { err = "verify: pipelined window not prepared (capture_all)" ; return false; } 4104const Clock :: time_point t0 = Clock :: now (); 4105pl_stage ( T , tokens , pos0 , ple_prev ); 4106pl_prestaged_ = true; 4107ms_host += ms_since ( t0 ); 4108return true; 4109} 4110 4111bool Verifier :: pl_launch ( int T , const int32_t * tokens , int64_t pos0 , 4112std:: string & err ) try { 4113const OnDevice on_device ( device_ ); 4114if ( fl_active_ ) { err = "verify: a window is already in flight on this verifier" ; return false; } 4115if ( released_ . load ()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine" ; return false; } 4116if ( T < 1 || T > max_t_ ) { err = "verify: window size out of range" ; return false; } 4117SessionState & ss = * ss_ ; 4118if ( pos0 + T > ss . qsa_states [ ss . qsa_primary ()]. max_cells ) { err = "verify: the window runs past the context" ; return false; } 4119if ( exec_ [ T ] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_ . empty ()) { 4120err = "verify: pipelined window not prepared (capture_all)" ; 4121return false; 4122} 4123const Clock :: time_point t0 = Clock :: now (); 4124last_batch_ = false; 4125bool staged = pl_prestaged_ && last_t_ == T && last_pos0_ == pos0 ; 4126for ( int t = 0 ; staged && t < T ; ++ t ) staged = last_tokens_ [ t ] == tokens [ t ]; 4127if ( staged && ss . ple . ready () && ple_stage ()) 4128staged = pl_prev_ [ 0 ] == ss . ple_prev [ 0 ] && pl_prev_ [ 1 ] == ss . ple_prev [ 1 ]; 4129pl_prestaged_ = false; 4130if (! staged ) pl_stage ( T , tokens , pos0 , ss . ple_prev ); 4131const int G = groups_ [ T ] > 0 ? groups_ [ T ] : 1 ; 4132fl_T_ = T ; 4133fl_k_ = 0 ; 4134fl_total_ = ( le_ - lb_ ) * G ; 4135fl_prof_ = prof_on_ && G == 1 && prof_pin_ != nullptr ; 4136if ( trace_h_ != nullptr ) std:: memset ( trace_h_ , 0 , trace_n_ * 8 ); // #649: this window's breadcrumbs only 4137std:: atomic_thread_fence (std:: memory_order_seq_cst ); 4138trace_ev ( "WINDOW (pipelined)" , -1 , -1 , pos0 * 16 + T ); 4139ms_host += ms_since ( t0 ); 4140const dpct:: err0 le = DPCT_CHECK_ERROR (( cs_ ) -> ext_oneapi_graph ( * exec_ [ T ])); 4141trace_ev ( "LAUNCHED" , -1 , -1 , ( int64_t ) le ); 4142/* 4143DPCT1009: SYCL reports errors using exceptions and does not use error 4144codes. Please replace the "get_error_string_dummy(...)" with a real 4145error-handling function. 4146*/ 4147/* 4148DPCT1001: The statement could not be removed. 4149*/ 4150/* 4151DPCT1000: Error handling if-stmt was detected but could not be rewritten. 4152*/ 4153if ( le != 0 ) { 4154err = std:: string ( "verify: launch: " ) + dpct:: get_error_string_dummy ( le ); 4155return false; 4156} 4157/* 4158DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While 4159the origin API might be synchronous, it depends on the type of operand 4160memory, so you may need to call wait() on event return by memcpy API to 4161ensure synchronization behavior. 4162*/ 4163if ( fl_prof_ ) cs_ -> memcpy ( prof_pin_ , prof_ , prof_h_ . size () * 8 ); 4164/* 4165DPCT1024: The original code returned the error code that was further 4166consumed by the program logic. This original code was replaced with 0. You 4167may need to rewrite the program logic consuming the error code. 4168*/ 4169if ( DPCT_CHECK_ERROR (dpct:: sync_barrier ( ev_done_ , cs_ )) != 0 ) { 4170err = "verify: event record failed" ; return false; 4171} 4172( void ) DPCT_CHECK_ERROR ((( cs_ ) -> ext_oneapi_empty ())); // WDDM: submit now 4173fl_active_ = true; 4174fl_since_ms_ = fl_flush_ms_ = fl_launch_ms_ = now_ms (); 4175return true; 4176} 4177catch (sycl:: exception const & exc ) { 4178std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 4179<< ", line:" << __LINE__ << std:: endl ; 4180std:: exit ( 1 ); 4181} 4182 4183int Verifier :: service ( PoolMultiFn pool , void * user , std:: string & err ) try { 4184if (! fl_active_ ) return 1 ; 4185if ( fl_k_ >= fl_total_ ) return 1 ; 4186const OnDevice on_device ( device_ ); 4187const ModelGeometry & g = * g_ ; 4188SessionState & ss = * ss_ ; 4189const int T = fl_T_ ; 4190// the PLE rows into the mapped staging (layer 1's pre() copies them once flag 1 is up), as run() does at k == 0 4191auto gather_ple = [ & ]() -> bool { 4192if (! fl_ple_ ) return true; 4193const Clock :: time_point tp = Clock :: now (); 4194if (! ss . ple . table -> gather_batch ( pl_ple_rows_ . data (), ( size_t ) T , h_ple_ , err )) return false; 4195std:: atomic_thread_fence (std:: memory_order_seq_cst ); 4196_mm_sfence (); 4197ms_host += ms_since ( tp ); 4198return true; 4199}; 4200if ( all_resident_ ) { // the zero-doorbell graph never rings: it waits only for flag 1 (stage 0's PLE rows) 4201if (! gather_ple ()) return -1 ; 4202* (volatile uint32_t * ) h_flag_ = 1 ; 4203fl_k_ = fl_total_ ; 4204progress_tick (); 4205return 1 ; 4206} 4207const int G = groups_ [ T ] > 0 ? groups_ [ T ] : 1 ; 4208const int gtb [ 2 ] = { 0 , ( T + 1 ) / 2 }, gte [ 2 ] = { G == 2 ? ( T + 1 ) / 2 : T , T }; 4209while ( fl_k_ < fl_total_ ) { 4210const int64_t l = lb_ + fl_k_ / G ; 4211const uint32_t want = ( uint32_t ) ( fl_k_ + 1 ); 4212if ( * (volatile uint32_t * ) h_seq_ < want ) { 4213const double now = now_ms (); 4214if ( now - fl_flush_ms_ > 2.0 ) { // flush WDDM and notice a dead graph, as run() does 4215fl_flush_ms_ = now ; 4216const dpct:: err0 q = dpct:: sycl_event_query ( ev_done_ ); 4217if ( q != 1 && * (volatile uint32_t * ) h_seq_ < want ) { 4218trace_ev ( "NEVER-RANG" , fl_k_ , l , ( int64_t ) q ); 4219err = "verify: layer " + std:: to_string ( l ) + 4220" never rang (" + 4221/* 4222DPCT1009: SYCL reports errors using exceptions and 4223does not use error codes. Please replace the 4224"get_error_string_dummy(...)" with a real 4225error-handling function. 4226*/ 4227( q == 0 4228? std:: string ( "graph finished" ) 4229: std:: string (dpct:: get_error_string_dummy ( q ))) + 4230")" ; 4231return -1 ; 4232} 4233( void ) DPCT_CHECK_ERROR ((( cs_ ) -> ext_oneapi_empty ())); 4234} 4235if ( now - fl_since_ms_ > 20000.0 ) { // #267: no spin kernel may outlive the engine 4236trace_ev ( "TIMEOUT" , fl_k_ , l , 0 ); 4237err = "verify: timed out at layer " + std:: to_string ( l ) + released_note ( release_gpu_waits ( 5000 )); 4238return -1 ; 4239} 4240return 0 ; 4241} 4242const Clock :: time_point b = Clock :: now (); 4243ms_wait += now_ms () - fl_since_ms_ ; 4244const int grp = ( int ) ( fl_k_ % G ); 4245cur_layer_ = want - 1 ; 4246set_plan_slot ( grp ); 4247const int tb = gtb [ grp ], n = gte [ grp ] - gtb [ grp ]; 4248// the ring can arrive before its payload (elementwise.hpp): the pool must read a whole one 4249if (!strata::kernels:: doorbell_wait_payload ( h_seq_ , h_x_ + ( size_t ) tb * g . n_embd , ( int64_t ) n * g . n_embd , 4250h_ids_ + ( size_t ) tb * ss . k , h_w_ + ( size_t ) tb * ss . k , 4251( int64_t ) n * ss . k , want )) { 4252err = "verify: layer " + std:: to_string ( l ) + " rang but its payload never arrived whole" ; 4253return -1 ; 4254} 4255progress_at ( "verify window (pipelined): the CPU experts of layer" , l ); 4256if ( pool != nullptr ) 4257pool ( user , h_x_ + ( size_t ) tb * g . n_embd , h_ids_ + ( size_t ) tb * ss . k , n , ss . k , 4258h_ymiss_ + ( size_t ) tb * ss . k * g . n_embd , l ); 4259if ( g_trace ) trace_ev ( * (volatile uint32_t * ) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET" , fl_k_ , l , 4260( int64_t ) ms_since ( b )); 4261progress_tick (); 4262std:: atomic_thread_fence (std:: memory_order_seq_cst ); 4263_mm_sfence (); 4264if ( * (volatile uint32_t * ) h_flagA_ != want ) { // the pool did not publish a plan: an empty one 4265sink_ . counts [ 0 ] = 0 ; 4266sink_ . counts [ 1 ] = 0 ; 4267sink_ . counts [ 2 ] = 0 ; 4268sink_ . start [ 0 ] = 0 ; 4269sink_ . start2 [ 0 ] = 0 ; 4270std:: atomic_thread_fence (std:: memory_order_seq_cst ); 4271* (volatile uint32_t * ) h_flagA_ = want ; 4272raise_flag ( h_flagB_ , want ); 4273} 4274if ( fl_k_ == 0 && ! gather_ple ()) return -1 ; 4275* (volatile uint32_t * ) h_flag_ = want ; 4276++ fl_k_ ; 4277ms_pool += ms_since ( b ); 4278fl_since_ms_ = fl_flush_ms_ = now_ms (); 4279} 4280return 1 ; 4281} 4282catch (sycl:: exception const & exc ) { 4283std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 4284<< ", line:" << __LINE__ << std:: endl ; 4285std:: exit ( 1 ); 4286} 4287 4288bool Verifier :: done (std:: string & err ) try { 4289if (! fl_active_ || fl_k_ < fl_total_ ) return false; 4290const OnDevice on_device ( device_ ); 4291dpct:: err0 q ; 4292try { 4293q = (dpct:: err0 ) dpct:: sycl_event_query ( ev_done_ ); 4294} catch (std:: exception const & e ) { 4295// a dead or foreign event used to read as the bare word "error" 4296err = std:: string ( "verify: the window's completion event could not be queried on device " ) + 4297std:: to_string ( device_ ) + ": " + e . what (); 4298return false; 4299} 4300 4301/* 4302DPCT1009: SYCL reports errors using exceptions and does not use error 4303codes. Please replace the "get_error_string_dummy(...)" with a real 4304error-handling function. 4305*/ 4306/* 4307DPCT1001: The statement could not be removed. 4308*/ 4309/* 4310DPCT1000: Error handling if-stmt was detected but could not be 4311rewritten. 4312*/ 4313if ( q == 1 ) { 4314// SYCL's "not complete" is CUDA's cudaErrorNotReady: the window is still running, which is not an error. 4315// The DPCT migration dropped that branch, so the first poll of every pipelined window failed with 4316// "verify: error" and --pipeline-windows never ran on this backend. Same body as the CUDA original. 4317const double now = now_ms (); 4318if ( now - fl_flush_ms_ > 2.0 ) { 4319fl_flush_ms_ = now ; 4320( void ) DPCT_CHECK_ERROR ( cs_ -> ext_oneapi_empty ()); 4321} 4322if ( now - fl_since_ms_ > 20000.0 ) // every layer served, and the graph still runs: #267 as above 4323err = "verify: the window never finished" + released_note ( release_gpu_waits ( 5000 )); 4324return false; 4325} 4326if ( q != 0 ) { 4327err = std:: string ( "verify: " ) + dpct:: get_error_string_dummy ( q ); 4328return false; 4329} 4330if ( copy_used_ ) { // no host function of this window may raise flag B in the next one 4331if ((( copy_ ) -> ext_oneapi_empty () ? 0 : 1 ) == 1 ) return false; 4332copy_used_ = false; 4333} 4334return true; 4335} 4336catch (sycl:: exception const & exc ) { 4337std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 4338<< ", line:" << __LINE__ << std:: endl ; 4339std:: exit ( 1 ); 4340} 4341 4342bool Verifier :: pl_finish ( int32_t * out , std:: string & err ) try { 4343using namespace strata:: kernels ; 4344const OnDevice on_device ( device_ ); 4345const ModelGeometry & g = * g_ ; 4346fl_active_ = false; 4347if ( fl_prof_ ) accumulate_profile ( prof_pin_ ); 4348++ windows ; 4349trace_ev ( "DONE (pipelined)" , -1 , -1 , ( int64_t ) ( now_ms () - fl_launch_ms_ )); 4350if ( le_ < g . n_layers ) return true; // an earlier stage: the hand-off is written 4351const int T = fl_T_ ; 4352const bool sampled = ! sampling_ . greedy && sampling_ . temperature > 0.0f ; 4353if ( head_sampling_ && ( sampled || hist_d_ != nullptr )) { // run()'s host-side sampling, Philox(seed, pos0 + t) 4354SamplerParams sp = sampling_ ; 4355sp . counter = ( uint64_t ) last_pos0_ ; 4356sample_tokens ( head_logits_ , T , ( int ) n_vocab_ , hist_d_ , hist_len_ , sp , m_out_ , cs_ ); 4357if ( DPCT_CHECK_ERROR ( cs_ -> wait ()) != 0 ) { 4358err = "verify: the head sampling failed" ; 4359return false; 4360} 4361} 4362if ( out != nullptr ) 4363for ( int t = 0 ; t < T ; ++ t ) out [ t ] = ((volatile int32_t * ) h_out_ )[ t ]; 4364progress_beat (); 4365return true; 4366} 4367catch (sycl:: exception const & exc ) { 4368std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 4369<< ", line:" << __LINE__ << std:: endl ; 4370std:: exit ( 1 ); 4371} 4372 4373bool Verifier :: pl_commit_async ( int n_keep , std:: string & err ) try { 4374const OnDevice on_device ( device_ ); 4375if ( n_keep < 1 || n_keep > last_t_ ) { err = "verify: commit count out of range" ; return false; } 4376// Debug: with a state dump requested, print what this commit is launched with, so a wrong count names 4377// itself next to the verdict log (STRATA_PIPELINE_LOG). 4378static const bool cdbg = std:: getenv ( "STRATA_PIPELINE_DUMP" ) != nullptr ; 4379if ( cdbg ) 4380std:: fprintf ( stderr , "strata commit: n_keep=%d T=%d pos0=%lld self_skip=%d\n" , n_keep , ( int ) last_t_ , 4381( long long ) last_pos0_ , ( last_t_ == 1 && one_token_self_commit ()) ? 1 : 0 ); 4382if ( commit_exec_ == nullptr || ev_commit_ == nullptr ) { err = "verify: pipelined commit not prepared" ; return false; } 4383const Clock :: time_point t0 = Clock :: now (); 4384if ( commit_live_ ) { // its graph reads the words below when it starts: the previous one has (a window ago) 4385dpct:: err0 q ; 4386while (( q = dpct:: sycl_event_query ( ev_commit_ )) == 1 ) _mm_pause (); 4387/* 4388DPCT1009: SYCL reports errors using exceptions and does not use 4389error codes. Please replace the "get_error_string_dummy(...)" with a 4390real error-handling function. 4391*/ 4392/* 4393DPCT1001: The statement could not be removed. 4394*/ 4395/* 4396DPCT1000: Error handling if-stmt was detected but could not be 4397rewritten. 4398*/ 4399if ( q != 0 ) { 4400err = 4401std:: string ( "verify: commit: " ) + dpct:: get_error_string_dummy ( q ); 4402return false; 4403} 4404} 4405// A one-token window advanced the GDN state itself (record_window), so the serial path's commit() skips the 4406// commit graph for it. The pipelined path ran the graph anyway and advanced the state twice per 4407// single-token window; the first decode window is always one token, so the two paths' GDN states were 4408// equal after the prompt and different after that window (STRATA_PIPELINE_DUMP), and the tokens diverged 4409// at the fourth. With this skip the pipelined windows are token-identical to the serial path. 4410if ( last_t_ == 1 && one_token_self_commit () && ! self_commit_off_ ) { 4411h_commit_ [ 0 ] = n_keep ; 4412h_commit_ [ 1 ] = n_keep - 1 ; 4413for ( int t = 0 ; t < max_t_ ; ++ t ) h_commit_ [ 2 + t ] = t < n_keep ? ( int32_t ) ( last_pos0_ + t ) : -1 ; 4414if ( ple_stage ()) 4415for ( int t = 0 ; t < n_keep ; ++ t ) { 4416ss_ -> ple_prev [ 0 ] = ss_ -> ple_prev [ 1 ]; 4417ss_ -> ple_prev [ 1 ] = last_tokens_ [ t ]; 4418} 4419ms_commit += ms_since ( t0 ); 4420return true; 4421} 4422h_commit_ [ 0 ] = n_keep ; 4423h_commit_ [ 1 ] = n_keep - 1 ; 4424for ( int t = 0 ; t < max_t_ ; ++ t ) h_commit_ [ 2 + t ] = t < n_keep ? ( int32_t ) ( last_pos0_ + t ) : -1 ; 4425std:: atomic_thread_fence (std:: memory_order_seq_cst ); 4426const dpct:: err0 le = 4427DPCT_CHECK_ERROR (( cs_ ) -> ext_oneapi_graph ( * commit_exec_ )); 4428/* 4429DPCT1009: SYCL reports errors using exceptions and does not use error 4430codes. Please replace the "get_error_string_dummy(...)" with a real 4431error-handling function. 4432*/ 4433/* 4434DPCT1001: The statement could not be removed. 4435*/ 4436/* 4437DPCT1000: Error handling if-stmt was detected but could not be 4438rewritten. 4439*/ 4440if ( le != 0 ) { 4441err = std:: string ( "verify: commit launch: " ) + 4442dpct:: get_error_string_dummy ( le ); 4443return false; 4444} 4445/* 4446DPCT1024: The original code returned the error code that was further 4447consumed by the program logic. This original code was replaced with 0. You 4448may need to rewrite the program logic consuming the error code. 4449*/ 4450if ( DPCT_CHECK_ERROR (dpct:: sync_barrier ( ev_commit_ , cs_ )) != 0 ) { 4451err = "verify: event record failed" ; return false; 4452} 4453( void ) DPCT_CHECK_ERROR ((( cs_ ) -> ext_oneapi_empty ())); 4454commit_live_ = true; 4455if ( ple_stage ()) 4456for ( int t = 0 ; t < n_keep ; ++ t ) { 4457ss_ -> ple_prev [ 0 ] = ss_ -> ple_prev [ 1 ]; 4458ss_ -> ple_prev [ 1 ] = last_tokens_ [ t ]; 4459} 4460ms_commit += ms_since ( t0 ); 4461return true; 4462} 4463catch (sycl:: exception const & exc ) { 4464std:: cerr << exc . what () << "Exception caught at file:" << __FILE__ 4465<< ", line:" << __LINE__ << std:: endl ; 4466std:: exit ( 1 ); 4467} 4468 4469void Verifier :: absorb_stats ( Verifier & o ) { 4470ms_wait += o . ms_wait ; ms_pool += o . ms_pool ; ms_host += o . ms_host ; ms_commit += o . ms_commit ; 4471windows += o . windows ; 4472o . ms_wait = o . ms_pool = o . ms_host = o . ms_commit = 0 ; 4473o . windows = 0 ; 4474for ( int k = 0 ; k < 2 ; ++ k ) 4475for ( int i = 0 ; i < kProfPer ; ++ i ) { prof_sum_ [ k ][ i ] += o . prof_sum_ [ k ][ i ]; o . prof_sum_ [ k ][ i ] = 0 ; } 4476prof_windows_ += o . prof_windows_ ; 4477o . prof_windows_ = 0 ; 4478} 4479 4480void Verifier :: set_expert_usage_counter (std:: vector < float >* usage ) { 4481if (! expert_usage_counts_d_ || ! usage || usage -> size () != expert_usage_counts_h_ . size ()) 4482throw std:: invalid_argument ( "mirror adaptive expert usage shape mismatch" ); 4483expert_usage_counter_ = usage ; 4484} 4485 4486} // namespace strata::core