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