okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a8a51b280
main
1#include "b60_mtp_q8_cache.hpp" 2#include "b60_weight_cache.hpp" 3#include "strata/core/on_device.hpp" 4#include "b60_layout_state.hpp" 5#include "private_mtp_demand.hpp" 6// src/core/mtp.cpp - see include/strata/core/mtp.hpp. 7#define DPCT_PROFILING_ENABLED 8#include <sycl/sycl.hpp> 9#include <dpct/dpct.hpp> 10#include "strata/sycl_queue.hpp" 11#include "strata/core/mtp.hpp" 12#include "strata/core/coupled_draft.hpp" 13#include "strata/core/on_device.hpp" 14 15#include "strata/core/native_head.hpp" 16#include "strata/workload_trace.hpp" 17#include "strata/core/peer_experts.hpp" 18#include "strata/platform/memory.hpp" 19#include "strata/kernels/bf16_gemv.hpp" 20#include "strata/kernels/cpu/expert.hpp" 21#include "strata/kernels/elementwise.hpp" 22#include "strata/kernels/fused_gr.hpp" 23#include "strata/kernels/gr.hpp" 24#include "strata/kernels/kv_q4.hpp" 25#include "strata/kernels/kv_q8.hpp" 26#include "strata/kernels/native_moe.hpp" 27#include "strata/kernels/native_mmvq.hpp" 28#include "strata/kernels/native_qsa.hpp" 29#include "strata/kernels/native_rope.hpp" 30#include "strata/kernels/native_router.hpp" 31#include "strata/kernels/qsa.hpp" 32#include "strata/kernels/qsa_decode_attn.hpp" 33#include "strata/kernels/quantize_act.hpp" 34#include "strata/kernels/rope.hpp" 35#include "strata/kernels/router_top10.hpp" 36#include "strata/kernels/s2_expert_grouped.hpp" 37#include "strata/kernels/sampler.hpp" 38#include "strata/kernels/shared_expert.hpp" 39#include "strata/kernels/verify_kernels.hpp" 40#include "strata/kernels/ngram.hpp" 41 42#include <algorithm> 43#include <atomic> 44#include <chrono> 45#include <cstdio> 46#include <cstdlib> 47#include <cstring> 48#include <exception> 49#include <fstream> 50#include <sstream> 51#include <vector> 52#if defined(_WIN32 ) 53#include <intrin.h> 54#elif defined(__x86_64__ ) 55#include <immintrin.h> 56#endif 57 58// --mtp-q4: the head rows' and projections' formats, dequantized and requantized at load: with the Strata quant layer (STRATA_OWN_CPU_QUANT) or, as 59// before, with ggml-base 60#if defined(STRATA_OWN_CPU_QUANT ) 61#include "strata/quant/act.hpp" 62#include "strata/quant/dequant.hpp" 63#define STRATA_MTP_Q4 1 64#elif defined(STRATA_NATIVE_EXPERTS ) 65#include "ggml.h" 66#define STRATA_MTP_Q4 1 67#endif 68 69#ifdef STRATA_MTP_Q4 70namespace { 71#if defined(STRATA_OWN_CPU_QUANT ) 72bool mtp_to_float (int type ,const void * src ,float * dst ,int64_t n ) { 73return strata::quant::dequant_row ((strata::quant::Type )type ,src ,dst ,n ); 74} 75void mtp_quant_q4_0 (const float * x ,void * dst ,int64_t n ) { strata::quant::quantize_q4_0_ref (x ,dst ,n ); } 76#else 77bool mtp_to_float (int type ,const void * src ,float * dst ,int64_t n ) { 78const auto * t = ggml_get_type_traits ((ggml_type )type ); 79if (t == nullptr || t -> to_float == nullptr )return false; 80t -> to_float (src ,dst ,n ); 81return true; 82} 83void mtp_quant_q4_0 (const float * x ,void * dst ,int64_t n ) {ggml_quantize_chunk (GGML_TYPE_Q4_0 ,x ,dst ,0 ,1 ,n ,nullptr ); } 84#endif 85}// namespace 86#endif 87 88namespace strata::core { 89namespace { 90 91constexpr float EPS = 1e-6f ; 92 93// #783 PR-i: STRATA_MTP_CATCHUP_ALL=1 catches the drafter's K/V up for the whole verified window, rejected rows included 94bool mtp_catchup_all () { 95static const bool on = [] { 96const char * v = std::getenv ("STRATA_MTP_CATCHUP_ALL" ); 97return v != nullptr && v [0 ]!= '\0' && v [0 ]!= '0' ; 98 }(); 99return on ; 100} 101constexpr int GGML_Q8_0 = 8 ; 102constexpr int GGML_Q4_0 = 2 ; 103using Clock = std::chrono::steady_clock ; 104double ms_since (Clock ::time_point t ) {return std::chrono::duration < double , std::milli > (Clock ::now ()- t ).count (); } 105 106struct Bump { 107uint8_t * base = nullptr ; 108uint64_t used = 0 ; 109template < typename T > T * take (uint64_t n ) { 110T * p = base ? (T * ) (base + used ) :nullptr ; 111used += (n * sizeof (T )+ 255 )& ~255ull ; 112return p ; 113 } 114}; 115 116bool mapped (size_t bytes ,void ** h ,void ** d )try { 117/* 118DPCT1048: The original value cudaHostAllocMapped is not meaningful in the 119migrated code and was removed or replaced with 0. You may need to check the 120migrated code. 121*/ 122if (DPCT_CHECK_ERROR (* h = strata::host_malloc_polled ( 123bytes , dpct::get_in_order_queue ()))!= 1240 || * h == nullptr )return false;// the host polls what the draft steps write: uncached host memory (sycl_queue.hpp) 125 std::memset (* h ,0 ,bytes ); 126return DPCT_CHECK_ERROR (* d = (void * )* h )== 0 ; 127} 128catch (sycl::exception const & exc ) { 129 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 130 <<", line:" <<__LINE__ << std::endl ; 131 std::exit (1 ); 132} 133 134strata::kernels::QsaShapes shapes_of (const ModelGeometry & g ) {return qsa_shapes (g ); } 135 136// 64-bit seek/tell on a `FILE*`: `fseek`/`ftell` take a 32-bit `long` on Windows and would wrap past 2 GiB. 137#if defined(_WIN32 ) 138#define STRATA_FILE_SEEK64 (f ,o ,w ) _fseeki64((f), (long long) (o), (w)) 139#define STRATA_FILE_TELL64 (f ) _ftelli64(f) 140#else 141#define STRATA_FILE_SEEK64 (f ,o ,w ) fseeko((f), (off_t) (o), (w)) 142#define STRATA_FILE_TELL64 (f ) ftello(f) 143#endif 144 145bool read_file (const std::string & path , std::vector < uint8_t >& out ) { 146// Loader fix (0.1.15+loaderfix.2): `ifstream::read` reaches the disk as 4095-byte reads on MSVC - the same 147// split `load_experts_ranges` had - so the drafter's 111 MiB dense blob paid 4 KiB per operation on a cold 148// start. `fread` passes a request bigger than the stream buffer straight to `ReadFile()`. 149FILE * f = std::fopen (path .c_str (),"rb" ); 150if (f == nullptr )return false; 151// A `FILE*` has no destructor and the short-read path below returns early: the guard closes on every path. 152struct Closer { 153FILE * f ; 154 ~Closer () {if (f != nullptr ) std::fclose (f ); } 155 }closer {f }; 156if (STRATA_FILE_SEEK64 (f ,0 ,SEEK_END )!= 0 )return false; 157const long long n = (long long )STRATA_FILE_TELL64 (f ); 158if (n < 0 || STRATA_FILE_SEEK64 (f ,0 ,SEEK_SET )!= 0 )return false; 159#if !defined(_WIN32 ) 160 strata::platform::advise_willneed (fileno (f ),0 , (uint64_t )n ); 161#endif 162out .resize ((size_t )n ); 163return n == 0 || std::fread (out .data (),1 , (size_t )n ,f )== (size_t )n ; 164} 165 166}// namespace 167 168MtpDrafter ::~MtpDrafter () { 169if (cs_ )cs_ -> wait (); 170for (auto & e :prefill_exec_ )if (e )delete (e ); 171for (auto & e :prefill_dev_exec_ )if (e )delete (e ); 172if (pf_dev_ ) sycl::free (pf_dev_ , dpct::get_in_order_queue ()); 173if (dense4_ ) sycl::free (dense4_ , dpct::get_in_order_queue ()); 174for (auto & e :round_exec_ )if (e )delete (e ); 175for (auto & e :step_exec_ )if (e )delete (e ); 176for (auto & e :round_exec_c_ )if (e )delete (e ); 177for (auto & e :step_exec_c_ )if (e )delete (e ); 178if (cparams_ ) sycl::free (cparams_ , dpct::get_in_order_queue ()); 179if (cring_ ) sycl::free (cring_ , dpct::get_in_order_queue ()); 180if (dinv_ ) sycl::free (dinv_ , dpct::get_in_order_queue ()); 181if (cscratch_ ) sycl::free (cscratch_ , dpct::get_in_order_queue ()); 182if (h_cparams_ ) sycl::free (h_cparams_ , dpct::get_in_order_queue ()); 183if (h_chist_ ) sycl::free (h_chist_ , dpct::get_in_order_queue ()); 184if (cs_ ) dpct::get_current_device ().destroy_queue (cs_ ); 185if (side_ ) dpct::get_current_device ().destroy_queue (side_ ); 186if (sh_fork_ ) dpct::destroy_event (sh_fork_ ); 187if (sh_join_ ) dpct::destroy_event (sh_join_ ); 188if (owns_weights_ && dense_ ){ 189const strata::core::OnDevice on (device_ ); 190for (const auto & t :tensors_ )if (strata::kernels::b60_has_mtp_q8_cache (dense_ + t .off )) 191 strata::kernels::b60_release_mtp_q8_cache (dense_ + t .off ,device_ ,& dpct::get_in_order_queue ()); 192 } 193if (owns_weights_ && dense_ ) sycl::free (dense_ , dpct::get_in_order_queue ()); 194if (owns_weights_ && experts_ ) 195 sycl::free (experts_ , dpct::get_in_order_queue ()); 196if (state_arena_ ) sycl::free (state_arena_ , dpct::get_in_order_queue ()); 197if (arena_ ) sycl::free (arena_ , dpct::get_in_order_queue ()); 198if (head_logits_ ) sycl::free (head_logits_ , dpct::get_in_order_queue ()); 199if (owns_draft_head_ && dhead_ ) { 200if (strata::kernels::b60_cached_weight (dhead_ ,24 )){ 201const strata::core::OnDevice on (device_ ); 202 strata::kernels::b60_release_weight_cache (dhead_ ,24 ,device_ ,& dpct::get_in_order_queue ()); 203 } 204 205 strata::kernels::native_q6_k_unpack (dhead_ ); 206 sycl::free (dhead_ , dpct::get_in_order_queue ()); 207 } 208if (owns_draft_head_ && dvocab_ ) 209 sycl::free (dvocab_ , dpct::get_in_order_queue ()); 210if (ev_chain_ ) dpct::destroy_event (ev_chain_ ); 211for (dpct::event_ptr e :ev_step_ )if (e ) dpct::destroy_event (e ); 212void * hosts []= {h_tok_ ,h_step_ ,h_pos_ ,h_row_ ,h_out_ ,h_prob_ ,h_force_ }; 213for (void * h :hosts )if (h ) strata::host_free_polled (h , dpct::get_in_order_queue ()); 214} 215 216const float * MtpDrafter ::f32 (const char * name )const { 217for (const auto & t :tensors_ )if (t .name == name && t .kind == "f32" )return (const float * ) (dense_ + t .off ); 218return nullptr ; 219} 220const uint16_t * MtpDrafter ::bf16 (const char * name )const { 221for (const auto & t :tensors_ )if (t .name == name && t .kind == "bf16" )return (const uint16_t * ) (dense_ + t .off ); 222return nullptr ; 223} 224const void * MtpDrafter ::q8 (const char * name )const { 225for (const auto & t :tensors_ )if (t .name == name && t .kind == "q8_0" )return dense_ + t .off ; 226return nullptr ; 227} 228const void * MtpDrafter ::wq (const char * name ,int & type )const { 229if (dense4_ != nullptr ) 230for (const auto & e :q4_off_ ) 231if (e .first == name ) {type = GGML_Q4_0 ;return dense4_ + e .second ; } 232type = GGML_Q8_0 ; 233return q8 (name ); 234} 235 236// --mtp-q4: every Q8_0 tensor of dense.bin as Q4_0 (ggml's reference quantizer), in one device buffer 237bool MtpDrafter ::make_q4_dense (const std::vector < uint8_t >& blob , std::string & err ) { 238#ifdef STRATA_MTP_Q4 239uint64_t total = 0 ; 240 std::vector < std::pair < const Tensor * ,uint64_t >> plan ; 241for (const auto & t :tensors_ ) { 242if (t .kind != "q8_0" || t .cols %32 != 0 )continue ; 243plan .push_back ({& t ,total }); 244total += ((uint64_t )t .rows * (uint64_t ) (t .cols /32 )* 18 + 255 )& ~255ull ; 245 } 246 std::vector < uint8_t > host ((size_t )total ); 247 std::vector < float > row ; 248for (const auto & [t ,off ] :plan ) { 249row .resize ((size_t )t -> cols ); 250const uint64_t in_row = (uint64_t ) (t -> cols /32 )* 34 ,out_row = (uint64_t ) (t -> cols /32 )* 18 ; 251for (int64_t r = 0 ;r < t -> rows ;++ r ) { 252if (!mtp_to_float (GGML_Q8_0 ,blob .data ()+ t -> off + (uint64_t )r * in_row ,row .data (),t -> cols )) {err = "mtp: --mtp-q4 cannot read a Q8_0 projection" ;return false; } 253mtp_quant_q4_0 (row .data (),host .data ()+ off + (uint64_t )r * out_row ,t -> cols ); 254 } 255q4_off_ .push_back ({t -> name ,off }); 256 } 257dense4_ = (uint8_t * ) strata::malloc_device_guarded ((size_t )total , dpct::get_in_order_queue ());// SYCL port: cudaMalloc/cudaMemcpy 258if (dense4_ == nullptr ) {err = "mtp: the Q4_0 projections do not fit" ;return false; } 259 dpct::get_in_order_queue ().memcpy (dense4_ ,host .data (), (size_t )total ).wait (); 260vram_ += total ; 261 std::fprintf (stderr ,"strata mtp: --mtp-q4: %zu projections as Q4_0 (%.1f MiB)\n" ,plan .size (), (double )total /1048576.0 ); 262return true; 263#else 264 (void )blob ; 265err = "mtp: --mtp-q4 needs a build with native experts (ggml)" ; 266return false; 267#endif 268} 269 270// --mtp-q4: the draft head's subset rows as Q4_0 (dequantized from the main head's format) 271bool MtpDrafter ::make_q4_head (std::string & err ) { 272#ifdef STRATA_MTP_Q4 273const int64_t N = g_ -> n_embd ; 274if (N %32 != 0 ) {err = "mtp: --mtp-q4 cannot read the head's format" ;return false; } 275// SYCL port: with STRATA_Q6_PLANAR the head is stored as planes, and the subset this builds from is row-major 276// only when the head is packed - the gather at load time then copies planes as if they were rows. The result is 277// a draft head that proposes nothing at all (measured: 0 drafts, decode 73.8 -> 35.3 tok/s) with no error, so 278// refuse instead of running wrong in silence. 279if (head_ -> type ()== 14 && strata::kernels::native_q6_k_is_planar (head_ -> weights ())) { 280err = "mtp: --mtp-q4 head needs the packed Q6_K head layout (STRATA_Q6_PLANAR=0)" ; 281return false; 282 } 283const size_t in_row = head_ -> row_bytes (),out_row = (size_t ) (N /32 )* 18 ; 284 std::vector < uint8_t > src ((size_t )n_dvocab_ * in_row ),dst ((size_t )n_dvocab_ * out_row ); 285try { dpct::get_in_order_queue ().memcpy (src .data (),dhead_ ,src .size ()).wait (); }// SYCL port: cudaMemcpy 286catch (sycl::exception const & ) {err = "mtp: reading the draft head" ;return false; } 287 std::vector < float > row ((size_t )N ); 288for (int64_t r = 0 ;r < n_dvocab_ ;++ r ) { 289if (!mtp_to_float (head_ -> type (),src .data ()+ (size_t )r * in_row ,row .data (),N )) {err = "mtp: --mtp-q4 cannot read the head's format" ;return false; } 290mtp_quant_q4_0 (row .data (),dst .data ()+ (size_t )r * out_row ,N ); 291 } 292// the Q4_0 rows replace the subset in place (they are smaller) 293try { dpct::get_in_order_queue ().memcpy (dhead_ ,dst .data (),dst .size ()).wait (); } 294catch (sycl::exception const & ) {err = "mtp: writing the draft head" ;return false; } 295dhead_type_ = GGML_Q4_0 ; 296 std::fprintf (stderr ,"strata mtp: --mtp-q4: draft head over %lld tokens as Q4_0 (%.1f MiB read per step, was %.1f)\n" , 297 (long long )n_dvocab_ , (double )dst .size () /1048576.0 , (double )src .size () /1048576.0 ); 298return true; 299#else 300err = "mtp: --mtp-q4 needs a build with native experts (ggml)" ; 301return false; 302#endif 303} 304 305bool MtpDrafter ::load (const std::string & rt_dir ,const ModelGeometry & g , 306SessionState & ss ,int max_t , std::string & err , 307int64_t window ,const MtpDrafter * shared )try { 308device_ = 309 dpct::get_current_device_id ();// a layer split's last stage on another 310// GPU: the drafter lives there 311g_ = & g ; 312ss_ = & ss ; 313if (ple_ss_ == nullptr )ple_ss_ = & ss ; 314max_t_ = max_t ; 315rt_dir_ = rt_dir ; 316if (max_t < 1 || max_t > strata::kernels::kVerifyMaxT ) {err = "mtp: max_t out of range" ;return false; } 317if (shared != nullptr ) { 318if (shared -> device_ != device_ || shared -> g_ != & g || shared -> dense_ == nullptr || 319shared -> experts_ == nullptr || shared -> rt_dir_ != rt_dir ) { 320err = "mtp: incompatible shared weights" ; 321return false; 322 } 323dense_ = shared -> dense_ ; 324experts_ = shared -> experts_ ; 325tensors_ = shared -> tensors_ ; 326owns_weights_ = false; 327owns_draft_head_ = false; 328 } 329// Loader fix (0.1.15+loaderfix.2): the two reads below are the whole “drafter files” cost; reporting 330// them apart from the rest of the stage is what makes the next regression visible. 331const auto t_files = std::chrono::steady_clock::now (); 332// ---- the index and the dense weights 333if (shared == nullptr ) { 334 std::ifstream idx (rt_dir + "/dense.txt" ); 335if (!idx ) {err = "mtp: cannot open " + rt_dir + "/dense.txt (run tools/mtp_rt.py)" ;return false; } 336 std::string line ; 337while (std::getline (idx ,line )) { 338if (line .empty ())continue ; 339 std::istringstream is (line ); 340Tensor t ; 341is >>t .name >>t .kind >>t .rows >>t .cols >>t .off >>t .bytes ; 342if (!is ) {err = "mtp: malformed dense.txt line: " + line ;return false; } 343tensors_ .push_back (t ); 344 } 345 std::vector < uint8_t > blob ; 346if (!read_file (rt_dir + "/dense.bin" ,blob )) {err = "mtp: cannot read dense.bin" ;return false; } 347const dpct::err0 alloc = 348DPCT_CHECK_ERROR (dense_ = (uint8_t * )strata::malloc_device_guarded ( 349blob .size (), dpct::get_in_order_queue ())); 350/* 351DPCT1000: Error handling if-stmt was detected but could not be 352rewritten. 353*/ 354if (alloc != 0 ) { 355size_t free_bytes = 0 ,total_bytes = 0 ; 356/* 357DPCT1106: 'cudaMemGetInfo' was migrated with the Intel 358extensions for device information which may not be supported by all 359compilers or runtimes. You may need to adjust the code. 360*/ 361const dpct::err0 info = 362DPCT_CHECK_ERROR (dpct::get_current_device ().get_memory_info ( 363free_bytes ,total_bytes )); 364/* 365DPCT1009: SYCL reports errors using exceptions and does not use 366error codes. Please replace the "get_error_string_dummy(...)" with a 367real error-handling function. 368*/ 369/* 370DPCT1001: The statement could not be removed. 371*/ 372err = "mtp: dense weights allocation failed (" + 373 std::string (dpct::get_error_string_dummy (alloc ))+ 374"), requested " + std::to_string (blob .size () >>20 )+ 375" MiB, CUDA0 free " + 376 (info == 0 ? std::to_string (free_bytes >>20 )+ " MiB" 377 :"unknown" ); 378return false; 379 } 380 dpct::get_in_order_queue ().memcpy (dense_ ,blob .data (),blob .size ()).wait (); 381vram_ += blob .size (); 382if (q4_ && !make_q4_dense (blob ,err ))return false; 383 } 384// ---- the 512 routed experts, one blob each 385if (shared == nullptr ) { 386const uint64_t bytes = (uint64_t )g .n_expert * strata::kernels::cpu::BLOB ; 387// Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under 388// MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes. 389FILE * f = std::fopen ((rt_dir + "/experts.bin" ).c_str (),"rb" ); 390if (f == nullptr ) {err = "mtp: cannot open experts.bin" ;return false; } 391struct Closer { 392FILE * f ; 393 ~Closer () {if (f != nullptr ) std::fclose (f ); } 394 }closer {f }; 395if (DPCT_CHECK_ERROR (experts_ = (uint8_t * )strata::malloc_device_guarded ( 396bytes , dpct::get_in_order_queue ()))!= 0 ) { 397err = "mtp: the 512 experts do not fit in VRAM" ;return false; 398 } 399#if !defined(_WIN32 ) 400 strata::platform::advise_willneed (fileno (f ),0 ,bytes ); 401#endif 402 std::vector < uint8_t > chunk (64u <<20 ); 403for (uint64_t off = 0 ;off < bytes ;) { 404const uint64_t n = std::min < uint64_t > (chunk .size (),bytes - off ); 405if (std::fread (chunk .data (),1 , (size_t )n ,f )!= (size_t )n ) {err = "mtp: experts.bin is truncated" ;return false; } 406 dpct::get_in_order_queue () 407 .memcpy (experts_ + off ,chunk .data (),n ) 408 .wait (); 409off += n ; 410 } 411vram_ += bytes ; 412 } 413const char * required []= {"fc_embedding.weight" ,"fc_hidden.weight" ,"self_attn.q_proj.weight" ,"self_attn.k_proj.weight" , 414"self_attn.v_proj.weight" ,"self_attn.o_proj.weight" ,"mlp.shared_expert.gate_proj.weight" , 415"mlp.shared_expert.up_proj.weight" ,"mlp.shared_expert.down_proj.weight" }; 416for (const char * n :required )if (!q8 (n )) {err = std::string ("mtp: " )+ n + " is missing (q8_0)" ;return false; } 417 418if (owns_weights_ && !q4_ && strata::kernels::b60_mtp_q8_cache_requested ()){ 419size_t cache_bytes = 0 ;int cache_count = 0 ; 420for (const auto & t :tensors_ ){ 421unsigned mask = 0 ;int rows = 0 ,cols = 0 ; 422if (t .name == "fc_embedding.weight" ){mask = 18u ;rows = 2560 ;cols = 2560 ;} 423if (t .name == "fc_hidden.weight" ){mask = 272u ;rows = 2560 ;cols = 2560 ;} 424if (t .name == "mlp.shared_expert.down_proj.weight" ){mask = 2u ;rows = 2560 ;cols = 640 ;} 425if (t .name == "mlp.shared_expert.gate_proj.weight" ){mask = 2u ;rows = 640 ;cols = 2560 ;} 426if (t .name == "mlp.shared_expert.up_proj.weight" ){mask = 2u ;rows = 640 ;cols = 2560 ;} 427if (t .name == "self_attn.k_proj.weight" ){mask = 18u ;rows = 512 ;cols = 2560 ;} 428if (t .name == "self_attn.o_proj.weight" ){mask = 2u ;rows = 2560 ;cols = 6144 ;} 429if (t .name == "self_attn.q_proj.weight" ){mask = 2u ;rows = 12288 ;cols = 2560 ;} 430if (t .name == "self_attn.v_proj.weight" ){mask = 18u ;rows = 512 ;cols = 2560 ;} 431if (!mask )continue ; 432if (t .kind != "q8_0" || t .rows != rows || t .cols != cols || t .bytes != uint64_t (rows )* (cols /32 )* 34 ) 433throw std::runtime_error ("B60 MTP Q8 RT tensor mismatch" ); 434 strata::kernels::b60_make_mtp_q8_cache (dense_ + t .off ,rows ,cols ,mask ,device_ ,& dpct::get_in_order_queue ()); 435cache_bytes += t .bytes + 256 ;++ cache_count ; 436 } 437if (cache_count != 9 || cache_bytes != 72071424 )throw std::runtime_error ("B60 MTP Q8 RT cache count/bytes" ); 438vram_ += cache_bytes ; 439 std::fprintf (stderr ,"B60_MTP_Q8_CACHE device=%d matrices=%d allocation_bytes=%zu\n" ,device_ ,cache_count ,cache_bytes ); 440 } 441 442// ---- the layer's own K/V (dense attention: no indexer state is read) 443const strata::kernels::QsaShapes s = shapes_of (g ); 444const int64_t max_cells = ss .qsa_states [ss .qsa_primary ()].max_cells ; 445// KV streaming: the drafter only reads its last `window` cells, so with streaming on its K/V is a ring of the 446// window (plus the cells a round writes ahead of its queries) over a host copy, refilled on a resume. The host copy 447// is pinned after the expert arena has pinned what it could: if it does not fit, the K/V stays whole in VRAM. 448int64_t ring = (window > 0 && window < max_cells ) ?window + 4 * (int64_t )max_t + 64 :0 ; 449// K8V4 never applies to the drafter: its own attention paths (below, and verify.cpp) handle whole formats 450// only, whatever ring shape it takes (0, a window, or the -1 fully-resident fallback). 451const bool kv_hybrid_was = qsa_kv_hybrid (); 452const bool kv_int8_was = qsa_kv_int8 (); 453qsa_set_kv_hybrid (false); 454if (kv_hybrid_was )qsa_set_kv_int8 (true);// the drafter under --kv k8v4: plain INT8 455uint64_t sb = qsa_state_bytes (g ,max_cells , false,ring ); 456if (DPCT_CHECK_ERROR (state_arena_ = (void * )strata::malloc_device_guarded ( 457sb , dpct::get_in_order_queue ()))!= 0 ) { 458err = "mtp: the K/V state does not fit" ;return false; 459 } 460if (qsa_state_init (g ,max_cells ,state_arena_ ,st_ ,& ss .qsa_states [ss .qsa_primary ()],ring )== 0 ) { 461if (st_ .kv_mode == 0 ) {err = "mtp: state init failed" ;return false; } 462 std::fprintf (stderr ,"strata mtp: no pinned RAM left for the draft layer's K/V copy; keeping it in VRAM\n" ); 463/* 464DPCT1026: The call to cudaGetLastError was removed because this 465functionality is redundant in SYCL. 466*/ 467 sycl::free (state_arena_ , dpct::get_in_order_queue ()); 468st_ = QsaState {}; 469ring = -1 ;// fully resident 470sb = qsa_state_bytes (g ,max_cells , false,ring ); 471if (DPCT_CHECK_ERROR (state_arena_ = (void * )strata::malloc_device_guarded ( 472sb , dpct::get_in_order_queue ()))!= 0 ) { 473err = "mtp: the K/V state does not fit" ;return false; 474 } 475if (qsa_state_init (g ,max_cells ,state_arena_ ,st_ ,& ss .qsa_states [ss .qsa_primary ()],ring )== 0 ) {err = "mtp: state init failed" ;return false; } 476 } 477qsa_set_kv_int8 (kv_int8_was ); 478qsa_set_kv_hybrid (kv_hybrid_was ); 479qsa_state_zero (st_ ,g ,nullptr ); 480 dpct::get_current_device ().queues_wait_and_throw (); 481vram_ += sb ; 482 483// ---- buffers 484window_ = (window > 0 && window < max_cells ) ?window :0 ; 485cap_ = (((window_ > 0 ?window_ :max_cells )+ 63 ) /64 )* 64 ; 486attn_scratch_floats_ = (int64_t ) strata::kernels::qsa_decode_attn_scratch_floats (cap_ ,s ); 487const uint64_t T = (uint64_t )max_t ,N = (uint64_t )g .n_embd ,HC = (uint64_t )g .hc ,K = (uint64_t )ss .k ; 488const uint64_t NH = (uint64_t )g .n_head ,HD = (uint64_t )g .head_dim ,NKV = (uint64_t )g .n_head_kv ; 489const uint64_t R2 = 2 * T ;// step/pos rows: T catch-up rows + up to T-2 chain steps 490bool ok = mapped (T * 4 + 64 , (void ** )& h_tok_ , (void ** )& m_tok_ )&& 491mapped (R2 * 4 * 4 + 64 , (void ** )& h_step_ , (void ** )& m_step_ )&& 492mapped (R2 * NH * 4 + 64 , (void ** )& h_pos_ , (void ** )& m_pos_ )&& 493mapped (64 , (void ** )& h_row_ , (void ** )& m_row_ )&& 494mapped (T * 4 + 64 , (void ** )& h_out_ , (void ** )& m_out_ )&& 495mapped (T * 4 + 64 , (void ** )& h_prob_ , (void ** )& m_prob_ )&& 496 (!force_on_ || mapped (64 , (void ** )& h_force_ , (void ** )& m_force_ )); 497if (!ok ) {err = "mtp: mapped staging failed" ;return false; } 498if (h_force_ != nullptr )for (int j = 0 ;j < 16 ;++ j )h_force_ [j ]= -1 ; 499auto carve = [& ](Bump & b ) { 500tok_ = b .take < int32_t > (T );step_ = b .take < int32_t > (R2 * 4 );pos_ = b .take < int32_t > (R2 * NH );row_ = b .take < int32_t > (4 ); 501ident_ = b .take < int32_t > (T * (uint64_t )cap_ ); 502Rin_ = b .take < float > (T * HC * N );R_ = b .take < float > (T * HC * N ); 503emb_ = b .take < float > (T * N );en_ = b .take < float > (T * N );e2_ = b .take < float > (T * N ); 504hn_ = b .take < float > (T * HC * N );h2_ = b .take < float > (T * HC * N ); 505mixed_ = b .take < float > (T * N );inj_ = b .take < float > (T * HC );inj2_ = b .take < float > (T * HC ); 506lo_ = b .take < float > (T * (uint64_t )g .hc_lr );rs_ = b .take < float > (T * HC );bo_ = b .take < float > (T * N ); 507xn_ = b .take < float > (T * HC * N ); 508xq_ = b .take < uint8_t > (strata::kernels::native_q8_1_bytes ((int ) (NH * HD ),8 )); 509qfull_ = b .take < float > (T * NH * 2 * HD );qcur_ = b .take < float > (T * NH * HD ); 510kcur_ = b .take < float > (T * NKV * HD );vcur_ = b .take < float > (T * NKV * HD ); 511attn_ = b .take < float > (T * NH * HD );attn32_ = b .take < float > (T * NH * HD ); 512attn_scratch_ = b .take < float > ((uint64_t )attn_scratch_floats_ );// the full layer runs one row at a time 513logits_ = b .take < float > (T * (uint64_t )g .n_expert );w_ = b .take < float > (T * K );ids_ = b .take < int32_t > (T * K ); 514shared_ = b .take < float > (T * N );parts_ = b .take < float > (T * K * N );y_ = b .take < float > (T * N ); 515sample_ = b .take < float > (T * N ); 516hit_slot_ = b .take < int32_t > (T * K );hit_dst_ = b .take < int32_t > (T * K );hit_count_ = b .take < int32_t > (4 ); 517grp_ptr_ = b .take < unsigned long long > (T * K );grp_start_ = b .take < int32_t > (T * K + 1 ); 518grp_counts_ = b .take < int32_t > (4 ); 519hit_xq_ = b .take < uint8_t > (T * (N /32 )* 34 );hit_xs_ = b .take < float > (T * (N /32 )); 520hit_scratch_ = b .take < uint8_t > (strata::kernels::moe_hit_grouped_scratch_bytes ((int64_t ) (T * K ),g .n_embd ,g .n_ff )); 521sh_scratch_ = (float * )b .take < uint8_t > (strata::kernels::shared_expert_scratch_bytes (g .n_ff )); 522x_bf16_ = b .take < uint16_t > (N ); 523out_ids_ = b .take < int32_t > (T + 4 ); 524probs_ = b .take < float > (T + 4 ); 525arg_scratch_ = b .take < uint8_t > (strata::kernels::argmax_rows_scratch_bytes ((int )T )); 526top_scratch_ = b .take < uint8_t > (strata::kernels::row_top_prob_scratch_bytes ((int )T )); 527dummy_inj_ = b .take < float > (HC ); 528 }; 529Bump count ; 530carve (count ); 531if (DPCT_CHECK_ERROR (arena_ = (void * )strata::malloc_device_guarded ( 532count .used , dpct::get_in_order_queue ()))!= 0 ) { 533err = "mtp: buffers do not fit" ;return false; 534 } 535 strata::big_fill_zero (dpct::get_in_order_queue (),arena_ ,count .used ); 536Bump real ; 537real .base = (uint8_t * )arena_ ; 538carve (real ); 539vram_ += count .used ; 540 { 541 std::vector < int32_t > id ((size_t ) (T * (uint64_t )cap_ )); 542for (uint64_t t = 0 ;t < T ;++ t ) 543for (int64_t i = 0 ;i < cap_ ;++ i )id [(size_t ) (t * (uint64_t )cap_ + (uint64_t )i )]= (int32_t )i ; 544/* 545DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 546assuming in the original code the source host memory is pageable memory. 547If the memory is not pageable, call wait() on event return by memcpy API 548to ensure synchronization behavior. 549*/ 550 dpct::get_in_order_queue ().memcpy (ident_ ,id .data (),id .size ()* 4 ).wait (); 551 } 552// --pipeline-windows 2 (the forcing graphs): the chain shares its card with stage 1's windows and the next launch 553// on stage 0 waits for it, so its stream gets the highest priority there (STRATA_MTP_PRIORITY=0: the default) 554bool prio = false; 555#if !defined(STRATA_USE_HIP )// (HIP: the default priority) 556static const bool hi_prio = [] {const char * v = std::getenv ("STRATA_MTP_PRIORITY" );return v == nullptr || std::atoi (v )!= 0 ; }(); 557int prio_lo = 0 ,prio_hi = 0 ; 558/* 559DPCT1027: The call to cudaDeviceGetStreamPriorityRange was replaced with 5600 because SYCL currently does not support get queue priority range. 561*/ 562if (force_on_ && hi_prio && 0 == 0 ) 563/* 564DPCT1025: The SYCL queue is created ignoring the flag and priority 565options. 566*/ 567prio = DPCT_CHECK_ERROR ( 568cs_ = dpct::get_current_device ().create_queue (true))== 0 ; 569/* 570DPCT1026: The call to cudaGetLastError was removed because this 571functionality is redundant in SYCL. 572*/ 573#endif 574/* 575DPCT1025: The SYCL queue is created ignoring the flag and priority 576options. 577*/ 578if (!prio && DPCT_CHECK_ERROR (cs_ = dpct::get_current_device ().create_queue ( 579 true))!= 0 ) { 580err = "mtp: stream" ;return false; 581 } 582/* 583DPCT1025: The SYCL queue is created ignoring the flag and priority 584options. 585*/ 586if (DPCT_CHECK_ERROR ( 587side_ = dpct::get_current_device ().create_queue (true))!= 0 || 588DPCT_CHECK_ERROR (sh_fork_ = new sycl::event ())!= 0 || 589DPCT_CHECK_ERROR (sh_join_ = new sycl::event ())!= 0 ) { 590err = "mtp: streams" ; 591return false; 592 } 593const double files_s = std::chrono::duration < double > (std::chrono::steady_clock::now ()- t_files ).count (); 594if (shared != nullptr ) { 595 std::fprintf (stderr ,"strata mtp: shared draft weights, %.0f MiB of private state and buffers\n" , 596 (double )vram_ /1048576.0 ); 597 }else { 598 std::fprintf (stderr ,"strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n" , 599 (double )vram_ /1048576.0 , (double )g .n_expert * strata::kernels::cpu::BLOB /1048576.0 , 600 (double )tensors_ .back ().off /1048576.0 ,files_s , 601files_s > 0 ? ((double )g .n_expert * strata::kernels::cpu::BLOB + (double )tensors_ .back ().off ) / 6021048576.0 /files_s :0.0 ); 603 } 604return true; 605} 606catch (sycl::exception const & exc ) { 607 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 608 <<", line:" <<__LINE__ << std::endl ; 609 std::exit (1 ); 610} 611 612namespace { 613// STRATA_MTP_FULL_HEAD=1 (a diagnostic): draft over the whole vocabulary (the main head itself) instead of 614// rt/draft_vocab.bin's subset - the reference head, to measure what the subset costs in acceptance 615bool full_head_env () { 616static const bool on = [] {const char * v = std::getenv ("STRATA_MTP_FULL_HEAD" );return v && v [0 ]== '1' ; }(); 617return on ; 618} 619}// namespace 620 621bool MtpDrafter ::top2_env () { 622static const bool on = [] {const char * v = std::getenv ("STRATA_MTP_TOP2" );return v && v [0 ]== '1' ; }(); 623return on ; 624} 625 626// STRATA_MTP_TOP2=1 (a diagnostic for tree drafts): draft j's runner-up under the draft layer, from the head logits 627// the step just wrote (row 0), on the host. Slow; only for measuring what a second branch would have caught. 628void MtpDrafter ::record_top2 (int j )try { 629const int64_t nv = dhead_ != nullptr ?n_dvocab_ :n_vocab_ ; 630if ((int64_t )lg_host_ .size ()< nv )lg_host_ .resize ((size_t )nv ); 631if ((int )top2_ .size ()< max_t_ )top2_ .assign ((size_t )max_t_ ,-1 ); 632if (j < 0 || j >=max_t_ )return ; 633if (DPCT_CHECK_ERROR (dpct::get_in_order_queue () 634 .memcpy (lg_host_ .data (),head_logits_ , 635 (size_t )nv * sizeof (float )) 636 .wait ())!= 0 ) { 637top2_ [(size_t )j ]= -1 ; 638return ; 639 } 640int64_t b1 = -1 ,b2 = -1 ; 641for (int64_t i = 0 ;i < nv ;++ i ) { 642const float v = lg_host_ [(size_t )i ]; 643if (b1 < 0 || v > lg_host_ [(size_t )b1 ]) {b2 = b1 ;b1 = i ; } 644else if (b2 < 0 || v > lg_host_ [(size_t )b2 ])b2 = i ; 645 } 646top2_ [(size_t )j ]= b2 < 0 ?-1 :dhead_ != nullptr ?dvocab_host_ [(size_t )b2 ] : (int32_t )b2 ; 647} 648catch (sycl::exception const & exc ) { 649 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 650 <<", line:" <<__LINE__ << std::endl ; 651 std::exit (1 ); 652} 653 654uint64_t MtpDrafter ::bind_bytes (uint64_t head_row_bytes ,int64_t n_vocab )const { 655uint64_t bytes = head_logits_ ?0 : (uint64_t )max_t_ * (uint64_t )n_vocab * sizeof (float ); 656if (dhead_ == nullptr && owns_draft_head_ && !full_head_env ()) { 657if (FILE * f = std::fopen (vocab_file ().c_str (),"rb" )) { 658 std::fseek (f ,0 ,SEEK_END ); 659const long size = std::ftell (f ); 660 std::fclose (f ); 661if (size >=4 && size %4 == 0 ) { 662bytes += (uint64_t ) (size /4 )* head_row_bytes + (uint64_t )size ; 663// Price the independent padded head cache before auto sizes the expert cache. 664if (strata::kernels::b60_single_actor_requested ()&& strata::kernels::b60_cache_requested (24 )&& 665size /4 == 106299 && head_row_bytes == 1360 && !q4_head_ ) 666bytes += uint64_t ((size /4 + 15 ) /16 * 16 )* head_row_bytes + 6672 * strata::kernels::kB60WeightCacheGuard ; 668 } 669 } 670 } 671// coupled draft sampling (STRATA_SPEC_COUPLED=1 only): an upper bound - the id -> subset map, the penalty ring, 672// the split scratch (64 lists of 64 entries at most) and the parameters 673if (coupled_draft_env ()&& cparams_ == nullptr ) 674bytes += (uint64_t )n_vocab * 4 + (uint64_t ) (kCoupledHistCap + max_t_ )* 4 + 64ull * 64ull * 8ull + 4096 ; 675return bytes ; 676} 677 678bool MtpDrafter ::setup_coupled (std::string & err )try { 679const int64_t nv = dhead_ != nullptr ?n_dvocab_ :n_vocab_ ; 680const size_t scratch = strata::kernels::coupled_draft_scratch_bytes ((int )nv ); 681if (scratch == 0 ) { 682 std::fprintf (stderr ,"strata mtp: STRATA_SPEC_COUPLED: %lld draft logits are too wide for the coupled sampler; " 683"argmax drafts\n" , (long long )nv ); 684return true; 685 } 686 sycl::queue & q = dpct::get_in_order_queue (); 687const size_t ring = (size_t ) (kCoupledHistCap + max_t_ )* sizeof (int32_t ); 688cparams_ = sycl::malloc_device < strata::kernels::SamplerParams > (1 ,q ); 689cring_ = (int32_t * ) sycl::malloc_device (ring ,q ); 690cscratch_ = sycl::malloc_device (scratch ,q ); 691if (cparams_ == nullptr || cring_ == nullptr || cscratch_ == nullptr || 692 !mapped (sizeof (strata::kernels::SamplerParams ), (void ** )& h_cparams_ , (void ** )& m_cparams_ )|| 693 !mapped ((size_t )kCoupledHistCap * sizeof (int32_t ), (void ** )& h_chist_ , (void ** )& m_chist_ )) { 694err = "mtp: the coupled draft sampler's buffers do not fit" ; 695return false; 696 } 697q .memset (cring_ ,0xff ,ring ).wait ();// -1: no token 698 std::fill (h_chist_ ,h_chist_ + kCoupledHistCap ,-1 ); 699vram_ += sizeof (strata::kernels::SamplerParams )+ ring + scratch ; 700if (dhead_ != nullptr ) {// token id -> subset index (-1: not in the draft head), for the penalties 701 std::vector < int32_t > sub ((size_t )n_dvocab_ ),inv ((size_t )n_vocab_ ,-1 ); 702q .memcpy (sub .data (),dvocab_ ,sub .size ()* sizeof (int32_t )).wait (); 703for (size_t i = 0 ;i < sub .size ();++ i ) 704if (sub [i ] >=0 && sub [i ]< n_vocab_ && inv [(size_t )sub [i ]]< 0 )inv [(size_t )sub [i ]]= (int32_t )i ; 705dinv_ = (int32_t * ) sycl::malloc_device (inv .size ()* sizeof (int32_t ),q ); 706if (dinv_ == nullptr ) { 707err = "mtp: the coupled draft sampler's token map does not fit" ; 708return false; 709 } 710q .memcpy (dinv_ ,inv .data (),inv .size ()* sizeof (int32_t )).wait (); 711vram_ += inv .size ()* sizeof (int32_t ); 712 } 713if (DPCT_CHECK_ERROR (dpct::get_current_device ().queues_wait_and_throw ())!= 7140 ) { 715/* 716DPCT1009: SYCL reports errors using exceptions and does not use 717error codes. Please replace the "get_error_string_dummy(...)" with a 718real error-handling function. 719*/ 720/* 721DPCT1010: SYCL uses exceptions to report errors and does not use the 722error codes. The cudaGetLastError function call was replaced with 0. You 723need to rewrite this code. 724*/ 725err = std::string ("mtp: coupled setup: " )+ dpct::get_error_string_dummy (0 ); 726return false; 727 } 728coupled_ok_ = true; 729 std::fprintf (stderr ,"strata mtp: coupled draft sampling on (STRATA_SPEC_COUPLED): sampled requests draft with the " 730"target's chain and Philox draw over %lld tokens\n" , (long long )nv ); 731return true; 732}catch (sycl::exception const & e ) { 733err = std::string ("mtp: coupled setup: " )+ e .what (); 734return false; 735} 736 737void MtpDrafter ::set_draft_sampling (const strata::kernels::SamplerParams & sp ) { 738coupled_active_ = coupled_ok_ && !sp .greedy && sp .temperature > 0.0f ; 739if (!coupled_active_ )return ; 740* h_cparams_ = sp ;// read by the next round graph (after the previous one has synced) 741 std::fill (h_chist_ ,h_chist_ + kCoupledHistCap ,-1 ); 742} 743 744void MtpDrafter ::set_draft_history (const int32_t * tail ,int64_t n_tail ,int32_t next ) { 745if (!coupled_active_ )return ; 746const int h = coupled_hist_len (h_cparams_ -> penalty_last_n ,kCoupledHistCap ); 747coupled_hist_base (tail ,n_tail ,next ,h ,h_chist_ + (kCoupledHistCap - h )); 748} 749 750namespace { 751// #474: what to change when the draft head's token subset does not fit the VRAM left - a smaller subset that setup 752// ships (data/draft_vocab_*.bin; their token counts below), and how to pick it. The start used to stop at "the draft 753// head does not fit" with no hint. Text only, after the failure: nothing changes for a start that fits. 754void draft_head_hint (int64_t n_tokens ,int64_t row_bytes ) { 755size_t free_b = 0 ,total_b = 0 ; 756bool have_free = true;// SYCL port: the device's own free-memory figure 757try { dpct::get_current_device ().get_memory_info (free_b ,total_b ); }catch (...) {have_free = false; } 758auto mib = [& ](int64_t n ) {return (double ) (n * row_bytes ) /1048576.0 ; }; 759 std::string free_s ; 760if (have_free ) { 761char b [64 ]; 762 std::snprintf (b ,sizeof (b )," and %.0f MiB is free" , (double )free_b /1048576.0 ); 763free_s = b ; 764 } 765 std::fprintf (stderr ,"strata mtp: the draft head over %lld tokens needs %.0f MiB of VRAM%s.\n" , 766 (long long )n_tokens ,mib (n_tokens ),free_s .c_str ()); 767struct Subset {const char * name ;int64_t tokens ;const char * what ; }; 768static const Subset smaller []= {{"cyrillic" ,58963 ,"English, code and the Cyrillic script" }, 769 {"en" ,40525 ,"English and code" }}; 770 std::string opts ; 771for (const Subset & s :smaller ) 772if (s .tokens < n_tokens ) { 773char b [160 ]; 774 std::snprintf (b ,sizeof (b ),"%s--draft-vocab %s (%s, ~%.0f MiB)" ,opts .empty () ?"" :" or " ,s .name , 775s .what ,mib (s .tokens )); 776opts += b ; 777 } 778if (!opts .empty ()) 779 std::fprintf (stderr ,"strata mtp: hint: a smaller draft vocabulary needs less VRAM: %s. Start once with it - " 780"START-HERE.bat --draft-vocab en (Windows) or ./setup.sh --draft-vocab en - and the model " 781"keeps it (\"draft_vocab\" in its strata-*.json config); or a smaller --context in " 782"setup.\n" , 783opts .c_str ()); 784else 785 std::fprintf (stderr ,"strata mtp: hint: this is already the smallest shipped draft vocabulary: a smaller " 786"--context (or closing what else uses the GPU) leaves it room.\n" ); 787} 788}// namespace 789 790bool MtpDrafter ::bind (const WeightTable & wt ,const NativeHead * head , 791const float * window_R , std::string & err , 792const MtpDrafter * shared )try { 793const OnDevice on_device (device_ ); 794wt_ = & wt ; 795head_ = head ; 796window_R_ = window_R ; 797const WeightRef * wo = wt .find ("output.weight" ); 798if (!wo ) {err = "mtp: output.weight is missing" ;return false; } 799n_vocab_ = wo -> ne1 ; 800if (head == nullptr || !head -> loaded ()) {err = "mtp: the draft layer needs the native head (--native)" ;return false; } 801if (head_logits_ == nullptr && 802DPCT_CHECK_ERROR (head_logits_ = sycl::malloc_device < float > ( 803 (size_t )max_t_ * (size_t )n_vocab_ , 804 dpct::get_in_order_queue ()))!= 0 ) { 805err = "mtp: the draft logits do not fit" ; 806return false; 807 } 808if (shared != nullptr ) { 809if (shared -> head_ != head || shared -> device_ != device_ || 810shared -> n_vocab_ != n_vocab_ ) { 811err = "mtp: incompatible shared draft head" ; 812return false; 813 } 814dhead_ = shared -> dhead_ ; 815dhead_type_ = shared -> dhead_type_ ;// the subset head's type (as src/core/mtp.cpp since #1110): -1 failed every --batch-mtp step 816dvocab_ = shared -> dvocab_ ; 817n_dvocab_ = shared -> n_dvocab_ ; 818owns_draft_head_ = false; 819 } 820// the draft head's token subset, when tools/draft_vocab.py wrote one 821if (dhead_ == nullptr && shared == nullptr && !full_head_env ()) { 822 std::vector < uint8_t > raw ; 823if (read_file (vocab_file (),raw )&& raw .size () >=4 && raw .size () %4 == 0 ) { 824n_dvocab_ = (int64_t ) (raw .size () /4 ); 825const int64_t row_bytes = (int64_t )head -> row_bytes ();// a vocabulary row of the native head 826if (DPCT_CHECK_ERROR (dvocab_ = (int32_t * )sycl::malloc_device ( 827raw .size (), dpct::get_in_order_queue ()))!= 8280 || 829DPCT_CHECK_ERROR (dhead_ = (uint8_t * )sycl::malloc_device ( 830 (size_t )(n_dvocab_ * row_bytes ), 831 dpct::get_in_order_queue ()))!= 0 || 832dvocab_ == nullptr || dhead_ == nullptr ) {// Level Zero returns null when the VRAM is full 833err = "mtp: the draft head does not fit" ; 834draft_head_hint (n_dvocab_ ,row_bytes ); 835return false; 836 } 837 dpct::get_in_order_queue ().memcpy (dvocab_ ,raw .data (),raw .size ()).wait (); 838dvocab_host_ .resize ((size_t )n_dvocab_ ); 839 std::memcpy (dvocab_host_ .data (),raw .data (),raw .size ()); 840bool planar_gathered = false; 841if (head -> type ()== 14 && strata::kernels::native_q6_k_is_planar (head -> weights ())&& !q4_head_ ) { 842// STRATA_Q6_PLANAR: the LM head is stored as planes; the subset is gathered from them, planar 843void * pd = strata::kernels::native_q6_k_planar_gather (head -> weights (), (int ) (row_bytes /210 )* 256 ,dvocab_ , 844n_dvocab_ ,"MTP draft head" ); 845if (pd != nullptr ) { 846 sycl::free (dhead_ , dpct::get_in_order_queue ()); 847dhead_ = (uint8_t * )pd ; 848planar_gathered = true; 849 } 850 } 851if (!planar_gathered ) 852 strata::kernels::gather_rows ((const uint8_t * )head -> weights (),row_bytes ,dvocab_ ,n_dvocab_ ,dhead_ ,nullptr ); 853 dpct::get_current_device ().queues_wait_and_throw (); 854vram_ += (uint64_t ) (n_dvocab_ * row_bytes )+ raw .size (); 855 std::fprintf (stderr ,"strata mtp: draft head over %lld tokens (%.1f MiB)\n" , (long long )n_dvocab_ , 856 (double ) (n_dvocab_ * row_bytes ) /1048576.0 ); 857dhead_type_ = head -> type (); 858if (strata::kernels::b60_cache_requested (24 )){ 859if (dhead_type_ != 23 || n_dvocab_ != 106299 || row_bytes != 1360 || q4_head_ )throw std::logic_error ("B60 exact draft cache requires the fixed raw IQ4 subset" ); 860 strata::kernels::b60_make_weight_cache (dhead_ ,int (n_dvocab_ ),2560 ,24 ,device_ ,& dpct::get_in_order_queue ()); 861const uint64_t cache_bytes = uint64_t ((n_dvocab_ + 15 )/16 * 16 )* 1360 + 2 * strata::kernels::kB60WeightCacheGuard ; 862vram_ += cache_bytes ; 863 std::fprintf (stderr ,"B60_DRAFT_CACHE device=%d bytes=%llu\n" ,device_ ,(unsigned long long )cache_bytes ); 864 } 865if (q4_head_ && !make_q4_head (err ))return false; 866if (dhead_type_ == 14 && strata::kernels::native_q6_k_packed_enabled ())// STRATA_Q6_PACKED=1 867 strata::kernels::native_q6_k_pack (dhead_ , (int ) (row_bytes /210 )* 256 , (int )n_dvocab_ , 868"MTP draft head" ); 869if (!planar_gathered && dhead_type_ == 14 && !q4_head_ && !strata::kernels::native_q6_k_packed_enabled ()&& 870 strata::kernels::native_q6_k_planar_enabled ())// STRATA_Q6_PLANAR 871dhead_ = (uint8_t * ) strata::kernels::native_q6_k_planar_adopt (dhead_ , (int ) (row_bytes /210 )* 256 , 872 (int )n_dvocab_ ,"MTP draft head" ); 873 } 874 } 875if (coupled_draft_env ()&& cparams_ == nullptr && !setup_coupled (err ))return false; 876return true; 877} 878catch (sycl::exception const & exc ) { 879 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 880 <<", line:" <<__LINE__ << std::endl ; 881 std::exit (1 ); 882} 883 884// The layer for T rows. full = false stops after the K/V append (the prompt only needs the cache). 885bool MtpDrafter ::record_forward (int T ,int step_row0 , dpct::queue_ptr cs , 886 std::string & err ) { 887 strata::workload_trace::Scope forward_trace ("decode.mtp_forward" ,cs ,T ); 888// step_row0 >= 0: the full layer on step rows [step_row0, +T); step_row0 < 0: K/V only on rows [-1 - step_row0, +T) 889const bool full = step_row0 >=0 ; 890if (full && T != 1 ) {err = "mtp: the full layer runs one row at a time (its attention scratch is sized for one)" ;return false; } 891if (!record_front (T ,full ?step_row0 :-1 - step_row0 ,cs ,err ))return false; 892return !full || record_rest (step_row0 ,cs ,err ); 893} 894 895bool MtpDrafter ::record_front (int T ,int row0 , dpct::queue_ptr cs , 896 std::string & err ) { 897using namespace strata::kernels ; 898const ModelGeometry & g = * g_ ; 899const int64_t N = g .n_embd ,HC = g .hc ,NH = g .n_head ,HD = g .head_dim ,NKV = g .n_head_kv ; 900const QsaShapes s = shapes_of (g ); 901const int32_t * step = step_ + row0 * 4 ; 902const int32_t * pos = pos_ + row0 * NH ; 903// --mtp-q4: each projection's format and weights for this pass (Q8_0 unless the Q4_0 copies exist) 904int wt_fc_embedding ,wt_fc_hidden ,wt_k_proj ,wt_v_proj ; 905const void * wp_fc_embedding = wq ("fc_embedding.weight" ,wt_fc_embedding ); 906const void * wp_fc_hidden = wq ("fc_hidden.weight" ,wt_fc_hidden ); 907const void * wp_k_proj = wq ("self_attn.k_proj.weight" ,wt_k_proj ); 908const void * wp_v_proj = wq ("self_attn.v_proj.weight" ,wt_v_proj ); 909try { 910// ---- the two input branches 911const WeightRef * we = wt_ -> find ("token_embd.weight" ); 912if (!we ) {err = "mtp: token_embd.weight is missing" ;return false; } 913if (const NativeEmbed * ne = native_embed ()) {// plan v0.3 P6: the GGUF-form table 914ne -> gather_dev (tok_ ,T ,emb_ ,cs ); 915 }else { 916const auto * codes = (const uint8_t * )we -> data ; 917const auto * scales = (const float * ) (codes + we -> codes_bytes ); 918const auto * offsets = we -> has_offset ? (const float * ) (codes + we -> codes_bytes + we -> scales_bytes ) :nullptr ; 919embedding_gather_dev (codes ,scales ,offsets ,tok_ ,T ,we -> ne0 ,we -> code_bits ,we -> code_bias ,we -> group_elems , 920 (uint64_t ) (we -> ne0 / (8 /we -> code_bits )), (uint64_t ) (we -> ne0 /we -> group_elems ),emb_ ,cs ); 921 } 922native_qsa_rms_norm_weighted (emb_ ,f32 ("pre_fc_norm_embedding.weight" ),en_ , (int )N ,T ,EPS ,cs ); 923native_quantize_q8_1 (en_ ,xq_ , (int )N ,T ,cs ); 924native_mmvq (wt_fc_embedding ,wp_fc_embedding ,xq_ ,e2_ , (int )N , (int )N ,T ,cs ); 925if (hnorm_stream_ )// --mtp-hnorm stream: one RMS per stream, each scaled by its slice of the weight 926native_qsa_rms_norm_grouped (Rin_ ,f32 ("pre_fc_norm_hidden.weight" ),hn_ , (int )N , (int )HC , (int ) (T * HC ),EPS ,cs ); 927else 928native_qsa_rms_norm_weighted (Rin_ ,f32 ("pre_fc_norm_hidden.weight" ),hn_ , (int ) (HC * N ),T ,EPS ,cs ); 929for (int c0 = 0 ;c0 < T * HC ;c0 += 8 ) { 930const int nc = (int ) std::min < int64_t > (8 ,T * HC - c0 ); 931native_quantize_q8_1 (hn_ + (size_t )c0 * N ,xq_ , (int )N ,nc ,cs ); 932native_mmvq (wt_fc_hidden ,wp_fc_hidden ,xq_ ,h2_ + (size_t )c0 * N , (int )N , (int )N ,nc ,cs ); 933 } 934add_streams_broadcast (h2_ ,e2_ ,R_ ,N , (int )HC ,T ,cs ); 935// ---- the attention hyper-connection 936bool b60_attn_q8 = false; 937 { 938FusedGrArgs fa [kFusedGrMaxT ]; 939for (int t = 0 ;t < T ;++ t ) { 940fa [t ].R = R_ + (size_t )t * HC * N ;fa [t ].R_out = R_ + (size_t )t * HC * N ;fa [t ].apply = false; 941fa [t ].w_norm = f32 ("attn_hyper_connection.hc_norm.weight" ); 942fa [t ].w_down = bf16 ("attn_hyper_connection.input_mix_weight_down.weight" ); 943fa [t ].w_up = bf16 ("attn_hyper_connection.input_mix_weight_up.weight" ); 944fa [t ].w_inject = bf16 ("attn_hyper_connection.block_inject_weight.weight" ); 945fa [t ].eps = EPS ;fa [t ].lo = lo_ + t * g .hc_lr ;fa [t ].rs = rs_ + t * HC ; 946fa [t ].inject_out = inj_ + t * HC ;fa [t ].mixed = mixed_ + t * N ;if (b60_gr_q8_requested ()&& T == 1 )fa [t ].q8_mixed = xq_ + size_t (t )* (N /32 )* 36 ; 947 } 948b60_attn_q8 = fused_gr_read_multi (fa ,T ,xn_ ,cs ); 949 } 950// ---- attention: K/V into the layer's own cache 951if (!b60_attn_q8 )native_quantize_q8_1 (mixed_ ,xq_ , (int )N ,T ,cs ); 952native_mmvq (wt_k_proj ,wp_k_proj ,xq_ ,kcur_ , (int )N , (int ) (NKV * HD ),T ,cs ); 953native_mmvq (wt_v_proj ,wp_v_proj ,xq_ ,vcur_ , (int )N , (int ) (NKV * HD ),T ,cs ); 954// #783 PR-d (stuchapin909): the T tokens' K norm, K/V rotation and K/V append each run once over all T rows 955// (every row is independent; the rope keeps its per-token positions). STRATA_NO_BATCH_KV_STEP=1 appends per token. 956static const bool no_batch_kv = [] { 957const char * v = std::getenv ("STRATA_NO_BATCH_KV_STEP" ); 958return v != nullptr && v [0 ]!= '\0' && v [0 ]!= '0' ; 959 }(); 960// #783 PR-f (stuchapin909): the per-head RMSNorm and the rope fused (bit-identical to the pair, rope_parity 961// check 6; STRATA_NO_NORM_ROPE=1 keeps the two; off on HIP until its parity check passes). K rows of one token 962// are consecutive in `pos`, tokens are NH apart, so a one-token window is the fusable case. 963const bool fuse_nr = native_rope_enabled ()&& native_norm_rope_usable ((int )HD , (int )s .n_rot ); 964if (T == 1 && fuse_nr ) { 965native_qsa_rms_norm_rope (kcur_ , (int )HD ,f32 ("self_attn.k_norm.weight" ),kcur_ , (int )NKV , (int )HD , 966 (int )s .n_rot ,EPS ,rope_scaling (),pos ,cs ); 967 }else { 968native_qsa_rms_norm_weighted (kcur_ ,f32 ("self_attn.k_norm.weight" ),kcur_ , (int )HD , (int ) (T * NKV ),EPS ,cs ); 969for (int t = 0 ;t < T ;++ t ) { 970float * kc = kcur_ + t * NKV * HD ; 971if (native_rope_enabled ())native_rope_apply (kc ,kc , (int )NKV , (int )HD , (int )s .n_rot ,rope_scaling (),pos + t * NH ,cs ); 972else rope_neox_apply (kc ,kc , (int )NKV , (int )HD , (int )s .n_rot ,st_ .cos_tab ,st_ .sin_tab ,pos + t * NH ,cs ); 973 } 974 } 975if (st_ .kv_rot ) {// rotated K and V (kv_q4.hpp): Q4_0, and INT8 with STRATA_KV_ROT=1 976fwht256_inplace_cuda (kcur_ , (int64_t )T * NKV ,cs ); 977fwht256_inplace_cuda (vcur_ , (int64_t )T * NKV ,cs ); 978 } 979// stored in the state's own format (#293 appended rotated INT8 K/V as Q4_0, into pools INT8 never has) 980if (!no_batch_kv && st_ .kv_q4 ) 981kv_append_q4_steps (st_ .k_q4 ,st_ .v_q4 ,st_ .page_table ,step ,4 ,T ,kcur_ ,vcur_ ,s ,cs ,& st_ .host ); 982else if (!no_batch_kv && st_ .kv_int8 ) 983kv_append_q8_steps (st_ .k_q ,st_ .v_q ,st_ .k_scale ,st_ .v_scale ,st_ .page_table ,step ,4 ,kcur_ ,vcur_ , 984 (int ) (NKV * HD ),T ,s ,cs ,& st_ .host ); 985else 986for (int t = 0 ;t < T ;++ t ) { 987if (st_ .kv_q4 ) 988kv_append_q4_step (st_ .k_q4 ,st_ .v_q4 ,st_ .page_table ,step + t * 4 ,kcur_ + t * NKV * HD , 989vcur_ + t * NKV * HD ,s ,cs ,& st_ .host ); 990else if (st_ .kv_int8 ) 991kv_append_q8_step (st_ .k_q ,st_ .v_q ,st_ .k_scale ,st_ .v_scale ,st_ .page_table ,step + t * 4 , 992kcur_ + t * NKV * HD ,vcur_ + t * NKV * HD ,s ,cs ,& st_ .host ); 993else 994kv_append_step (st_ .k_pool ,st_ .v_pool ,st_ .page_table ,step + t * 4 ,kcur_ + t * NKV * HD , 995vcur_ + t * NKV * HD ,s ,cs ,& st_ .host ); 996 } 997 }catch (const std::exception & e ) { 998err = std::string ("mtp: " )+ e .what (); 999return false; 1000 } 1001return true; 1002} 1003 1004void MtpDrafter ::norm_rope (float * data ,const float * gamma ,int rows ,int cols , 1005const int32_t * p , dpct::queue_ptr cs ) { 1006using namespace strata::kernels ; 1007const QsaShapes s = shapes_of (* g_ ); 1008native_qsa_rms_norm_weighted (data ,gamma ,data ,cols ,rows ,EPS ,cs ); 1009if (native_rope_enabled ())native_rope_apply (data ,data ,rows ,cols , (int )s .n_rot ,rope_scaling (),p ,cs ); 1010else rope_neox_apply (data ,data ,rows ,cols , (int )s .n_rot ,st_ .cos_tab ,st_ .sin_tab ,p ,cs ); 1011} 1012 1013bool MtpDrafter ::record_rest (int step_row , dpct::queue_ptr cs , 1014 std::string & err ) { 1015using namespace strata::kernels ; 1016const ModelGeometry & g = * g_ ; 1017SessionState & ss = * ss_ ; 1018const int T = 1 ; 1019const int64_t N = g .n_embd ,HC = g .hc ,K = ss .k ,NH = g .n_head ,HD = g .head_dim ; 1020const QsaShapes s = shapes_of (g ); 1021const GrShapes gs {g .n_embd ,g .hc ,g .hc_lr }; 1022const int32_t * step = step_ + step_row * 4 ; 1023const int32_t * pos = pos_ + step_row * NH ; 1024// --mtp-q4: the q and o projections' format and weights (Q8_0 unless the Q4_0 copies exist) 1025int wt_q_proj ,wt_o_proj ; 1026const void * wp_q_proj = wq ("self_attn.q_proj.weight" ,wt_q_proj ); 1027const void * wp_o_proj = wq ("self_attn.o_proj.weight" ,wt_o_proj ); 1028const bool fuse_nr = native_rope_enabled ()&& native_norm_rope_usable ((int )HD , (int )s .n_rot );// #783 PR-f 1029try { 1030// ---- dense attention over every cell 1031native_mmvq (wt_q_proj ,wp_q_proj ,xq_ ,qfull_ , (int )N , (int ) (NH * 2 * HD ),T ,cs ); 1032// all T tokens' q rows at once (the rows of token t sit at pos[t * NH ..], so row r reads pos[r]) 1033if (fuse_nr ) { 1034native_qsa_rms_norm_rope (qfull_ , (int ) (2 * HD ),f32 ("self_attn.q_norm.weight" ),qcur_ , (int ) (T * NH ), 1035 (int )HD , (int )s .n_rot ,EPS ,rope_scaling (),pos ,cs ); 1036 }else { 1037/* 1038DPCT1124: cudaMemcpy2DAsync is migrated to asynchronous memcpy 1039API. While the origin API might be synchronous, it depends on the 1040type of operand memory, so you may need to call wait() on event 1041return by memcpy API to ensure synchronization behavior. 1042*/ 1043if (DPCT_CHECK_ERROR (dpct::async_dpct_memcpy ( 1044qcur_ , (size_t )HD * 4 ,qfull_ , (size_t )HD * 2 * 4 , 1045 (size_t )HD * 4 , (size_t )(T * NH ), dpct::device_to_device , 1046* cs ))!= 0 ) { 1047err = "mtp: q split failed" ; 1048return false; 1049 } 1050norm_rope (qcur_ ,f32 ("self_attn.q_norm.weight" ), (int ) (T * NH ), (int )HD ,pos ,cs ); 1051 } 1052if (st_ .kv_rot )fwht256_inplace_cuda (qcur_ , (int64_t )T * NH ,cs ); 1053const QsaAttnPools pools = qsa_attn_pools (st_ ); 1054if (window_ > 0 )window_ids (const_cast < int32_t *> (step ),T , (int )window_ ,ident_ ,cap_ ,cs ); 1055// parts_ has no live value here: the same in-order stream overwrites 1056// active MoE outputs later in record_rest before their combine reads. 1057const uint64_t merge_workspace_floats = uint64_t (max_t_ )* uint64_t (K )* uint64_t (N ); 1058if (!qsa_decode_attn_batch_try_two_stage (qcur_ ,pools ,ident_ ,step ,cap_ ,s , 1059attn_scratch_ ,attn_ ,T ,parts_ ,merge_workspace_floats ,cs )) 1060qsa_decode_attn_batch (qcur_ ,pools ,ident_ ,step ,cap_ ,s ,attn_scratch_ ,attn_ ,T ,cs ); 1061if (st_ .kv_rot )fwht256_inplace_cuda (attn_ , (int64_t )T * NH ,cs ); 1062native_qsa_gate_apply (attn_ ,qfull_ ,attn32_ , (int ) (T * NH ), (int )HD ,cs ); 1063native_quantize_q8_1 (attn32_ ,xq_ , (int ) (NH * HD ),T ,cs ); 1064native_mmvq (wt_o_proj ,wp_o_proj ,xq_ ,bo_ , (int ) (NH * HD ), (int )N ,T ,cs ); 1065// ---- the MLP hyper-connection (the attention write folded in) 1066bool b60_ffn_q8 = false; 1067 { 1068FusedGrArgs fa [kFusedGrMaxT ]; 1069for (int t = 0 ;t < T ;++ t ) { 1070fa [t ].R = R_ + (size_t )t * HC * N ;fa [t ].R_out = R_ + (size_t )t * HC * N ;fa [t ].apply = true; 1071fa [t ].bo_prev = bo_ + t * N ;fa [t ].inj_prev = inj_ + t * HC ; 1072fa [t ].w_norm = f32 ("mlp_hyper_connection.hc_norm.weight" ); 1073fa [t ].w_down = bf16 ("mlp_hyper_connection.input_mix_weight_down.weight" ); 1074fa [t ].w_up = bf16 ("mlp_hyper_connection.input_mix_weight_up.weight" ); 1075fa [t ].w_inject = bf16 ("mlp_hyper_connection.block_inject_weight.weight" ); 1076fa [t ].eps = EPS ;fa [t ].lo = lo_ + t * g .hc_lr ;fa [t ].rs = rs_ + t * HC ; 1077fa [t ].inject_out = inj2_ + t * HC ;fa [t ].mixed = mixed_ + t * N ;if (b60_gr_q8_requested ()&& T == 1 )fa [t ].q8_mixed = xq_ + size_t (t )* (N /32 )* 36 ; 1078 } 1079b60_ffn_q8 = fused_gr_read_multi (fa ,T ,xn_ ,cs ); 1080 } 1081// ---- MoE: router, the 512 resident experts, the shared expert (on a branch beside them on CUDA), the 1082// combine, the write 1083NativeSharedWeights nsw ; 1084nsw .gate_data = wq ("mlp.shared_expert.gate_proj.weight" ,nsw .gate_type ); 1085nsw .up_data = wq ("mlp.shared_expert.up_proj.weight" ,nsw .up_type ); 1086nsw .down_data = wq ("mlp.shared_expert.down_proj.weight" ,nsw .down_type ); 1087nsw .q8_1 = xq_ ;nsw .x_q8_1 = b60_ffn_q8 ?xq_ :nullptr ;// routed experts retain their original Q8_0 input 1088const SForm none {}; 1089const bool need_bf16_x = !shared_expert_native_bf16_enabled (); 1090static const bool fuse_head_gr = [] { 1091const char * v = std::getenv ("STRATA_FUSE_HEAD_GR" ); 1092return v != nullptr && std::atoi (v )!= 0 ; 1093 }(); 1094static const bool head_mix_multi_on = [] { 1095#if defined(STRATA_USE_HIP ) 1096return false; 1097#else 1098const char * v = std::getenv ("STRATA_HEAD_MIX_MULTI" ); 1099return v == nullptr || std::atoi (v )!= 0 ; 1100#endif 1101 }(); 1102// the shared expert only reads mixed_ / xq_ and writes shared_: a branch beside the router and the routed 1103// experts, joined before the combine (CUDA; HIP keeps one stream: STRATA_MTP_SHARED_BRANCH=0 does too) 1104static const bool branch_on = [] { 1105#if defined(STRATA_USE_HIP ) 1106return false; 1107#else 1108const char * v = std::getenv ("STRATA_MTP_SHARED_BRANCH" ); 1109return v == nullptr || std::atoi (v )!= 0 ; 1110#endif 1111 }(); 1112 dpct::queue_ptr sh_cs = cs ; 1113if (branch_on ) { 1114/* 1115DPCT1024: The original code returned the error code that was 1116further consumed by the program logic. This original code was 1117replaced with 0. You may need to rewrite the program logic consuming 1118the error code. 1119*/ 1120if (DPCT_CHECK_ERROR (dpct::sync_barrier (sh_fork_ ,cs ))!= 0 || 1121DPCT_CHECK_ERROR ( 1122 (side_ )-> ext_oneapi_submit_barrier ({* sh_fork_ }))!= 0 ) { 1123err = "mtp: the shared expert's branch" ; 1124return false; 1125 } 1126sh_cs = side_ ; 1127 } 1128auto shared_rows = [& ]() { 1129for (int t = 0 ;t < T ;++ t ) { 1130if (need_bf16_x )f32_to_bf16_bulk (mixed_ + t * N ,x_bf16_ ,N ,sh_cs ); 1131shared_expert (nullptr ,nullptr ,x_bf16_ ,none ,nullptr ,nullptr ,nullptr ,none ,nullptr ,nullptr ,nullptr , 1132none ,nullptr ,nullptr ,nullptr ,bf16 ("mlp.shared_expert_gate.weight" ),sh_scratch_ , 1133shared_ + t * N ,N ,g .n_ff ,32 ,sh_cs ,mixed_ + t * N ,& nsw ); 1134 } 1135 }; 1136if (branch_on ) { 1137shared_rows (); 1138/* 1139DPCT1024: The original code returned the error code that was 1140further consumed by the program logic. This original code was 1141replaced with 0. You may need to rewrite the program logic consuming 1142the error code. 1143*/ 1144if (DPCT_CHECK_ERROR (dpct::sync_barrier (sh_join_ ,side_ ))!= 0 ) { 1145err = "mtp: the shared expert's branch" ;return false; 1146 } 1147 } 1148// #783 PR-c (stuchapin909): a multi-token window routes in two launches (one router GEMV reading the weight once, 1149// one top-10 over all rows - each row bitwise the single-token call) and combines in one 1150if (T > 1 && native_router_enabled ()&& g .n_expert == 512 && K == 10 ) { 1151bf16_gemv_fp32_mmvf_multi (mixed_ ,N ,bf16 ("mlp.gate.weight" ),logits_ ,g .n_expert , (int )N , (int )g .n_expert ,T ,cs ); 1152native_router_top10_multi (logits_ ,ids_ ,w_ ,T ,cs ); 1153 }else { 1154for (int t = 0 ;t < T ;++ t ) { 1155bf16_gemv_fp32_mmvf (mixed_ + t * N ,bf16 ("mlp.gate.weight" ),logits_ + t * g .n_expert , (int )N , (int )g .n_expert ,cs ); 1156if (native_router_enabled ()&& g .n_expert == 512 && K == 10 )native_router_top10 (logits_ + t * g .n_expert ,ids_ + t * K ,w_ + t * K ,cs ); 1157else router_top10 (logits_ + t * g .n_expert ,1 , (int )g .n_expert , (int )K ,ids_ + t * K ,w_ + t * K ,cs ); 1158 } 1159 } 1160moe_group_resident (ids_ , (int ) (T * K ), (int )K ,experts_ , (int64_t ) strata::kernels::cpu::BLOB ,grp_ptr_ , 1161grp_start_ ,grp_counts_ ,hit_dst_ ,hit_slot_ ,cs ); 1162quantize_q8_0_scaled (mixed_ ,hit_xq_ ,hit_xs_ , (int64_t )T * N ,cs ); 1163moe_grouped_s2 (grp_ptr_ ,grp_start_ ,grp_counts_ ,hit_dst_ ,hit_slot_ , (int64_t )T * K , (int64_t )T * K ,hit_xq_ , 1164hit_xs_ ,hit_scratch_ ,parts_ ,cs ); 1165if (branch_on ) { 1166if (DPCT_CHECK_ERROR (cs -> ext_oneapi_submit_barrier ({* sh_join_ }))!= 11670 ) { 1168err = "mtp: the shared expert's join" ;return false; 1169 } 1170 }else { 1171shared_rows (); 1172 } 1173static const bool no_multi_gr = [] {// #783 PR-g: STRATA_NO_MULTI_GR=1 keeps the per-token GR calls 1174const char * v = std::getenv ("STRATA_NO_MULTI_GR" ); 1175return v != nullptr && v [0 ]!= '\0' && v [0 ]!= '0' ; 1176 }(); 1177for (int t = 0 ;t < T ;++ t ) { 1178if (!(T > 1 && native_moe_combine_enabled ())) { 1179if (native_moe_combine_enabled ()) 1180native_moe_combine (parts_ + (size_t )t * K * N ,w_ + t * K ,shared_ + t * N ,y_ + t * N ,N ,K ,cs ); 1181else 1182moe_combine (parts_ + (size_t )t * K * N ,w_ + t * K ,shared_ + t * N ,y_ + t * N ,N ,K ,cs ); 1183 } 1184if (!fuse_head_gr && no_multi_gr ) 1185gr_write (R_ + (size_t )t * HC * N ,y_ + t * N ,inj2_ + t * HC ,gs ,R_ + (size_t )t * HC * N ,cs ); 1186 } 1187if (T > 1 && native_moe_combine_enabled ()) 1188native_moe_combine_multi (parts_ ,w_ ,shared_ ,y_ ,N ,K ,T ,cs ); 1189// #783 PR-g (stuchapin909): the T residual writes in one launch (each token's R, block output and injection are 1190// its own, so doing them after the loop changes nothing) 1191if (!fuse_head_gr && !no_multi_gr ) 1192gr_write_multi (R_ ,y_ ,inj2_ ,gs ,R_ ,T ,cs ); 1193// ---- the final mixer and the main model's head 1194bool b60_head_q8 = false; 1195if (fuse_head_gr ) { 1196FusedGrArgs fa [kFusedGrMaxT ]; 1197for (int t = 0 ;t < T ;++ t ) { 1198fa [t ].R = R_ + (size_t )t * HC * N ;fa [t ].R_out = R_ + (size_t )t * HC * N ;fa [t ].apply = true; 1199fa [t ].bo_prev = y_ + t * N ;fa [t ].inj_prev = inj2_ + t * HC ; 1200fa [t ].w_norm = f32 ("hyper_connection_mixer.hc_norm.weight" ); 1201fa [t ].w_down = bf16 ("hyper_connection_mixer.input_mix_weight_down.weight" ); 1202fa [t ].w_up = bf16 ("hyper_connection_mixer.input_mix_weight_up.weight" ); 1203fa [t ].w_inject = nullptr ; 1204fa [t ].eps = EPS ;fa [t ].lo = lo_ + t * g .hc_lr ;fa [t ].rs = rs_ + t * HC ; 1205fa [t ].inject_out = dummy_inj_ ;fa [t ].mixed = sample_ + t * N ;if (b60_gr_q8_requested ()&& T == 1 )fa [t ].q8_mixed = xq_ + size_t (t )* (N /32 )* 36 ; 1206 } 1207b60_head_q8 = fused_gr_read_multi (fa ,T ,xn_ ,cs ); 1208 }else if (head_mix_multi_on ) { 1209// the window's rows in one read (CUDA; HIP keeps gr_read per row): bitwise the same sums 1210FusedGrArgs fa [kFusedGrMaxT ]; 1211for (int t = 0 ;t < T ;++ t ) { 1212fa [t ].R = R_ + (size_t )t * HC * N ;fa [t ].R_out = R_ + (size_t )t * HC * N ;fa [t ].apply = false; 1213fa [t ].w_norm = f32 ("hyper_connection_mixer.hc_norm.weight" ); 1214fa [t ].w_down = bf16 ("hyper_connection_mixer.input_mix_weight_down.weight" ); 1215fa [t ].w_up = bf16 ("hyper_connection_mixer.input_mix_weight_up.weight" ); 1216fa [t ].eps = EPS ;fa [t ].lo = lo_ + t * g .hc_lr ;fa [t ].rs = rs_ + t * HC ;fa [t ].mixed = sample_ + t * N ;if (b60_gr_q8_requested ()&& T == 1 )fa [t ].q8_mixed = xq_ + size_t (t )* (N /32 )* 36 ; 1217 } 1218b60_head_q8 = fused_gr_read_multi (fa ,T ,xn_ ,cs ); 1219 }else { 1220for (int t = 0 ;t < T ;++ t ) 1221gr_read (R_ + (size_t )t * HC * N ,f32 ("hyper_connection_mixer.hc_norm.weight" ), 1222bf16 ("hyper_connection_mixer.input_mix_weight_down.weight" ), 1223bf16 ("hyper_connection_mixer.input_mix_weight_up.weight" ),nullptr ,EPS ,gs ,ss .block .gr , 1224sample_ + t * N ,dummy_inj_ ,cs ); 1225 } 1226if (!b60_head_q8 )native_quantize_q8_1 (sample_ ,xq_ , (int )N ,T ,cs ); 1227const bool sub = dhead_ != nullptr ; 1228const int64_t nv = sub ?n_dvocab_ :n_vocab_ ; 1229native_mmvq (sub ?dhead_type_ :head_ -> type (),sub ?dhead_ :head_ -> weights (),xq_ ,head_logits_ , (int )N , 1230 (int )nv ,T ,cs ); 1231if (coupled_rec_ ) { 1232// coupled draft sampling: the target's chain and Philox draw for the row that will verify this draft 1233// (counter = this cell + 1, from its step record), penalties over the ring; T == 1 (full layer) 1234coupled_draft_sample (head_logits_ , (int )nv ,sub ?dvocab_ :nullptr ,sub ?dinv_ :nullptr , (int )n_vocab_ , 1235cparams_ ,cring_ ,kCoupledHistCap ,coupled_j_ ,step ,cscratch_ ,out_ids_ ,probs_ ,cs ); 1236return true; 1237 } 1238if (argmax_rows_wanted ()) { 1239argmax_rows (head_logits_ ,T , (int )nv ,arg_scratch_ ,out_ids_ ,cs ); 1240 }else { 1241SamplerParams sp ; 1242sp .greedy = true; 1243sp .temperature = 0.0f ; 1244sample_tokens (head_logits_ ,T , (int )nv ,nullptr ,0 ,sp ,out_ids_ ,cs ); 1245 } 1246if (multi_block_head_ops ())row_top_prob_split (head_logits_ ,T , (int )nv ,out_ids_ ,probs_ ,top_scratch_ ,cs ); 1247else row_top_prob (head_logits_ ,T , (int )nv ,out_ids_ ,probs_ ,cs ); 1248if (sub )map_ids (out_ids_ ,dvocab_ ,T ,cs ); 1249 }catch (const std::exception & e ) { 1250err = std::string ("mtp: " )+ e .what (); 1251return false; 1252 } 1253return true; 1254} 1255 1256namespace { 1257bool finish_capture (dpct::queue_ptr cs ,bool ok , 1258 dpct::experimental::command_graph_exec_ptr & exec , 1259const char * what , std::string & err )try { 1260 dpct::experimental::command_graph_ptr graph = nullptr ; 1261const dpct::err0 ce = 1262DPCT_CHECK_ERROR (dpct::experimental::end_recording (cs ,& graph )); 1263if (!ok ) { 1264if (graph )delete (graph ); 1265return false; 1266 } 1267if (ce != 0 || 1268DPCT_CHECK_ERROR ( 1269exec = new sycl::ext::oneapi::experimental::command_graph < 1270 sycl::ext::oneapi::experimental::graph_state::executable > ( 1271graph -> finalize ()))!= 0 ) { 1272if (graph )delete (graph ); 1273/* 1274DPCT1009: SYCL reports errors using exceptions and does not use 1275error codes. Please replace the "get_error_string_dummy(...)" with a 1276real error-handling function. 1277*/ 1278err = std::string ("mtp: " )+ what + 1279" capture: " + dpct::get_error_string_dummy (ce ); 1280return false; 1281 } 1282delete (graph ); 1283// an explicit upload: the first launch's implicit one blocked behind a device-side spin (verify.cpp) 1284/* 1285DPCT1007: Migration of cudaGraphUpload is not supported. 1286*/ 1287// no cudaGraphUpload on SYCL: a finalized command_graph is already resident 1288cs -> wait (); 1289return true; 1290} 1291catch (sycl::exception const & exc ) { 1292 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1293 <<", line:" <<__LINE__ << std::endl ; 1294 std::exit (1 ); 1295} 1296}// namespace 1297 1298bool MtpDrafter ::capture_prefill (int T , std::string & err )try { 1299if (prefill_exec_ [T ])return true; 1300using namespace strata::kernels ; 1301if (DPCT_CHECK_ERROR (dpct::experimental::begin_recording (cs_ ))!= 0 ) { 1302err = "mtp: begin capture" ;return false; 1303 } 1304copy_i32_from_mapped (tok_ ,m_tok_ ,T ,cs_ ); 1305copy_i32_from_mapped (step_ ,m_step_ , (int64_t )T * 4 ,cs_ ); 1306copy_i32_from_mapped (pos_ ,m_pos_ , (int64_t )T * g_ -> n_head ,cs_ ); 1307const bool ok = record_forward (T ,-1 ,cs_ ,err );// K/V only, rows [0, T) 1308return finish_capture (cs_ ,ok ,prefill_exec_ [T ],"prefill" ,err ); 1309} 1310catch (sycl::exception const & exc ) { 1311 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1312 <<", line:" <<__LINE__ << std::endl ; 1313 std::exit (1 ); 1314} 1315 1316bool MtpDrafter ::capture_prefill_dev (int T , std::string & err )try { 1317if (prefill_dev_exec_ [T ])return true; 1318if (DPCT_CHECK_ERROR (dpct::experimental::begin_recording (cs_ ))!= 0 ) { 1319err = "mtp: begin capture" ;return false; 1320 } 1321const bool ok = record_forward (T ,-1 ,cs_ ,err );// K/V only, rows [0, T); tok_/step_/pos_ filled before launch 1322return finish_capture (cs_ ,ok ,prefill_dev_exec_ [T ],"prefill (device inputs)" ,err ); 1323} 1324catch (sycl::exception const & exc ) { 1325 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1326 <<", line:" <<__LINE__ << std::endl ; 1327 std::exit (1 ); 1328} 1329 1330bool MtpDrafter ::capture_round (int T ,bool coupled , std::string & err )try { 1331 dpct::experimental::command_graph_exec_ptr & exec = coupled ?round_exec_c_ [T ] :round_exec_ [T ]; 1332if (exec )return true; 1333using namespace strata::kernels ; 1334const int64_t HCN = g_ -> hc * g_ -> n_embd ; 1335if (DPCT_CHECK_ERROR (dpct::experimental::begin_recording (cs_ ))!= 0 ) { 1336err = "mtp: begin capture" ;return false; 1337 } 1338bool ok = true; 1339// coupled: the request's chain and the penalty history's base, for this round's drafts 1340if (coupled )coupled_draft_stage (m_cparams_ ,m_chist_ ,cparams_ ,cring_ ,kCoupledHistCap ,cs_ ); 1341// the catch-up: the layer's front for the window's T cells (their K/V), then its rest for row a only, on row 1342// a's intermediates copied to row 0, at the cell the host staged in step row 2*max_t - 1; the draft chain is 1343// one graph per step (`capture_step`) so the host can stop it when a draft is unlikely 1344const int ra = 2 * max_t_ - 1 ; 1345const int64_t N = g_ -> n_embd ,NH = g_ -> n_head ; 1346#if defined(STRATA_USE_HIP )// AMD keeps its separate copies 1347copy_i32_from_mapped (tok_ ,m_tok_ ,T ,cs_ ); 1348copy_i32_from_mapped (step_ ,m_step_ , (int64_t )2 * T * 4 ,cs_ ); 1349copy_i32_from_mapped (pos_ ,m_pos_ , (int64_t )2 * T * NH ,cs_ ); 1350copy_i32_from_mapped (row_ ,m_row_ ,2 ,cs_ ); 1351copy_from_mapped (Rin_ ,window_R_ , (int64_t )T * HCN ,cs_ ); 1352copy_i32_from_mapped (step_ + ra * 4 ,m_step_ + ra * 4 ,4 ,cs_ ); 1353copy_i32_from_mapped (pos_ + ra * NH ,m_pos_ + ra * NH ,NH ,cs_ ); 1354#else // the draft round's seven inputs in one launch 1355const MappedCopy in [7 ]= {{tok_ ,m_tok_ ,T }, {step_ ,m_step_ , (int64_t )2 * T * 4 }, {pos_ ,m_pos_ ,2 * T * NH }, 1356 {row_ ,m_row_ ,2 }, {Rin_ ,window_R_ ,T * HCN }, {step_ + ra * 4 ,m_step_ + ra * 4 ,4 }, 1357 {pos_ + ra * NH ,m_pos_ + ra * NH ,NH }}; 1358copy_from_mapped_multi (in ,7 ,cs_ ); 1359#endif 1360ok = record_front (T ,0 ,cs_ ,err ); 1361if (ok ) { 1362if (T > 1 ) { 1363copy_row_to_first (row_ ,R_ ,HCN ,inj_ ,g_ -> hc ,mixed_ ,N ,cs_ ); 1364native_quantize_q8_1 (mixed_ ,xq_ , (int )N ,1 ,cs_ ); 1365 } 1366coupled_rec_ = coupled ; 1367coupled_j_ = 0 ; 1368ok = record_rest (ra ,cs_ ,err ); 1369coupled_rec_ = false; 1370 } 1371if (ok )mtp_select (R_ ,HCN ,out_ids_ ,row_ + 1 ,Rin_ ,tok_ ,m_out_ ,0 ,cs_ ,probs_ ,m_prob_ ); 1372if (ok && force_on_ && !coupled )force_token (tok_ ,m_force_ ,0 ,cs_ );// chain_launch: step 1's input 1373return finish_capture (cs_ ,ok ,exec ,coupled ?"round (coupled)" :"round" ,err ); 1374} 1375catch (sycl::exception const & exc ) { 1376 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1377 <<", line:" <<__LINE__ << std::endl ; 1378 std::exit (1 ); 1379} 1380 1381// Chain step j (1..max_t-2): one row at the cell staged in step row `max_t + j - 1`, from the previous step's 1382// residual and token (left in Rin_[0] / tok_[0] by mtp_select); draft j and its probability to the mapped outputs. 1383bool MtpDrafter ::capture_step (int j ,bool coupled , std::string & err )try { 1384 dpct::experimental::command_graph_exec_ptr & exec = coupled ?step_exec_c_ [j ] :step_exec_ [j ]; 1385if (exec )return true; 1386using namespace strata::kernels ; 1387const int64_t HCN = g_ -> hc * g_ -> n_embd ; 1388const int row = max_t_ + j - 1 ; 1389if (DPCT_CHECK_ERROR (dpct::experimental::begin_recording (cs_ ))!= 0 ) { 1390err = "mtp: begin capture" ;return false; 1391 } 1392#if defined(STRATA_USE_HIP ) 1393copy_i32_from_mapped (step_ + row * 4 ,m_step_ + row * 4 ,4 ,cs_ ); 1394copy_i32_from_mapped (pos_ + row * g_ -> n_head ,m_pos_ + row * g_ -> n_head ,g_ -> n_head ,cs_ ); 1395#else 1396const MappedCopy in [2 ]= {{step_ + row * 4 ,m_step_ + row * 4 ,4 }, 1397 {pos_ + row * g_ -> n_head ,m_pos_ + row * g_ -> n_head ,g_ -> n_head }}; 1398copy_from_mapped_multi (in ,2 ,cs_ ); 1399#endif 1400coupled_rec_ = coupled ; 1401coupled_j_ = j ; 1402bool ok = record_forward (1 ,row ,cs_ ,err ); 1403coupled_rec_ = false; 1404if (ok )mtp_select (R_ ,HCN ,out_ids_ ,row_ + 1 ,Rin_ ,tok_ ,m_out_ ,j ,cs_ ,probs_ ,m_prob_ ); 1405if (ok && force_on_ && !coupled )force_token (tok_ ,m_force_ ,j ,cs_ );// chain_launch: step j+1's input 1406return finish_capture (cs_ ,ok ,exec ,coupled ?"step (coupled)" :"step" ,err ); 1407} 1408catch (sycl::exception const & exc ) { 1409 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1410 <<", line:" <<__LINE__ << std::endl ; 1411 std::exit (1 ); 1412} 1413 1414void MtpDrafter ::kv_restore (int64_t upto ) { 1415const OnDevice on_device (device_ ); 1416if (st_ .kv_mode != 2 || upto <=0 )return ; 1417// the ring's blocks below `upto`, from the host copy: a checkpoint resume may have left later cells in them 1418const strata::kernels::QsaShapes s = shapes_of (* g_ ); 1419const int64_t b1 = (upto + s .page_size - 1 ) /s .page_size ,b0 = std::max < int64_t > (0 ,b1 - st_ .n_slots ); 1420 strata::kernels::kv_ring_restore (qsa_attn_pools (st_ ),st_ .host ,qsa_kv_format (st_ ),b0 ,b1 ,st_ .n_slots ,s ,cs_ ); 1421cs_ -> wait (); 1422} 1423 1424bool MtpDrafter ::prepare_prefill (std::string & err )try { 1425const OnDevice on_device (device_ ); 1426const int64_t per_row = 1 + 4 + g_ -> n_head ; 1427if (pf_cap_ < (int64_t )max_t_ * per_row ) { 1428if (pf_dev_ ) sycl::free (pf_dev_ , dpct::get_in_order_queue ()); 1429pf_dev_ = nullptr ; 1430pf_cap_ = 0 ; 1431if (DPCT_CHECK_ERROR (pf_dev_ = sycl::malloc_device < int32_t > ( 1432 (size_t )(max_t_ * per_row ), 1433 dpct::get_in_order_queue ()))!= 0 ) { 1434err = "mtp prefill: the input records do not fit" ; 1435return false; 1436 } 1437pf_cap_ = max_t_ * per_row ; 1438 } 1439for (int T = 1 ;T <=max_t_ ;++ T ) 1440if (!capture_prefill_dev (T ,err ))return false;// (STRATA_MTP_PREFILL_SYNC's loop syncs anyway) 1441return true; 1442} 1443catch (sycl::exception const & exc ) { 1444 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1445 <<", line:" <<__LINE__ << std::endl ; 1446 std::exit (1 ); 1447} 1448 1449bool MtpDrafter ::prefill (const float * R_rows ,const int32_t * next_tokens ,int64_t n ,int64_t cell0 , std::string & err , 1450bool sync ) { 1451const OnDevice on_device (device_ ); 1452const Clock ::time_point t0 = Clock ::now (); 1453const int64_t HCN = g_ -> hc * g_ -> n_embd ; 1454// cells the window can never reach again need no K/V 1455const int64_t first_needed = (window_ > 0 && prompt_len_ > 0 ) ?prompt_len_ - window_ - 64 :0 ; 1456// E-4: every group's token / step / position records uploaded at once; each group is then device copies and a 1457// graph on the one stream, with a single sync at the end (a group of <= max_t rows used to be staged in mapped 1458// memory and synced before the next: ~5,500 host round trips on a 32K prompt). The same work in the same 1459// order. STRATA_MTP_PREFILL_SYNC=1 keeps the old loop, =0 forces E-4. 1460// HIP defaults to the old loop. This pass runs whenever E-9 (Prefill::draft_kv) declines, which it does for the 1461// drafter's ring (KV streaming, --kv-resident), and on gfx1201 / ROCm 7.2.4 the E-4 queue (a graph launch and four 1462// device copies per group, ~2,000 groups per 8192-token chunk, no sync) sometimes never completes: the prompt hangs 1463// in hipGraphLaunch or the final sync until the watchdog ends the engine. R9700, full IQ3_XXS, --kv-resident 1464// 32768, mixed load (chats, 32K and 7K prompts, deep follow-ups): E-4 hung in the first round on 2 of 2 tries, 1465// the old loop ran 30 of 30 rounds clean, prompt speed unchanged. 1466static const bool per_group_sync = [] { 1467if (const char * v = std::getenv ("STRATA_MTP_PREFILL_SYNC" ))return std::atoi (v )!= 0 ; 1468#if defined(STRATA_USE_HIP ) 1469return true; 1470#else 1471return false; 1472#endif 1473 }(); 1474const int64_t NHp = g_ -> n_head ,per_row = 1 + 4 + NHp ; 1475if (!per_group_sync && n > 0 ) { 1476if (pf_cap_ < n * per_row ) { 1477if (pf_dev_ ) sycl::free (pf_dev_ , dpct::get_in_order_queue ()); 1478pf_dev_ = nullptr ; 1479pf_cap_ = 0 ; 1480if (DPCT_CHECK_ERROR (pf_dev_ = sycl::malloc_device < int32_t > ( 1481 (size_t )(n * per_row ), 1482 dpct::get_in_order_queue ()))!= 0 ) { 1483err = "mtp prefill: the input records do not fit" ; 1484return false; 1485 } 1486pf_cap_ = n * per_row ; 1487 } 1488 std::vector < int32_t > rec ((size_t ) (n * per_row )); 1489int32_t * tk = rec .data (); 1490int32_t * stp = tk + n ; 1491int32_t * ps = stp + 4 * n ; 1492for (int64_t i = 0 ;i < n ;++ i ) { 1493const int64_t cell = cell0 + i ; 1494tk [i ]= next_tokens [i ]; 1495stp [i * 4 + 0 ]= (int32_t )cell ; 1496stp [i * 4 + 1 ]= (int32_t ) (cell + 1 ); 1497stp [i * 4 + 2 ]= (int32_t ) ((cell + 1 ) /4 ); 1498stp [i * 4 + 3 ]= (int32_t ) (cell + 1 ); 1499for (int64_t h = 0 ;h < NHp ;++ h )ps [i * NHp + h ]= (int32_t )cell ; 1500 } 1501/* 1502DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 1503While the origin API might be synchronous, it depends on the type of 1504operand memory, so you may need to call wait() on event return by memcpy 1505API to ensure synchronization behavior. 1506*/ 1507if (DPCT_CHECK_ERROR (cs_ -> memcpy (pf_dev_ ,rec .data (), 1508rec .size ()* sizeof (int32_t )))!= 0 ) { 1509err = "mtp prefill: the input records upload failed" ; 1510return false; 1511 } 1512const int32_t * d_tk = pf_dev_ ; 1513const int32_t * d_stp = d_tk + n ; 1514const int32_t * d_ps = d_stp + 4 * n ; 1515for (int64_t c = 0 ;c < n ;c += max_t_ ) { 1516const int T = (int ) std::min < int64_t > (max_t_ ,n - c ); 1517if (cell0 + c + T <=first_needed )continue ; 1518if (!capture_prefill_dev (T ,err ))return false; 1519/* 1520DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 1521API. While the origin API might be synchronous, it depends on the 1522type of operand memory, so you may need to call wait() on event 1523return by memcpy API to ensure synchronization behavior. 1524*/ 1525if (DPCT_CHECK_ERROR (cs_ -> memcpy (tok_ ,d_tk + c , (size_t )T * 4 ))!= 15260 || 1527/* 1528DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 1529API. While the origin API might be synchronous, it depends on 1530the type of operand memory, so you may need to call wait() on 1531event return by memcpy API to ensure synchronization behavior. 1532*/ 1533DPCT_CHECK_ERROR ( 1534cs_ -> memcpy (step_ ,d_stp + c * 4 , (size_t )T * 16 ))!= 0 || 1535/* 1536DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 1537API. While the origin API might be synchronous, it depends on 1538the type of operand memory, so you may need to call wait() on 1539event return by memcpy API to ensure synchronization behavior. 1540*/ 1541DPCT_CHECK_ERROR (cs_ -> memcpy (pos_ ,d_ps + c * NHp , 1542 (size_t )(T * NHp )* 4 ))!= 0 || 1543/* 1544DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy 1545API. While the origin API might be synchronous, it depends on 1546the type of operand memory, so you may need to call wait() on 1547event return by memcpy API to ensure synchronization behavior. 1548*/ 1549DPCT_CHECK_ERROR ( 1550cs_ -> memcpy (Rin_ ,R_rows + (size_t )c * HCN , 1551 (size_t )T * HCN * sizeof (float )))!= 0 || 1552DPCT_CHECK_ERROR ( 1553 (cs_ )-> ext_oneapi_graph (* prefill_dev_exec_ [T ]))!= 0 ) { 1554/* 1555DPCT1009: SYCL reports errors using exceptions and does not 1556use error codes. Please replace the 1557"get_error_string_dummy(...)" with a real error-handling 1558function. 1559*/ 1560/* 1561DPCT1010: SYCL uses exceptions to report errors and does not 1562use the error codes. The cudaGetLastError function call was 1563replaced with 0. You need to rewrite this code. 1564*/ 1565err = std::string ("mtp prefill: " )+ 1566 dpct::get_error_string_dummy (0 ); 1567return false; 1568 } 1569 } 1570if (!sync ) {// the caller orders on stream(); the records are staged (a pageable copy returns once taken) 1571 (void )DPCT_CHECK_ERROR (((cs_ )-> ext_oneapi_empty ())); 1572ms_prefill += ms_since (t0 ); 1573return true; 1574 } 1575if (DPCT_CHECK_ERROR (cs_ -> wait ())!= 0 ) { 1576/* 1577DPCT1009: SYCL reports errors using exceptions and does not use 1578error codes. Please replace the "get_error_string_dummy(...)" with a 1579real error-handling function. 1580*/ 1581/* 1582DPCT1010: SYCL uses exceptions to report errors and does not use 1583the error codes. The cudaGetLastError function call was replaced 1584with 0. You need to rewrite this code. 1585*/ 1586err = 1587 std::string ("mtp prefill: " )+ dpct::get_error_string_dummy (0 ); 1588return false; 1589 } 1590ms_prefill += ms_since (t0 ); 1591return true; 1592 } 1593for (int64_t c = 0 ;c < n ;c += max_t_ ) { 1594const int T = (int ) std::min < int64_t > (max_t_ ,n - c ); 1595if (cell0 + c + T <=first_needed )continue ; 1596if (!capture_prefill (T ,err ))return false; 1597for (int t = 0 ;t < T ;++ t ) { 1598const int64_t cell = cell0 + c + t ; 1599h_tok_ [t ]= next_tokens [c + t ]; 1600h_step_ [t * 4 + 0 ]= (int32_t )cell ; 1601h_step_ [t * 4 + 1 ]= (int32_t ) (cell + 1 ); 1602h_step_ [t * 4 + 2 ]= (int32_t ) ((cell + 1 ) /4 ); 1603h_step_ [t * 4 + 3 ]= (int32_t ) (cell + 1 ); 1604for (int64_t h = 0 ;h < g_ -> n_head ;++ h )h_pos_ [t * g_ -> n_head + h ]= (int32_t )cell ; 1605 } 1606/* 1607DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. 1608While the origin API might be synchronous, it depends on the type of 1609operand memory, so you may need to call wait() on event return by memcpy 1610API to ensure synchronization behavior. 1611*/ 1612if (DPCT_CHECK_ERROR (cs_ -> memcpy (Rin_ ,R_rows + (size_t )c * HCN , 1613 (size_t )T * HCN * sizeof (float )))!= 16140 || 1615DPCT_CHECK_ERROR ((cs_ )-> ext_oneapi_graph (* prefill_exec_ [T ]))!= 0 || 1616DPCT_CHECK_ERROR (cs_ -> wait ())!= 0 ) { 1617/* 1618DPCT1009: SYCL reports errors using exceptions and does not use 1619error codes. Please replace the "get_error_string_dummy(...)" with a 1620real error-handling function. 1621*/ 1622/* 1623DPCT1010: SYCL uses exceptions to report errors and does not use 1624the error codes. The cudaGetLastError function call was replaced 1625with 0. You need to rewrite this code. 1626*/ 1627err = 1628 std::string ("mtp prefill: " )+ dpct::get_error_string_dummy (0 ); 1629return false; 1630 } 1631 } 1632ms_prefill += ms_since (t0 ); 1633return true; 1634} 1635 1636bool MtpDrafter ::draft (int T ,const int32_t * tokens ,int64_t p ,int a ,int32_t * drafts , std::string & err , 1637float * probs ,float min_p ,int * n_drafts ) { 1638const OnDevice on_device (device_ ); 1639if (T < 1 || T > max_t_ || a < 0 || a >=T ) {err = "mtp: draft arguments out of range" ;return false; } 1640if (chain_live_ ) {err = "mtp: a pipelined chain is still in flight" ;return false; } 1641// #783 PR-i (stuchapin909): the round runs for the cells up to the accepted row a (T = a + 1): the K/V of the rejected 1642// rows is not caught up - no later read reaches a cell past the one being drafted and the next round writes it first 1643if (!mtp_catchup_all ())T = a + 1 ; 1644const bool cp = coupled_active_ ;// coupled draft sampling for this request: its own graphs 1645if (!capture_round (T ,cp ,err ))return false; 1646const int max_steps = std::min (max_t_ - 1 ,max_drafts_ ); 1647for (int j = 1 ;j < max_steps ;++ j ) 1648if (!capture_step (j ,cp ,err ))return false; 1649const Clock ::time_point t0 = Clock ::now (); 1650const int64_t NH = g_ -> n_head ; 1651auto put = [& ](int row ,int64_t cell ) { 1652h_step_ [row * 4 + 0 ]= (int32_t )cell ; 1653h_step_ [row * 4 + 1 ]= (int32_t ) (cell + 1 ); 1654h_step_ [row * 4 + 2 ]= (int32_t ) ((cell + 1 ) /4 ); 1655h_step_ [row * 4 + 3 ]= (int32_t ) (cell + 1 ); 1656for (int64_t h = 0 ;h < NH ;++ h )h_pos_ [row * NH + h ]= (int32_t )cell ; 1657 }; 1658for (int t = 0 ;t < T ;++ t ) { 1659h_tok_ [t ]= tokens [t ]; 1660put (t ,p + t ); 1661 } 1662put (2 * max_t_ - 1 ,coupled_draft_cell (p ,a ,0 ));// p + a: draft 0's cell 1663for (int j = 1 ;j < max_steps ;++ j ) 1664put (max_t_ + j - 1 ,coupled_draft_cell (p ,a ,j )); 1665for (int j = 0 ;j < max_steps ;++ j ) ((volatile int32_t * )h_out_ )[j ]= -1 ; 1666h_row_ [0 ]= a ; 1667h_row_ [1 ]= 0 ; 1668if (h_force_ != nullptr )for (int j = 0 ;j < 16 ;++ j )h_force_ [j ]= -1 ;// the forcing kernels: no-ops here 1669 std::atomic_thread_fence (std::memory_order_seq_cst ); 1670if (!stage_source_R (T ,err ))return false; 1671 1672SessionState * const pss = ple_ss_ ?ple_ss_ :ss_ ; 1673const bool do_ple = pss != nullptr && pss -> ple .ready ()&& pss -> ple .table != nullptr ; 1674int32_t ple_prev [2 ]= {do_ple ?pss -> ple_prev [0 ] :0 ,do_ple ?pss -> ple_prev [1 ] :0 }; 1675auto prefetch_ple = [& ](int32_t tok ) { 1676if (!do_ple || tok < 0 )return ; 1677uint32_t rows16 [strata::kernels::PLE_N_HEADS ]; 1678 strata::kernels::ngram_rows (& tok ,ple_prev ,1 ,pss -> ple .consts ,rows16 ); 1679ple_prev [0 ]= ple_prev [1 ]; 1680ple_prev [1 ]= tok ; 1681pss -> ple .table -> prefetch_rows (rows16 ); 1682 }; 1683 1684int n = 0 ; 1685if (min_p <=0.0f && max_steps > 0 ) { 1686if (DPCT_CHECK_ERROR ((cs_ )-> ext_oneapi_graph ( 1687* (cp ?round_exec_c_ [T ] :round_exec_ [T ])))!= 0 ) { 1688/* 1689DPCT1009: SYCL reports errors using exceptions and does not use 1690error codes. Please replace the "get_error_string_dummy(...)" with a 1691real error-handling function. 1692*/ 1693/* 1694DPCT1010: SYCL uses exceptions to report errors and does not use 1695the error codes. The cudaGetLastError function call was replaced 1696with 0. You need to rewrite this code. 1697*/ 1698err = std::string ("mtp draft: " )+ dpct::get_error_string_dummy (0 ); 1699return false; 1700 } 1701for (int j = 1 ;j < max_steps ;++ j ) { 1702if (DPCT_CHECK_ERROR ((cs_ )-> ext_oneapi_graph ( 1703* (cp ?step_exec_c_ [j ] :step_exec_ [j ])))!= 0 ) { 1704/* 1705DPCT1009: SYCL reports errors using exceptions and does not 1706use error codes. Please replace the 1707"get_error_string_dummy(...)" with a real error-handling 1708function. 1709*/ 1710/* 1711DPCT1010: SYCL uses exceptions to report errors and does not 1712use the error codes. The cudaGetLastError function call was 1713replaced with 0. You need to rewrite this code. 1714*/ 1715err = std::string ("mtp draft step: " )+ dpct::get_error_string_dummy (0 ); 1716return false; 1717 } 1718 } 1719 (void )DPCT_CHECK_ERROR (((cs_ )-> ext_oneapi_empty ())); 1720prefetch_ple (tokens [a ]); 1721for (int j = 0 ;j + 1 < max_steps ;++ j ) { 1722uint32_t spins = 0 ; 1723while (((volatile int32_t * )h_out_ )[j ]< 0 ) { 1724#if defined(_WIN32 )|| defined(__x86_64__ ) 1725_mm_pause (); 1726#endif 1727if ((++ spins & 1023u )== 0 && 1728 ((cs_ )-> ext_oneapi_empty () ?0 :1 )!= 1 )break ;/* SYCL port: DPCT_CHECK_ERROR of ext_oneapi_empty() was always 0, so the wait gave up after 1024 spins and read a draft the GPU had not written */ 1729 } 1730drafts [j ]= ((volatile int32_t * )h_out_ )[j ]; 1731if (probs )probs [j ]= ((volatile float * )h_prob_ )[j ]; 1732prefetch_ple (drafts [j ]); 1733 } 1734if (DPCT_CHECK_ERROR (cs_ -> wait ())!= 0 ) { 1735/* 1736DPCT1009: SYCL reports errors using exceptions and does not use 1737error codes. Please replace the "get_error_string_dummy(...)" with a 1738real error-handling function. 1739*/ 1740/* 1741DPCT1010: SYCL uses exceptions to report errors and does not use 1742the error codes. The cudaGetLastError function call was replaced 1743with 0. You need to rewrite this code. 1744*/ 1745err = std::string ("mtp draft: " )+ dpct::get_error_string_dummy (0 ); 1746return false; 1747 } 1748const int last = max_steps - 1 ; 1749drafts [last ]= ((volatile int32_t * )h_out_ )[last ]; 1750if (probs )probs [last ]= ((volatile float * )h_prob_ )[last ]; 1751prefetch_ple (drafts [last ]); 1752n = max_steps ; 1753 }else if (max_steps > 0 ) { 1754if (DPCT_CHECK_ERROR ((cs_ )-> ext_oneapi_graph ( 1755* (cp ?round_exec_c_ [T ] :round_exec_ [T ])))!= 0 ) { 1756/* 1757DPCT1009: SYCL reports errors using exceptions and does not use 1758error codes. Please replace the "get_error_string_dummy(...)" with a 1759real error-handling function. 1760*/ 1761/* 1762DPCT1010: SYCL uses exceptions to report errors and does not use 1763the error codes. The cudaGetLastError function call was replaced 1764with 0. You need to rewrite this code. 1765*/ 1766err = std::string ("mtp draft: " )+ dpct::get_error_string_dummy (0 ); 1767return false; 1768 } 1769 (void )DPCT_CHECK_ERROR (((cs_ )-> ext_oneapi_empty ())); 1770prefetch_ple (tokens [a ]); 1771auto wait_step = [& ](int j ) { 1772try { 1773uint32_t spins = 0 ; 1774while (((volatile int32_t * )h_out_ )[j ]< 0 ) { 1775#if defined(_WIN32 )|| defined(__x86_64__ ) 1776_mm_pause (); 1777#endif 1778if ((++ spins & 1023u )== 0 && 1779 ((cs_ )-> ext_oneapi_empty () ?0 :1 )!= 1 )break ;/* SYCL port: DPCT_CHECK_ERROR of ext_oneapi_empty() was always 0, so the wait gave up after 1024 spins and read a draft the GPU had not written */ 1780 } 1781 } 1782catch (sycl::exception const & exc ) { 1783 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1784 <<", line:" <<__LINE__ << std::endl ; 1785 std::exit (1 ); 1786 } 1787 }; 1788wait_step (0 ); 1789drafts [0 ]= ((volatile int32_t * )h_out_ )[0 ]; 1790float pj = ((volatile float * )h_prob_ )[0 ]; 1791if (probs )probs [0 ]= pj ; 1792n = 1 ; 1793for (int j = 1 ;j < max_steps && pj >=min_p ;++ j ) { 1794if (DPCT_CHECK_ERROR ((cs_ )-> ext_oneapi_graph ( 1795* (cp ?step_exec_c_ [j ] :step_exec_ [j ])))!= 0 ) { 1796/* 1797DPCT1009: SYCL reports errors using exceptions and does not 1798use error codes. Please replace the 1799"get_error_string_dummy(...)" with a real error-handling 1800function. 1801*/ 1802/* 1803DPCT1010: SYCL uses exceptions to report errors and does not 1804use the error codes. The cudaGetLastError function call was 1805replaced with 0. You need to rewrite this code. 1806*/ 1807err = std::string ("mtp draft step: " )+ dpct::get_error_string_dummy (0 ); 1808return false; 1809 } 1810 (void )DPCT_CHECK_ERROR (((cs_ )-> ext_oneapi_empty ())); 1811prefetch_ple (drafts [j - 1 ]); 1812wait_step (j ); 1813drafts [j ]= ((volatile int32_t * )h_out_ )[j ]; 1814pj = ((volatile float * )h_prob_ )[j ]; 1815if (probs )probs [j ]= pj ; 1816++ n ; 1817 } 1818prefetch_ple (drafts [n - 1 ]); 1819if (DPCT_CHECK_ERROR (cs_ -> wait ())!= 0 ) { 1820/* 1821DPCT1009: SYCL reports errors using exceptions and does not use 1822error codes. Please replace the "get_error_string_dummy(...)" with a 1823real error-handling function. 1824*/ 1825/* 1826DPCT1010: SYCL uses exceptions to report errors and does not use 1827the error codes. The cudaGetLastError function call was replaced 1828with 0. You need to rewrite this code. 1829*/ 1830err = std::string ("mtp draft: " )+ dpct::get_error_string_dummy (0 ); 1831return false; 1832 } 1833 } 1834for (int j = n ;j < max_t_ - 1 ;++ j ) {drafts [j ]= 0 ;if (probs )probs [j ]= 0.0f ; } 1835if (n_drafts )* n_drafts = n ; 1836ms_draft += ms_since (t0 ); 1837++ rounds ; 1838return true; 1839} 1840 1841bool MtpDrafter ::stage_source_R (int T , std::string & err )try { 1842if (src_R_ == nullptr || src_R_ == window_R_ )return true; 1843/* 1844DPCT1124: cudaMemcpyAsync is migrated to asynchronous memcpy API. While 1845the origin API might be synchronous, it depends on the type of operand 1846memory, so you may need to call wait() on event return by memcpy API to 1847ensure synchronization behavior. 1848*/ 1849if (DPCT_CHECK_ERROR (cs_ -> memcpy ((void * )window_R_ ,src_R_ , 1850 (size_t )T * (size_t )(g_ -> hc * g_ -> n_embd )* 1851sizeof (float )))!= 0 ) { 1852err = "mtp: staging the window's residual rows failed" ; 1853return false; 1854 } 1855return true; 1856} 1857catch (sycl::exception const & exc ) { 1858 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1859 <<", line:" <<__LINE__ << std::endl ; 1860 std::exit (1 ); 1861} 1862 1863bool MtpDrafter ::prepare_chain (std::string & err )try { 1864const OnDevice on_device (device_ ); 1865if (!force_on_ || h_force_ == nullptr ) {err = "mtp: chains need set_force_capture before load" ;return false; } 1866for (int T = 1 ;T <=max_t_ ;++ T ) 1867if (!capture_round (T , false,err ))return false; 1868for (int j = 1 ;j <=max_t_ - 2 ;++ j ) 1869if (!capture_step (j , false,err ))return false; 1870if (ev_chain_ == nullptr && 1871DPCT_CHECK_ERROR (ev_chain_ = new sycl::event ())!= 0 ) { 1872err = "mtp: event creation failed" ; 1873return false; 1874 } 1875for (dpct::event_ptr & e :ev_step_ ) 1876if (e == nullptr && DPCT_CHECK_ERROR (e = new sycl::event ())!= 0 ) { 1877err = "mtp: event creation failed" ; 1878return false; 1879 } 1880return true; 1881} 1882catch (sycl::exception const & exc ) { 1883 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1884 <<", line:" <<__LINE__ << std::endl ; 1885 std::exit (1 ); 1886} 1887 1888bool MtpDrafter ::chain_launch (int T ,const int32_t * tokens ,int64_t p ,int a , 1889const int32_t * force ,int n_force ,int n_out , 1890int n_early , std::string & err )try { 1891const OnDevice on_device (device_ ); 1892if (chain_live_ ) {err = "mtp: a chain is already in flight" ;return false; } 1893if (!force_on_ || ev_chain_ == nullptr ) {err = "mtp: chains need prepare_chain" ;return false; } 1894if (T < 1 || T > max_t_ || a < 0 || a >=T || n_out < 1 || n_out > max_t_ - 1 || n_force < 0 || n_force > n_out || 1895n_force > 16 ) { 1896err = "mtp: chain arguments out of range" ; 1897return false; 1898 } 1899if (round_exec_ [T ]== nullptr ) {err = "mtp: chain graphs not prepared" ;return false; } 1900for (int j = 1 ;j < n_out ;++ j ) 1901if (step_exec_ [j ]== nullptr ) {err = "mtp: chain graphs not prepared" ;return false; } 1902const Clock ::time_point t0 = Clock ::now (); 1903const int64_t NH = g_ -> n_head ; 1904auto put = [& ](int row ,int64_t cell ) { 1905h_step_ [row * 4 + 0 ]= (int32_t )cell ; 1906h_step_ [row * 4 + 1 ]= (int32_t ) (cell + 1 ); 1907h_step_ [row * 4 + 2 ]= (int32_t ) ((cell + 1 ) /4 ); 1908h_step_ [row * 4 + 3 ]= (int32_t ) (cell + 1 ); 1909for (int64_t h = 0 ;h < NH ;++ h )h_pos_ [row * NH + h ]= (int32_t )cell ; 1910 }; 1911for (int t = 0 ;t < T ;++ t ) { 1912h_tok_ [t ]= tokens [t ]; 1913put (t ,p + t ); 1914 } 1915put (2 * max_t_ - 1 ,p + a );// output 0's cell 1916for (int j = 1 ;j < n_out ;++ j )put (max_t_ + j - 1 ,p + a + j );// every step's cell, staged at once 1917for (int j = 0 ;j < 16 ;++ j )h_force_ [j ]= j < n_force ?force [j ] :-1 ; 1918h_row_ [0 ]= a ; 1919h_row_ [1 ]= 0 ; 1920 std::atomic_thread_fence (std::memory_order_seq_cst ); 1921if (!stage_source_R (T ,err ))return false; 1922chain_early_ = std::max (0 , std::min (n_early ,n_out )); 1923int submit_n = n_out ; 1924if (auto * ds = strata::private_demand::get (this )) { 1925ds -> limit = n_out ;ds -> submitted = ds -> target = submit_n = 1 ; 1926ds -> final = n_out == 1 ; 1927ds -> last_ready_ns = 0 ; 1928ds -> T = T ;ds -> p = p ;ds -> a = a ;ds -> n_force = n_force ; 1929for (int j = 0 ;j < T ;++ j )ds -> tokens [j ]= tokens [j ]; 1930for (int j = 0 ;j < n_force ;++ j )ds -> force [j ]= force [j ]; 1931++ ds -> chains ;ds -> requested += n_out ;++ ds -> actual ; 1932 } 1933bool ok = DPCT_CHECK_ERROR ((cs_ )-> ext_oneapi_graph (* round_exec_ [T ]))== 0 ; 1934/* 1935DPCT1024: The original code returned the error code that was further 1936consumed by the program logic. This original code was replaced with 0. You 1937may need to rewrite the program logic consuming the error code. 1938*/ 1939if (ok && chain_early_ >=1 )ok = 1940DPCT_CHECK_ERROR (dpct::sync_barrier (ev_step_ [0 ],cs_ ))== 0 ; 1941for (int j = 1 ;ok && j < submit_n ;++ j ) { 1942ok = DPCT_CHECK_ERROR ((cs_ )-> ext_oneapi_graph (* step_exec_ [j ]))== 0 ; 1943/* 1944DPCT1024: The original code returned the error code that was further 1945consumed by the program logic. This original code was replaced with 0. 1946You may need to rewrite the program logic consuming the error code. 1947*/ 1948if (ok && j < chain_early_ )ok = 1949DPCT_CHECK_ERROR (dpct::sync_barrier (ev_step_ [j ],cs_ ))== 0 ; 1950 } 1951/* 1952DPCT1024: The original code returned the error code that was further 1953consumed by the program logic. This original code was replaced with 0. You 1954may need to rewrite the program logic consuming the error code. 1955*/ 1956if (!ok || DPCT_CHECK_ERROR (dpct::sync_barrier (ev_chain_ ,cs_ ))!= 0 ) { 1957/* 1958DPCT1009: SYCL reports errors using exceptions and does not use 1959error codes. Please replace the "get_error_string_dummy(...)" with a 1960real error-handling function. 1961*/ 1962/* 1963DPCT1010: SYCL uses exceptions to report errors and does not use the 1964error codes. The cudaGetLastError function call was replaced with 0. You 1965need to rewrite this code. 1966*/ 1967err = std::string ("mtp chain: " )+ dpct::get_error_string_dummy (0 ); 1968return false; 1969 } 1970 (void )DPCT_CHECK_ERROR (((cs_ )-> ext_oneapi_empty ()));// WDDM: submit now 1971steps_seen_ = 0 ; 1972chain_live_ = true; 1973chain_n_ = n_out ; 1974ms_draft += ms_since (t0 ); 1975++ rounds ; 1976return true; 1977} 1978catch (sycl::exception const & exc ) { 1979 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 1980 <<", line:" <<__LINE__ << std::endl ; 1981 std::exit (1 ); 1982} 1983 1984int MtpDrafter ::chain_outputs_ready (std::string & err )try { 1985if (!chain_live_ )return chain_n_ ; 1986const OnDevice on_device (device_ ); 1987if (auto * ds = strata::private_demand::get (this )) { 1988if (ds -> target > ds -> submitted ) { 1989const long long start_ns = ds -> metrics ? strata::private_demand::now_ns () :0 ; 1990if (ds -> metrics && ds -> last_ready_ns ) { 1991const auto reaction = start_ns - ds -> last_ready_ns ; 1992ds -> reaction_ns += reaction ; 1993ds -> max_reaction_ns = std::max (ds -> max_reaction_ns ,reaction ); 1994 } 1995if (ds -> target > chain_n_ || ds -> target > ds -> limit ) { 1996err = "private demand: target exceeds staged chain" ;return -1 ; 1997 } 1998for (int j = ds -> submitted ;j < ds -> target ;++ j ) { 1999if (DPCT_CHECK_ERROR (cs_ -> ext_oneapi_graph (* step_exec_ [j ]))!= 0 || 2000DPCT_CHECK_ERROR (dpct::sync_barrier (ev_step_ [j ],cs_ ))!= 0 ) { 2001err = "private demand: continuation failed" ;return -1 ; 2002 } 2003++ ds -> submitted ;++ ds -> continuations ;++ ds -> actual ; 2004 } 2005if (DPCT_CHECK_ERROR (dpct::sync_barrier (ev_chain_ ,cs_ ))!= 0 ) { 2006err = "private demand: retirement event failed" ;return -1 ; 2007 } 2008 (void )DPCT_CHECK_ERROR (cs_ -> ext_oneapi_empty ()); 2009if (ds -> metrics )ds -> submit_ns += strata::private_demand::now_ns ()- start_ns ; 2010 } 2011 } 2012 2013const auto * ds = strata::private_demand::get (this ); 2014const int readable = ds ? std::min (chain_early_ ,ds -> submitted ) :chain_early_ ; 2015while (steps_seen_ < readable ) { 2016const dpct::err0 q = dpct::sycl_event_query (ev_step_ [steps_seen_ ]); 2017/* 2018DPCT1001: The statement could not be removed. 2019*/ 2020/* 2021DPCT1002: Special case error handling if-stmt was detected. You may 2022need to rewrite this code. 2023*/ 2024if (q == 1 )break ; 2025/* 2026DPCT1009: SYCL reports errors using exceptions and does not use 2027error codes. Please replace the "get_error_string_dummy(...)" with a 2028real error-handling function. 2029*/ 2030/* 2031DPCT1001: The statement could not be removed. 2032*/ 2033/* 2034DPCT1000: Error handling if-stmt was detected but could not be 2035rewritten. 2036*/ 2037if (q != 0 ) { 2038err = std::string ("mtp chain: " )+ dpct::get_error_string_dummy (q ); 2039return -1 ; 2040 } 2041chain_tok_ [steps_seen_ ]= ((volatile int32_t * )h_out_ )[steps_seen_ ]; 2042chain_prob_ [steps_seen_ ]= ((volatile float * )h_prob_ )[steps_seen_ ]; 2043++ steps_seen_ ; 2044if (auto * observed = strata::private_demand::get (this );observed && observed -> metrics ) 2045observed -> last_ready_ns = strata::private_demand::now_ns (); 2046 } 2047return steps_seen_ ; 2048} 2049catch (sycl::exception const & exc ) { 2050 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2051 <<", line:" <<__LINE__ << std::endl ; 2052 std::exit (1 ); 2053} 2054 2055int MtpDrafter ::chain_poll (std::string & err )try { 2056if (!chain_live_ )return 1 ; 2057if (auto * ds = strata::private_demand::get (this );ds && !ds -> final )return 0 ; 2058const OnDevice on_device (device_ ); 2059const dpct::err0 q = dpct::sycl_event_query (ev_chain_ ); 2060/* 2061DPCT1001: The statement could not be removed. 2062*/ 2063/* 2064DPCT1002: Special case error handling if-stmt was detected. You may need 2065to rewrite this code. 2066*/ 2067if (q == 1 )return 0 ; 2068chain_live_ = false; 2069/* 2070DPCT1009: SYCL reports errors using exceptions and does not use error 2071codes. Please replace the "get_error_string_dummy(...)" with a real 2072error-handling function. 2073*/ 2074/* 2075DPCT1001: The statement could not be removed. 2076*/ 2077/* 2078DPCT1000: Error handling if-stmt was detected but could not be 2079rewritten. 2080*/ 2081if (q != 0 ) { 2082err = std::string ("mtp chain: " )+ dpct::get_error_string_dummy (q ); 2083return -1 ; 2084 } 2085if (auto * ds = strata::private_demand::get (this ))chain_n_ = ds -> submitted ; 2086for (int j = 0 ;j < chain_n_ ;++ j ) { 2087chain_tok_ [j ]= ((volatile int32_t * )h_out_ )[j ]; 2088chain_prob_ [j ]= ((volatile float * )h_prob_ )[j ]; 2089 } 2090for (int j = chain_n_ ;j < 8 ;++ j ) {chain_tok_ [j ]= 0 ;chain_prob_ [j ]= 0.0f ; } 2091return 1 ; 2092} 2093catch (sycl::exception const & exc ) { 2094 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2095 <<", line:" <<__LINE__ << std::endl ; 2096 std::exit (1 ); 2097} 2098 2099bool MtpDrafter ::draft_first (int T ,const float * R_row ,int32_t token , 2100int64_t cell ,int32_t * drafts , std::string & err , 2101float * probs ,float min_p ,int * n_drafts )try { 2102const OnDevice on_device (device_ ); 2103// row 0 is the real pair; rows 1.. repeat it and only write cells the next round overwrites 2104const int64_t HCN = g_ -> hc * g_ -> n_embd ; 2105for (int t = 0 ;t < T ;++ t ) 2106if (DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 2107 (void * )(window_R_ + (size_t )t * HCN ),R_row , 2108 (size_t )HCN * sizeof (float )).wait ())!= 0 ) { 2109err = "mtp: staging the first residual failed" ; 2110return false; 2111 } 2112 std::vector < int32_t > toks ((size_t )T ,token ); 2113return draft (T ,toks .data (),cell ,0 ,drafts ,err ,probs ,min_p ,n_drafts ); 2114} 2115catch (sycl::exception const & exc ) { 2116 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 2117 <<", line:" <<__LINE__ << std::endl ; 2118 std::exit (1 ); 2119} 2120 2121}// namespace strata::core