okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c850b979b
main
1// src/core/dflash2.cpp - see include/strata/core/dflash2.hpp. 2#include "strata/core/dflash2.hpp" 3 4#include "strata/core/native_head.hpp" 5#include "strata/core/on_device.hpp" 6#include "strata/core/weights.hpp" 7#include "strata/kernels/dflash2.hpp" 8#include "strata/kernels/elementwise.hpp" 9#include "strata/kernels/native_mmvq.hpp" 10#include "strata/kernels/native_qsa.hpp" 11#include "strata/kernels/verify_kernels.hpp" 12 13#include <algorithm> 14#include <cstdlib> 15#include <chrono> 16#include <cstdio> 17#include <cstdlib> 18#include <cstring> 19#include <exception> 20#include <atomic> 21#include <initializer_list> 22#include <stdexcept> 23 24namespace strata::core { 25namespace { 26 27using Clock = std::chrono::steady_clock ; 28double ms_since (Clock ::time_point t ) {return std::chrono::duration < double , std::milli > (Clock ::now ()- t ).count (); } 29 30bool mapped (size_t bytes ,void ** h ,void ** d ) { 31if (cudaHostAlloc (h ,bytes ,cudaHostAllocMapped )!= cudaSuccess )return false; 32 std::memset (* h ,0 ,bytes ); 33return cudaHostGetDevicePointer (d ,* h ,0 )== cudaSuccess ; 34} 35 36constexpr int GGML_Q8_0 = 8 ; 37 38}// namespace 39 40Dflash2Drafter ::~Dflash2Drafter () { 41if (device_ < 0 )return ; 42prof_report (); 43prof_free (); 44const OnDevice on_device (device_ ); 45if (cs_ )cudaStreamSynchronize (cs_ ); 46for (cudaGraphExec_t & e :exec_ ) 47if (e )cudaGraphExecDestroy (e ); 48auto fr = [](void * p ) {if (p )cudaFree (p ); }; 49if (h_logq_ )cudaFreeHost (h_logq_ ); 50if (h_logd_ )cudaFreeHost (h_logd_ ); 51fr (rb_q_ );fr (rb_d_ );fr (rb_pos_ ); 52if (!blob_shared_ )fr (blob_ ); 53fr (landing_ );if (dpend_ )cudaFreeHost (dpend_ );fr (tag_ );fr (d_meta_ );fr (xq_ );fr (xil_ );fr (xqp_ );fr (xdp_ );fr (xqc_ );fr (xdc_ );fr (rt_ctx_ );fr (rope_inv_ ); 54for (int l = 0 ;l < 8 ;++ l ) {fr (kring_ [l ]);fr (vring_ [l ]); } 55fr (fcy_ );fr (hctx_ );fr (kc_ );fr (vc_ );fr (h_ );fr (xn_ );fr (xc_ );fr (dyn_ );fr (q_ );fr (qn_ );fr (k_ );fr (v_ );fr (kblk_ );fr (ao_ );fr (o_ ); 56fr (gate_ );fr (up_ );fr (mlp_ );fr (part_ );fr (fn_ );fr (logits_ );fr (topval_ );fr (hsel_ );fr (toptok_ );fr (topscratch_ ); 57if (!dhead_shared_ && !blob_shared_ ) {fr (dvocab_ );fr (dhead_ ); } 58if (h_meta_ )cudaFreeHost (h_meta_ ); 59if (h_out_ )cudaFreeHost (h_out_ ); 60if (cs_ )cudaStreamDestroy (cs_ ); 61if (cs2_ )cudaStreamDestroy (cs2_ ); 62if (ev_fork_ )cudaEventDestroy (ev_fork_ ); 63if (ev_join_ )cudaEventDestroy (ev_join_ ); 64for (cudaEvent_t e :ev_ctx_ )if (e )cudaEventDestroy (e ); 65if (ev_a_ )cudaEventDestroy (ev_a_ ); 66if (ev_b_ )cudaEventDestroy (ev_b_ ); 67} 68 69// STRATA_DF2_PROFILE=1 (measurement only): the round runs without its graph and an event follows every stage; the per-stage averages print at exit 70struct Dflash2Drafter ::Prof { 71 std::vector < cudaEvent_t > ev ; 72 std::vector < std::string > name ; 73 std::vector < std::pair < std::string ,double >> total ; 74int64_t rounds = 0 ; 75}; 76 77void Dflash2Drafter ::prof_free () { 78delete prof_ ; 79prof_ = nullptr ; 80} 81 82// STRATA_DF2_SKIP=attn,head,ctx,mlp,qkvo (measurement only): leaves those parts out of the round, so the graph's GPU time without them can be read 83static bool skip_part (const char * what ) { 84static const std::string list = [] {const char * e = std::getenv ("STRATA_DF2_SKIP" );return std::string (e ?e :"" ); }(); 85return !list .empty ()&& list .find (what )!= std::string::npos ; 86} 87 88void Dflash2Drafter ::stamp (const char * name ) { 89if (!prof_ )return ; 90cudaEvent_t e ; 91cudaEventCreate (& e ); 92cudaEventRecord (e ,cs_ ); 93prof_ -> ev .push_back (e ); 94prof_ -> name .push_back (name ); 95} 96 97void Dflash2Drafter ::prof_collect () { 98if (!prof_ || prof_ -> ev .size ()< 2 )return ; 99cudaStreamSynchronize (cs_ ); 100for (size_t i = 1 ;i < prof_ -> ev .size ();++ i ) { 101float ms = 0 ; 102cudaEventElapsedTime (& ms ,prof_ -> ev [i - 1 ],prof_ -> ev [i ]); 103auto it = std::find_if (prof_ -> total .begin (),prof_ -> total .end (), [& ](const auto & t ) {return t .first == prof_ -> name [i ]; }); 104if (it == prof_ -> total .end ())prof_ -> total .emplace_back (prof_ -> name [i ],ms );else it -> second += ms ; 105 } 106for (cudaEvent_t e :prof_ -> ev )cudaEventDestroy (e ); 107prof_ -> ev .clear (); 108prof_ -> name .clear (); 109++ prof_ -> rounds ; 110} 111 112void Dflash2Drafter ::prof_report ()const { 113if (!prof_ || prof_ -> rounds == 0 )return ; 114double sum = 0 ; 115for (const auto & t :prof_ -> total )sum += t .second ; 116 std::fprintf (stderr ,"strata dflash2 profile (%lld rounds, ms per round, total %.3f):" , (long long )prof_ -> rounds ,sum / (double )prof_ -> rounds ); 117for (const auto & t :prof_ -> total ) std::fprintf (stderr ," %s %.3f" ,t .first .c_str (),t .second / (double )prof_ -> rounds ); 118 std::fputc (10 ,stderr ); 119} 120 121const Dflash2Drafter ::Tensor & Dflash2Drafter ::find (const std::string & name )const { 122for (const Tensor & t :tensors_ ) 123if (t .name == name )return t ; 124throw std::runtime_error ("dflash2: tensor " + name + " is missing from the pack" ); 125} 126 127bool Dflash2Drafter ::load (const std::string & path ,int device , std::string & err ) { 128device_ = device ; 129const OnDevice on_device (device_ ); 130 std::FILE * f = std::fopen (path .c_str (),"rb" ); 131if (f == nullptr ) {err = "dflash2: cannot open " + path ;return false; } 132struct Closer { std::FILE * f ; ~Closer () { std::fclose (f ); } }closer {f }; 133uint32_t hdr [3 ]; 134if (std::fread (hdr ,4 ,3 ,f )!= 3 || std::memcmp (hdr ,"DF2P" ,4 )!= 0 || hdr [1 ]!= 1 ) {err = "dflash2: " + path + " is not a DF2P v1 pack" ;return false; } 135 std::string index (hdr [2 ],' ' ); 136if (std::fread (index .data (),1 ,hdr [2 ],f )!= hdr [2 ]) {err = "dflash2: the pack's index is cut short" ;return false; } 137const long data_off = 12 + (long )hdr [2 ]; 138uint64_t total = 0 ; 139for (size_t i = 0 ;i < index .size ();) { 140const size_t j = index .find ('\n' ,i ); 141if (j == std::string::npos )break ; 142const std::string line = index .substr (i ,j - i ); 143i = j + 1 ; 144char a [256 ],b [64 ],c [256 ]; 145long long v1 ,v2 ,v3 ,v4 ; 146if (std::sscanf (line .c_str (),"cfg %63s %255s" ,b ,c )== 2 ) { 147const std::string key = b ; 148if (key == "hidden" )N_ = std::atoi (c ); 149else if (key == "layers" )L_ = std::atoi (c ); 150else if (key == "heads" )NH_ = std::atoi (c ); 151else if (key == "kv_heads" )NKV_ = std::atoi (c ); 152else if (key == "head_dim" )HD_ = std::atoi (c ); 153else if (key == "inter" )I_ = std::atoi (c ); 154else if (key == "window" )window_ = std::atoi (c ); 155else if (key == "rope_theta" )theta_ = (float ) std::atof (c ); 156else if (key == "eps" )eps_ = (float ) std::atof (c ); 157else if (key == "conv_group" )group_ = std::atoi (c ); 158else if (key == "rank" )rank_ = std::atoi (c ); 159else if (key == "mask_token" )mask_token_ = std::atoi (c ); 160else if (key == "vocab" )vocab_ = std::atoll (c ); 161else if (key == "taps" ) { 162taps_ .clear (); 163for (const char * q = c ;* q ;) {taps_ .push_back (std::atoi (q ));while (* q && * q != ',' )++ q ;if (* q == ',' )++ q ; } 164 } 165 }else if (std::sscanf (line .c_str (),"t %255s %63s %lld %lld %lld %lld" ,a ,b ,& v1 ,& v2 ,& v3 ,& v4 )== 6 ) { 166Tensor t ; 167t .name = a ;t .dtype = b ;t .rows = v1 ;t .cols = v2 ;t .off = (uint64_t )v3 ;t .bytes = (uint64_t )v4 ; 168tensors_ .push_back (t ); 169total = std::max (total ,t .off + t .bytes ); 170 } 171 } 172if (tensors_ .empty ()|| NH_ != 32 || NKV_ != 8 || HD_ != 128 || rank_ != 256 || N_ != 2560 || L_ > 8 || window_ + 16 > kRing ) { 173err = "dflash2: the pack's shape is not the Flash-Next drafter this engine was written for" ; 174return false; 175 } 176if (cudaMalloc ((void ** )& blob_ ,total )!= cudaSuccess ) {err = "dflash2: the pack does not fit in VRAM (" + std::to_string (total >>20 )+ " MiB)" ;return false; } 177vram_ += total ; 178uint64_t max_bytes = 0 ; 179for (const Tensor & t :tensors_ )max_bytes = std::max (max_bytes ,t .bytes ); 180 std::vector < uint8_t > stage (max_bytes ); 181uint8_t * tmp = nullptr ; 182if (cudaMalloc ((void ** )& tmp ,max_bytes )!= cudaSuccess ) {err = "dflash2: upload scratch" ;return false; } 183struct TmpFree {uint8_t * p ; ~TmpFree () {cudaFree (p ); } }tmp_free {tmp }; 184for (const Tensor & t :tensors_ ) { 185#if defined(_WIN32 ) 186_fseeki64 (f ,data_off + (long long )t .off ,SEEK_SET ); 187#else 188fseeko (f ,data_off + (off_t )t .off ,SEEK_SET ); 189#endif 190if (std::fread (stage .data (),1 ,t .bytes ,f )!= t .bytes ) {err = "dflash2: the pack is shorter than its index" ;return false; } 191if (t .dtype == "q8_0" ) {// GGUF blocks -> the tiled qs plane at the tensor's offset, then the d plane (same total bytes) 192if (cudaMemcpy (tmp ,stage .data (),t .bytes ,cudaMemcpyHostToDevice )!= cudaSuccess ) {err = "dflash2: weight upload failed" ;return false; } 193 kernels::df2_q8_tile (tmp ,blob_ + t .off ,blob_ + t .off + (uint64_t )t .rows * (uint64_t )t .cols , (int )t .cols ,t .rows * t .cols /32 ,nullptr ); 194if (cudaDeviceSynchronize ()!= cudaSuccess ) {err = "dflash2: weight conversion failed" ;return false; } 195 }else if (t .dtype == "q4_0" && t .name .find ("_codebook" )!= std::string::npos ) {// the selector's Q4_0 rows stay in block order (read row by row) 196if (cudaMemcpy (blob_ + t .off ,stage .data (),t .bytes ,cudaMemcpyHostToDevice )!= cudaSuccess ) {err = "dflash2: weight upload failed" ;return false; } 197 }else if (t .dtype == "q4_0" ) {// GGML Q4_0 blocks -> the tiled nibble plane at the tensor's offset, then the d plane (same total bytes) 198if (cudaMemcpy (tmp ,stage .data (),t .bytes ,cudaMemcpyHostToDevice )!= cudaSuccess ) {err = "dflash2: weight upload failed" ;return false; } 199 kernels::df2_q4_tile (tmp ,blob_ + t .off ,blob_ + t .off + (uint64_t )t .rows * (uint64_t )t .cols /2 , (int )t .cols ,t .rows * t .cols /32 ,nullptr ); 200if (cudaDeviceSynchronize ()!= cudaSuccess ) {err = "dflash2: weight conversion failed" ;return false; } 201q4_ = true; 202 }else if (cudaMemcpy (blob_ + t .off ,stage .data (),t .bytes ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 203err = "dflash2: weight upload failed" ; 204return false; 205 } 206 } 207if (!make_streams (err ))return false; 208return alloc (err ); 209} 210 211bool Dflash2Drafter ::make_streams (std::string & err ) { 212// the draft round runs while the verifier's async commit still has work on the card: a high-priority stream keeps it from queueing behind that 213// (CUDA by default; on HIP only with STRATA_DF2_PRIO=1, where the engine's other streams keep the default priority) 214int prio_lo = 0 ,prio_hi = 0 ; 215#if defined(STRATA_USE_HIP ) 216static const bool hi_prio = [] {const char * e = std::getenv ("STRATA_DF2_PRIO" );return e && e [0 ]== '1' ; }(); 217if (hi_prio )hipDeviceGetStreamPriorityRange (& prio_lo ,& prio_hi ); 218if (hipStreamCreateWithPriority (& cs_ ,hipStreamNonBlocking ,hi_prio ?prio_hi :0 )!= cudaSuccess || 219hipStreamCreateWithPriority (& cs2_ ,hipStreamNonBlocking ,hi_prio ?prio_hi :0 )!= cudaSuccess ) { 220#else 221static const bool hi_prio = [] {const char * e = std::getenv ("STRATA_DF2_PRIO" );return !(e && e [0 ]== '0' ); }(); 222cudaDeviceGetStreamPriorityRange (& prio_lo ,& prio_hi ); 223if (cudaStreamCreateWithPriority (& cs_ ,cudaStreamNonBlocking ,hi_prio ?prio_hi :0 )!= cudaSuccess || 224cudaStreamCreateWithPriority (& cs2_ ,cudaStreamNonBlocking ,hi_prio ?prio_hi :0 )!= cudaSuccess ) { 225#endif 226err = "dflash2: stream" ; 227return false; 228 } 229for (auto & e :ev_hs_ )cudaEventCreateWithFlags (& e ,cudaEventDisableTiming ); 230if (cudaEventCreateWithFlags (& ev_fork_ ,cudaEventDisableTiming )!= cudaSuccess || cudaEventCreateWithFlags (& ev_join_ ,cudaEventDisableTiming )!= cudaSuccess ) { 231err = "dflash2: events" ; 232return false; 233 } 234for (int l = 0 ;l < 8 ;++ l ) 235if (cudaEventCreateWithFlags (& ev_ctx_ [l ],cudaEventDisableTiming )!= cudaSuccess ) {err = "dflash2: events" ;return false; } 236if (const char * e = std::getenv ("STRATA_DF2_PROFILE" );e && e [0 ]== '1' )prof_ = new Prof (); 237if (const char * e = std::getenv ("STRATA_DF2_TIMING" );e && e [0 ]== '1' ) { 238timing_ = true; 239cudaEventCreate (& ev_a_ ); 240cudaEventCreate (& ev_b_ ); 241 } 242return true; 243} 244 245bool Dflash2Drafter ::alloc (std::string & err ) { 246auto dev = [& ](auto ** p ,size_t n ) { 247using T = std::remove_pointer_t < std::remove_reference_t < decltype(* p )>> ; 248if (cudaMalloc ((void ** )p ,n * sizeof (T ))!= cudaSuccess )return false; 249vram_ += n * sizeof (T ); 250return true; 251 }; 252const size_t B = kRows ; 253bool ok = dev (& d_meta_ ,32 )&& dev (& xq_ , kernels::native_q8_1_bytes (N_ ,kRows )+ 4096 )&& dev (& xil_ , kernels::native_q8_1_il_bytes (N_ ,kRows )+ 4096 )&& dev (& xqp_ , (size_t )5 * N_ * 8 + 4096 )&& dev (& xdp_ , (size_t )5 * N_ /32 * 8 + 64 )&& dev (& xqc_ , (size_t )5 * N_ * 8 + 4096 )&& dev (& xdc_ , (size_t )5 * N_ /32 * 8 + 64 )&& dev (& rt_ctx_ ,2 * B * 128 )&& dev (& rope_inv_ ,64 )&& 254dev (& fcy_ ,B * N_ )&& dev (& hctx_ ,B * N_ )&& dev (& kc_ ,B * NKV_ * HD_ )&& dev (& vc_ ,B * NKV_ * HD_ )&& dev (& h_ ,B * N_ )&& dev (& xn_ ,B * N_ )&& 255dev (& xc_ ,B * N_ )&& dev (& dyn_ ,B * 640 )&& dev (& q_ ,B * NH_ * HD_ )&& dev (& qn_ ,B * NH_ * HD_ )&& dev (& k_ ,B * NKV_ * HD_ )&& dev (& v_ ,B * NKV_ * HD_ )&& 256dev (& kblk_ ,B * NKV_ * HD_ )&& dev (& ao_ ,B * NH_ * HD_ )&& dev (& o_ ,B * N_ )&& dev (& gate_ ,B * I_ )&& dev (& up_ ,B * I_ )&& dev (& mlp_ ,B * N_ )&& 257dev (& part_ , (size_t ) kernels::kDf2MaxChunks * 8 * 32 * 130 )&& dev (& fn_ ,B * N_ )&& dev (& topval_ ,kDrafts * 16 )&& dev (& toptok_ ,kDrafts * 16 )&& 258dev (& hsel_ ,kDrafts * rank_ )&& dev (& topscratch_ , (size_t )kDrafts * kernels::kDf2TopBlocks * kernels::kDf2TopK * 2 ); 259ok = ok && dev (& landing_ , (size_t )kRows * std::max < size_t > (taps_ .size (),1 )* (size_t )N_ ); 260for (int l = 0 ;ok && l < L_ ;++ l )ok = dev (& kring_ [l ], (size_t )kRing * NKV_ * HD_ )&& dev (& vring_ [l ], (size_t )kRing * NKV_ * HD_ ); 261if (!ok ) {err = "dflash2: the drafter's buffers do not fit in VRAM" ;return false; } 262void * hd = nullptr ; 263void * dd = nullptr ; 264if (!mapped (32 * 4 , (void ** )& hd ,& dd )) {err = "dflash2: mapped staging" ;return false; } 265h_meta_ = (int32_t * )hd ; 266m_meta_ = (int32_t * )dd ; 267if (!mapped (64 * 4 ,& hd ,& dd )) {err = "dflash2: mapped output" ;return false; } 268h_out_ = (int32_t * )hd ; 269out_tok_ = (int32_t * )dd ;// the select kernel writes the 7 picks here (host-visible) ... 270out_prob_ = (float * )dd + 16 ;// ... and their probabilities at +16 ints 271rt_blk_ = rt_ctx_ + B * 128 ; 272cudaMemset (rt_ctx_ ,0 ,2 * B * 128 * 4 ); 273 kernels::df2_rope_inv (theta_ ,rope_inv_ ,nullptr ); 274if (cudaMalloc ((void ** )& tag_ , (size_t )kRing * 8 )!= cudaSuccess ) {err = "dflash2: ring tags" ;return false; } 275vram_ += (uint64_t )kRing * 8 ; 276cudaMemset (tag_ ,0xff , (size_t )kRing * 8 );// -1: no slot holds a context row yet 277for (int64_t & t :slot_pos_ )t = -1 ; 278init_ring_log (); 279cudaMemset (xqp_ ,0 , (size_t )5 * N_ * 8 + 4096 ); 280cudaMemset (xdp_ ,0 , ((size_t )5 * N_ /32 * 8 + 64 )* 4 ); 281cudaMemset (xqc_ ,0 , (size_t )5 * N_ * 8 + 4096 ); 282cudaMemset (xdc_ ,0 , ((size_t )5 * N_ /32 * 8 + 64 )* 4 ); 283for (int l = 0 ;l < L_ ;++ l ) {cudaMemset (kring_ [l ],0 , (size_t )kRing * NKV_ * HD_ * 4 );cudaMemset (vring_ [l ],0 , (size_t )kRing * NKV_ * HD_ * 4 ); } 284return cudaDeviceSynchronize ()== cudaSuccess ; 285} 286 287bool Dflash2Drafter ::bind_raw (EmbedFn embed ,const void * head_w ,int head_type ,int64_t head_rows ,const std::vector < int32_t >& vocab , std::string & err ) { 288const OnDevice on_device (device_ ); 289embed_ = std::move (embed ); 290head_w_ = head_w ; 291head_type_ = head_type ; 292n_dvocab_ = head_rows ; 293if (!vocab .empty ()) { 294n_dvocab_ = (int64_t )vocab .size (); 295if (dhead_shared_ ) {// the MTP drafter's copy of the same vocabulary (checked in bind) 296dvocab_ = const_cast < int32_t *> (shared_ .vocab_dev ); 297 }else { 298if (cudaMalloc ((void ** )& dvocab_ ,vocab .size ()* 4 )!= cudaSuccess ) {err = "dflash2: draft vocabulary" ;return false; } 299vram_ += vocab .size ()* 4 ; 300cudaMemcpy (dvocab_ ,vocab .data (),vocab .size ()* 4 ,cudaMemcpyHostToDevice ); 301 } 302 } 303if ((n_dvocab_ + kernels::kDf2TopBlocks - 1 ) / kernels::kDf2TopBlocks > 4096 ) {err = "dflash2: the head has too many rows for the top-k" ;return false; } 304if (!logits_ && cudaMalloc ((void ** )& logits_ , (size_t )kDrafts * (size_t )n_dvocab_ * 4 )!= cudaSuccess ) {err = "dflash2: the draft logits do not fit" ;return false; } 305vram_ += (uint64_t )kDrafts * (uint64_t )n_dvocab_ * 4 ; 306bound_ = true; 307return true; 308} 309 310#ifndef STRATA_DF2_NO_BIND // the split engine (src/split) binds through bind_raw only: bind() copies head rows between cards with the peer API 311bool Dflash2Drafter ::bind (const WeightTable & wt ,const NativeHead * head ,const std::string & vocab_file , std::string & err ,int head_device ) { 312const OnDevice on_device (device_ ); 313if (head == nullptr || !head -> loaded ()) {err = "dflash2: the drafter needs the native head (--native)" ;return false; } 314const WeightRef * we = wt .find ("token_embd.weight" ); 315if (we == nullptr && native_embed ()== nullptr ) {err = "dflash2: token_embd.weight is missing" ;return false; }// (a later stage of a layer split may not carry it: the native table serves) 316EmbedFn embed = [we ](const int32_t * tok ,int n ,float * out ,cudaStream_t cs ) { 317if (const NativeEmbed * ne = native_embed ()) { 318ne -> gather_dev (tok ,n ,out ,cs ); 319 }else if (we != nullptr ) { 320const auto * codes = (const uint8_t * )we -> data ; 321const auto * scales = (const float * ) (codes + we -> codes_bytes ); 322const auto * offsets = we -> has_offset ? (const float * ) (codes + we -> codes_bytes + we -> scales_bytes ) :nullptr ; 323 kernels::embedding_gather_dev (codes ,scales ,offsets ,tok ,n ,we -> ne0 ,we -> code_bits ,we -> code_bias ,we -> group_elems , 324 (uint64_t ) (we -> ne0 / (8 /we -> code_bits )), (uint64_t ) (we -> ne0 /we -> group_elems ),out ,cs ); 325 } 326 }; 327 std::vector < int32_t > vocab ; 328// STRATA_DF2_HEAD=native: the drafter runs its head on the target's own resident head (every vocabulary row, no 213 MiB pruned copy, no vocabulary file read) 329// (a head on another card, a layer split's last stage, is not read in place: the pruned copy is gathered there and copied over, as before) 330const bool head_native = Dflash2Drafter ::head_native ()&& (head_device < 0 || head_device == device_ ); 331if (!vocab_file .empty ()&& !head_native ) { 332if (std::FILE * vf = std::fopen (vocab_file .c_str (),"rb" )) { 333 std::fseek (vf ,0 ,SEEK_END ); 334const long size = std::ftell (vf ); 335 std::fseek (vf ,0 ,SEEK_SET ); 336if (size >=4 && size %4 == 0 ) { 337vocab .resize ((size_t )size /4 ); 338if (std::fread (vocab .data (),4 ,vocab .size (),vf )!= vocab .size ())vocab .clear (); 339 } 340 std::fclose (vf ); 341 } 342 } 343const void * hw = head -> weights (); 344const int64_t row_bytes = (int64_t )head -> row_bytes (); 345int64_t head_rows = row_bytes > 0 ? (int64_t ) (head -> weight_bytes () / (uint64_t )row_bytes ) :0 ; 346if (!vocab .empty ()&& shared_ .rows != nullptr && !std::getenv ("STRATA_DF2_SHARE_HEAD_OFF" )&& shared_ .type == head -> type ()&& 347shared_ .n == (int64_t )vocab .size ()&& shared_ .vocab_host != nullptr && * shared_ .vocab_host == vocab && shared_ .vocab_dev != nullptr ) { 348// DF-05: the MTP drafter gathered these very rows (same vocabulary ids in the same order, the main head's own layout and type): use them 349dhead_ = const_cast < uint8_t *> (shared_ .rows ); 350dhead_shared_ = true; 351hw = dhead_ ; 352head_rows = (int64_t )vocab .size (); 353 }else if (!vocab .empty ()&& head_device >=0 && head_device != device_ ) { 354// the head is on another card: gather the subset's rows there, copy them over once 355const size_t bytes = (size_t ) ((int64_t )vocab .size ()* row_bytes ); 356uint8_t * tmp = nullptr ; 357int32_t * dv = nullptr ; 358 { 359const OnDevice on_head (head_device ); 360if (cudaMalloc ((void ** )& dv ,vocab .size ()* 4 )!= cudaSuccess || cudaMalloc ((void ** )& tmp ,bytes )!= cudaSuccess ) { 361if (dv )cudaFree (dv ); 362err = "dflash2: the draft vocabulary's head rows do not fit on the head's card" ; 363return false; 364 } 365cudaMemcpy (dv ,vocab .data (),vocab .size ()* 4 ,cudaMemcpyHostToDevice ); 366 kernels::gather_rows ((const uint8_t * )hw ,row_bytes ,dv , (int64_t )vocab .size (),tmp ,nullptr ); 367cudaDeviceSynchronize (); 368cudaFree (dv ); 369 } 370if (cudaMalloc ((void ** )& dhead_ ,bytes )!= cudaSuccess ) { 371 {const OnDevice on_head (head_device );cudaFree (tmp ); } 372err = "dflash2: the draft vocabulary's head rows do not fit" ; 373return false; 374 } 375const cudaError_t pe = cudaMemcpyPeer (dhead_ ,device_ ,tmp ,head_device ,bytes ); 376 {const OnDevice on_head (head_device );cudaFree (tmp ); } 377if (pe != cudaSuccess ) {err = std::string ("dflash2: the head rows' copy to the drafter's card: " )+ cudaGetErrorString (pe );return false; } 378vram_ += bytes ; 379hw = dhead_ ; 380head_rows = (int64_t )vocab .size (); 381 }else if (!vocab .empty ()) { 382int32_t * dv = nullptr ; 383if (cudaMalloc ((void ** )& dv ,vocab .size ()* 4 )!= cudaSuccess || cudaMalloc ((void ** )& dhead_ , (size_t ) ((int64_t )vocab .size ()* row_bytes ))!= cudaSuccess ) { 384if (dv )cudaFree (dv ); 385err = "dflash2: the draft vocabulary's head rows do not fit" ; 386return false; 387 } 388cudaMemcpy (dv ,vocab .data (),vocab .size ()* 4 ,cudaMemcpyHostToDevice ); 389 kernels::gather_rows ((const uint8_t * )hw ,row_bytes ,dv , (int64_t )vocab .size (),dhead_ ,nullptr ); 390cudaDeviceSynchronize (); 391cudaFree (dv ); 392vram_ += (uint64_t ) ((int64_t )vocab .size ()* row_bytes ); 393hw = dhead_ ; 394head_rows = (int64_t )vocab .size (); 395 } 396if (!bind_raw (embed ,hw ,head -> type (),head_rows ,vocab ,err ))return false; 397 std::fprintf (stderr ,"strata dflash2: %lld-token draft head (%.1f MiB%s), drafter %.0f MiB of VRAM (%s weights)\n" , (long long )n_dvocab_ , 398 (double ) (n_dvocab_ * row_bytes ) /1048576.0 ,dhead_shared_ ?", the MTP drafter's copy, no second one" :"" , (double )vram_ /1048576.0 ,q4_ ?"Q4_0" :"Q8_0" ); 399// the pack's selector codebooks as Q4_0 rows (tools/dflash2_pack.py --q4_0-selector; strata_control/drafting.py reads this text from the program to know it can use that pack) 400if (find ("candidate_selector.predecessor_codebook" ).dtype == "q4_0" ) 401 std::fprintf (stderr ,"strata dflash2: selector codebooks: Q4_0 rows (about 174 MiB less than bf16)\n" ); 402return true; 403} 404 405#endif // STRATA_DF2_NO_BIND 406void Dflash2Drafter ::gemm (std::initializer_list < const char *> names , std::initializer_list < float *> outs ,int ncols ,cudaStream_t cs ,const uint8_t * xq ,const float * xd ) { 407 kernels::Df2Mat mats [3 ]; 408int n = 0 ,n_in = 0 ; 409auto o = outs .begin (); 410for (const char * name :names ) { 411const Tensor & t = find (name ); 412mats [n ]= kernels::Df2Mat {blob_ + t .off ,* o ++ , (int )t .rows ,t .dtype == "q4_0" }; 413if (n == 0 )n_in = (int )t .cols ; 414++ n ; 415 } 416 kernels::df2_gemm (mats ,n ,xq ,xd ,n_in ,ncols ,cs ); 417} 418 419// The part of a context update after the activations are quantized: per layer the keys and values (projection, k-norm, rope, ring write). Also what a ring 420// rebuild runs over logged rows: `xq` / `xd` are then the log's codes and scales, `pos` the rows' positions (device), rt_ctx_ their rope table. 421bool Dflash2Drafter ::record_kv (int n ,cudaStream_t cs ,const uint8_t * xq ,const float * xd ,const int32_t * pos , std::string & err ) { 422using namespace kernels ; 423try { 424for (int l = 0 ;l < L_ ;++ l ) { 425const std::string p = "layers." + std::to_string (l )+ "." ; 426const std::string kp = p + "self_attn.k_proj.weight" ,vp = p + "self_attn.v_proj.weight" ; 427gemm ({kp .c_str (),vp .c_str ()}, {kc_ ,vc_ },n ,cs ,xq ,xd ); 428stamp ("gemm:kp" ); 429df2_kv_ring (kc_ ,vc_ ,f32 (p + "self_attn.k_norm.weight" ),pos ,rt_ctx_ ,kring_ [l ],vring_ [l ],kRing ,n ,NKV_ ,eps_ ,cs ,tag_ ,d_meta_ + 18 ); 430stamp ("df2_kv_ring" ); 431if (fork_ )cudaEventRecord (ev_ctx_ [l ],cs );// layer l's keys and values are in the ring 432 } 433 }catch (const std::exception & e ) { 434err = e .what (); 435return false; 436 } 437return true; 438} 439 440bool Dflash2Drafter ::record_context (const float * taps ,int n ,cudaStream_t cs , std::string & err ,bool rope ) { 441using namespace kernels ; 442if (skip_part ("ctx" ))return true; 443try { 444const int tap_n = (int )taps_ .size ()* N_ ; 445if (rope )df2_rope_table_inv (d_meta_ + 0 ,n ,rope_inv_ ,rt_ctx_ ,cs ); 446stamp ("df2_rope_table" ); 447df2_quant_rows (taps ,tap_n ,n ,xqc_ ,xdc_ ,cs ); 448stamp ("df2_quant_rows" ); 449gemm ({"fc.weight" }, {fcy_ },n ,cs ,xqc_ ,xdc_ ); 450stamp ("gemm:fc" ); 451df2_rms_quant (fcy_ ,f32 ("hidden_norm.weight" ),nullptr ,n ,N_ ,eps_ ,xqc_ ,xdc_ ,cs ); 452stamp ("df2_rms_quant" ); 453if (log_on_ ) {// the ring log: these codes and scales are all the K/V of the five layers are made from (see begin_request) 454cudaMemcpyAsync (h_logq_ ,xqc_ , (size_t )n * N_ ,cudaMemcpyDeviceToHost ,cs ); 455cudaMemcpyAsync (h_logd_ ,xdc_ , (size_t )n * (N_ /32 )* 4 ,cudaMemcpyDeviceToHost ,cs ); 456 } 457if (!record_kv (n ,cs ,xqc_ ,xdc_ ,d_meta_ + 0 ,err ))return false; 458 }catch (const std::exception & e ) { 459err = e .what (); 460return false; 461 } 462return true; 463} 464 465bool Dflash2Drafter ::record_block (cudaStream_t cs , std::string & err ,bool rope ) { 466using namespace kernels ; 467try { 468const int B = kRows ; 469if (rope )df2_rope_table_inv (d_meta_ + 8 ,B ,rope_inv_ ,rt_blk_ ,cs ); 470stamp ("df2_rope_table" ); 471embed_ (d_meta_ + 24 ,B ,h_ ,cs ); 472stamp ("embed_" ); 473df2_rms_quant (h_ ,f32 ("layers.0.input_layernorm.weight" ),xn_ ,B ,N_ ,eps_ ,xqp_ ,xdp_ ,cs ); 474stamp ("df2_rms_quant" ); 475for (int l = 0 ;l < L_ ;++ l ) { 476const std::string p = "layers." + std::to_string (l )+ "." ; 477const float * base_a = f32 (p + "attention_conv.base_kernel" ); 478const float * base_m = f32 (p + "mlp_conv.base_kernel" ); 479const std::string akp = p + "attention_conv.kernel_projection.weight" ,mkp = p + "mlp_conv.kernel_projection.weight" ; 480const std::string qp = p + "self_attn.q_proj.weight" ,kp = p + "self_attn.k_proj.weight" ,vp = p + "self_attn.v_proj.weight" ; 481const std::string gp = p + "mlp.gate_proj.weight" ,up = p + "mlp.up_proj.weight" ; 482const std::string op = p + "self_attn.o_proj.weight" ; 483if (!skip_part ("tiny" ))gemm ({akp .c_str ()}, {dyn_ },B ,cs ,xqp_ ,xdp_ ); 484stamp ("gemm:akp" ); 485if (!skip_part ("small" ))df2_conv_quant (xn_ ,dyn_ ,640 ,base_a ,B ,N_ ,group_ ,xqp_ ,xdp_ ,cs ); 486stamp ("df2_conv_quant" ); 487if (!skip_part ("qkvo" ))gemm ({qp .c_str (),kp .c_str (),vp .c_str ()}, {q_ ,k_ ,v_ },B ,cs ,xqp_ ,xdp_ ); 488stamp ("gemm:qp" ); 489if (!skip_part ("small" ))df2_norm_rope_qk (q_ ,k_ ,f32 (p + "self_attn.q_norm.weight" ),f32 (p + "self_attn.k_norm.weight" ),rt_blk_ ,qn_ ,kblk_ ,B ,NH_ ,NKV_ ,eps_ ,cs ); 490stamp ("df2_norm_rope_qk" ); 491if (fork_ )cudaStreamWaitEvent (cs ,ev_ctx_ [l ],0 );// the context update has written this layer's ring 492if (!skip_part ("attn" ))df2_attention (qn_ ,kring_ [l ],vring_ [l ],kblk_ ,v_ ,d_meta_ + 17 ,kRing ,window_ ,part_ ,xqp_ ,xdp_ ,cs ,tag_ ,d_meta_ + 18 ); 493stamp ("df2_attention" ); 494if (!skip_part ("qkvo" ))gemm ({op .c_str ()}, {o_ },B ,cs ,xqp_ ,xdp_ ); 495stamp ("gemm:o_proj" ); 496if (!skip_part ("small" ))df2_conv_rms_quant (o_ ,dyn_ + 320 ,640 ,base_a + 2 * N_ ,h_ ,f32 (p + "post_attention_layernorm.weight" ),xn_ ,B ,N_ ,group_ ,eps_ ,xqp_ ,xdp_ ,cs ); 497stamp ("df2_conv_rms_quant" ); 498if (!skip_part ("tiny" ))gemm ({mkp .c_str ()}, {dyn_ },B ,cs ,xqp_ ,xdp_ ); 499stamp ("gemm:mkp" ); 500if (!skip_part ("small" ))df2_conv_quant (xn_ ,dyn_ ,640 ,base_m ,B ,N_ ,group_ ,xqp_ ,xdp_ ,cs ); 501stamp ("df2_conv_quant" ); 502if (!skip_part ("mlp" ))gemm ({gp .c_str (),up .c_str ()}, {gate_ ,up_ },B ,cs ,xqp_ ,xdp_ ); 503stamp ("gemm:gp" ); 504if (!skip_part ("small" ))df2_swiglu_quant (gate_ ,up_ ,B ,I_ ,xqp_ ,xdp_ ,cs ); 505stamp ("df2_swiglu_quant" ); 506if (!skip_part ("mlp" ))gemm ({(p + "mlp.down_proj.weight" ).c_str ()}, {mlp_ },B ,cs ,xqp_ ,xdp_ ); 507stamp ("gemm:mlp.down_proj" ); 508// the next layer's input norm, or after the last layer the final norm (-> fn_, the rows the head and the selector read) 509const std::string next_gamma = l + 1 < L_ ?"layers." + std::to_string (l + 1 )+ ".input_layernorm.weight" : std::string ("norm.weight" ); 510if (!skip_part ("small" ))df2_conv_rms_quant (mlp_ ,dyn_ + 320 ,640 ,base_m + 2 * N_ ,h_ ,f32 (next_gamma ),l + 1 < L_ ?xn_ :fn_ ,B ,N_ ,group_ ,eps_ ,xqp_ ,xdp_ ,cs ); 511stamp ("df2_conv_rms_quant" ); 512 } 513native_quantize_q8_1 (fn_ + N_ ,xq_ ,N_ ,ndraft_ ,cs );// rows 1..7, the head's format 514df2_quant_rows (fn_ + N_ ,N_ ,ndraft_ ,xqp_ ,xdp_ ,cs );// and the selector projection's 515const bool hs_fork = fork_ && cs2_ != nullptr && ev_hs_ [0 ]!= nullptr ;// the selector's projection beside the head, the top-k and their launches 516if (hs_fork ) { 517cudaEventRecord (ev_hs_ [0 ],cs ); 518cudaStreamWaitEvent (cs2_ ,ev_hs_ [0 ],0 ); 519gemm ({"candidate_selector.hidden_projection.weight" }, {hsel_ },ndraft_ ,cs2_ ,xqp_ ,xdp_ ); 520cudaEventRecord (ev_hs_ [1 ],cs2_ ); 521 } 522if (!skip_part ("head" )) { 523// the verify window's head kernel (interleaved activations, rows a warp by the card's table): bitwise native_mmvq's output, so the drafts are the same 524static const bool il_on = [] {const char * e = std::getenv ("STRATA_DF2_HEAD_IL" );return !(e && e [0 ]== '0' ); }(); 525if (il_on && native_mmvq_il_supported (head_type_ ,ndraft_ , (int )n_dvocab_ )) { 526native_q8_1_interleave (xq_ ,xil_ ,N_ ,ndraft_ ,cs ); 527native_mmvq_il (head_type_ ,head_w_ ,xq_ ,xil_ ,logits_ ,N_ , (int )n_dvocab_ ,ndraft_ ,cs ); 528 }else 529native_mmvq (head_type_ ,head_w_ ,xq_ ,logits_ ,N_ , (int )n_dvocab_ ,ndraft_ ,cs ); 530 } 531stamp ("native_mmvq" ); 532df2_topk (logits_ , (int )n_dvocab_ ,dvocab_ ,ndraft_ ,topscratch_ ,topval_ ,toptok_ ,cs ); 533stamp ("df2_topk" ); 534if (hs_fork )cudaStreamWaitEvent (cs ,ev_hs_ [1 ],0 ); 535else gemm ({"candidate_selector.hidden_projection.weight" }, {hsel_ },ndraft_ ,cs ,xqp_ ,xdp_ ); 536stamp ("gemm:candidate_selector.hidden_projection" ); 537df2_select (hsel_ ,topval_ ,toptok_ ,reinterpret_cast < const uint16_t *> (blob_ + find ("candidate_selector.predecessor_codebook" ).off ), 538reinterpret_cast < const uint16_t *> (blob_ + find ("candidate_selector.successor_codebook" ).off ),rank_ ,ndraft_ ,d_meta_ + 16 ,out_tok_ , 539out_prob_ ,cs ,find ("candidate_selector.predecessor_codebook" ).dtype == "q4_0" ); 540 }catch (const std::exception & e ) { 541err = e .what (); 542return false; 543 } 544return true; 545} 546 547bool Dflash2Drafter ::capture (int n ,const float * taps , std::string & err ) { 548if (exec_ [n ])return true; 549if (cudaStreamBeginCapture (cs_ ,cudaStreamCaptureModeThreadLocal )!= cudaSuccess ) {err = "dflash2: begin capture" ;return false; } 550 kernels::copy_i32_from_mapped (d_meta_ ,m_meta_ ,32 ,cs_ ); 551 kernels::df2_rope_table_inv (d_meta_ ,16 ,rope_inv_ ,rt_ctx_ ,cs_ );// the context rows' and the block rows' tables in one launch, before the branches split 552// the context update (fc, the keys and values) and the block's front run side by side: they meet before each layer's attention 553// measured: -0.3 ms a round on an RTX 3060, +0.0..0.7 on a Strix Halo (gfx1151), so the HIP builds keep one stream (STRATA_DF2_FORK=1 / 0 overrides) 554#if defined(STRATA_USE_HIP ) 555static const bool fork_default = false; 556#else 557static const bool fork_default = true; 558#endif 559static const bool fork_on = [] {const char * e = std::getenv ("STRATA_DF2_FORK" );return e && e [0 ] ?e [0 ]== '1' :fork_default ; }(); 560fork_ = fork_on && prof_ == nullptr && cs2_ != nullptr ; 561if (fork_ ) { 562cudaEventRecord (ev_fork_ ,cs_ ); 563cudaStreamWaitEvent (cs2_ ,ev_fork_ ,0 ); 564 } 565bool ok = record_context (taps ,n ,fork_ ?cs2_ :cs_ ,err , false); 566if (fork_ )cudaEventRecord (ev_join_ ,cs2_ ); 567if (ok )ok = record_block (cs_ ,err , false); 568if (fork_ )cudaStreamWaitEvent (cs_ ,ev_join_ ,0 ); 569fork_ = false; 570cudaGraph_t graph = nullptr ; 571const cudaError_t ce = cudaStreamEndCapture (cs_ ,& graph ); 572if (!ok ) {if (graph )cudaGraphDestroy (graph );return false; } 573if (ce != cudaSuccess || cudaGraphInstantiate (& exec_ [n ],graph ,0 )!= cudaSuccess ) { 574if (graph )cudaGraphDestroy (graph ); 575err = std::string ("dflash2: capture: " )+ cudaGetErrorString (ce ); 576return false; 577 } 578cudaGraphDestroy (graph ); 579cudaGraphUpload (exec_ [n ],cs_ ); 580cudaStreamSynchronize (cs_ ); 581return true; 582} 583 584bool Dflash2Drafter ::clone_alloc (const Dflash2Drafter & parent , std::string & err ) { 585if (parent .blob_ == nullptr ) {err = "dflash2: the parent drafter has no pack loaded" ;return false; } 586device_ = parent .device_ ; 587const OnDevice on_device (device_ ); 588N_ = parent .N_ ;L_ = parent .L_ ;NH_ = parent .NH_ ;NKV_ = parent .NKV_ ;HD_ = parent .HD_ ;I_ = parent .I_ ;window_ = parent .window_ ; 589group_ = parent .group_ ;rank_ = parent .rank_ ;mask_token_ = parent .mask_token_ ;theta_ = parent .theta_ ;eps_ = parent .eps_ ; 590taps_ = parent .taps_ ;vocab_ = parent .vocab_ ;q4_ = parent .q4_ ;tensors_ = parent .tensors_ ; 591blob_ = parent .blob_ ;blob_shared_ = true; 592return make_streams (err )&& alloc (err ); 593} 594 595bool Dflash2Drafter ::clone_bind (const Dflash2Drafter & parent , std::string & err ) { 596if (!parent .bound_ || !blob_shared_ ) {err = "dflash2: the parent drafter is not bound" ;return false; } 597const OnDevice on_device (device_ ); 598embed_ = parent .embed_ ;head_w_ = parent .head_w_ ;head_type_ = parent .head_type_ ;n_dvocab_ = parent .n_dvocab_ ; 599dvocab_ = parent .dvocab_ ;dhead_ = parent .dhead_ ;dhead_shared_ = true; 600ndraft_ = parent .ndraft_ ; 601if (cudaMalloc ((void ** )& logits_ , (size_t )kDrafts * (size_t )n_dvocab_ * 4 )!= cudaSuccess ) {err = "dflash2: the slot drafter's draft logits do not fit" ;return false; } 602vram_ += (uint64_t )kDrafts * (uint64_t )n_dvocab_ * 4 ; 603bound_ = true; 604return true; 605} 606 607bool Dflash2Drafter ::copy_state_from (Dflash2Drafter & src , std::string & err ) { 608if (src .device_ != device_ || src .L_ != L_ || src .NKV_ != NKV_ ) {err = "dflash2: the two drafters are not alike" ;return false; } 609if (!src .context_wait (err )|| !context_wait (err ))return false; 610const OnDevice on_device (device_ ); 611if (cudaStreamSynchronize (src .cs_ )!= cudaSuccess || cudaStreamSynchronize (cs_ )!= cudaSuccess ) {err = "dflash2: sync before a state copy" ;return false; } 612const size_t ring_bytes = (size_t )kRing * NKV_ * HD_ * 4 ; 613for (int l = 0 ;l < L_ ;++ l ) 614if (cudaMemcpyAsync (kring_ [l ],src .kring_ [l ],ring_bytes ,cudaMemcpyDeviceToDevice ,cs_ )!= cudaSuccess || 615cudaMemcpyAsync (vring_ [l ],src .vring_ [l ],ring_bytes ,cudaMemcpyDeviceToDevice ,cs_ )!= cudaSuccess ) {err = "dflash2: ring copy" ;return false; } 616if (cudaMemcpyAsync (tag_ ,src .tag_ , (size_t )kRing * 8 ,cudaMemcpyDeviceToDevice ,cs_ )!= cudaSuccess ) {err = "dflash2: tag copy" ;return false; } 617if (cudaStreamSynchronize (cs_ )!= cudaSuccess ) {err = std::string ("dflash2: state copy: " )+ cudaGetErrorString (cudaGetLastError ());return false; } 618copy_log_state_from (src );// history, the log (shared copy-on-write), the tag shadow, the epoch, ring_hi_ and have_ctx_ 619return true; 620} 621 622float * Dflash2Drafter ::defer_rows (int64_t pos0 ,int n , std::string & err ) { 623if (dpend_ == nullptr ) { 624const OnDevice on_device (device_ ); 625if (cudaHostAlloc ((void ** )& dpend_ , (size_t )kRing2048 * taps_ .size ()* (size_t )N_ * 4 ,cudaHostAllocPortable )!= cudaSuccess ) { 626 (void )cudaGetLastError (); 627dpend_ = nullptr ; 628err = "dflash2: the deferred-rows buffer does not fit in pinned memory" ; 629return nullptr ; 630 } 631 } 632if (!has_deferred ()|| pos0 != dpend_hi_ ) {dpend_lo_ = pos0 ;dpend_hi_ = pos0 ; } 633dpend_hi_ = pos0 + n ; 634if (dpend_hi_ - dpend_lo_ > kRing2048 )dpend_lo_ = dpend_hi_ - kRing2048 ; 635n_deferred_rows += n ; 636return dpend_ + (size_t ) (pos0 %kRing2048 )* (size_t ) (taps_ .size ()* (size_t )N_ ); 637} 638 639bool Dflash2Drafter ::catch_up (int64_t upto , std::string & err ) { 640if (!has_deferred ())return true; 641const Clock ::time_point t0 = Clock ::now (); 642const OnDevice on_device (device_ ); 643const size_t row = taps_ .size ()* (size_t )N_ ; 644int64_t from = std::max < int64_t > (dpend_lo_ ,upto - 2047 ); 645upto = std::min < int64_t > (upto ,dpend_hi_ ); 646int64_t replayed = 0 ; 647while (from < upto ) { 648const int m = (int ) std::min < int64_t > (kRows ,upto - from ); 649if (!context_wait (err ))return false; 650for (int i = 0 ;i < m ;++ i )// (the held run wraps at 2048 positions: row by row) 651if (cudaMemcpyAsync (landing_ + (size_t )i * row ,dpend_ + (size_t ) ((from + i ) %kRing2048 )* row ,row * 4 ,cudaMemcpyHostToDevice ,cs_ )!= cudaSuccess ) { 652err = "dflash2: the deferred rows' upload" ; 653return false; 654 } 655if (!context (landing_ ,m ,from ,err ))return false;// (waits for the stream, so the next chunk may reuse the landing) 656from += m ; 657replayed += m ; 658 } 659dpend_lo_ = std::max < int64_t > (upto ,dpend_lo_ ); 660if (dpend_lo_ >=dpend_hi_ )dpend_lo_ = dpend_hi_ = 0 ; 661++ n_catchups ; 662n_catchup_rows += replayed ; 663ms_catchup += ms_since (t0 ); 664return true; 665} 666 667void Dflash2Drafter ::set_max_drafts (int n ) { 668n = std::max (1 , std::min (n , (int )kDrafts )); 669if (n == ndraft_ )return ; 670const OnDevice on_device (device_ ); 671cudaDeviceSynchronize (); 672for (auto & e :exec_ ) 673if (e ) {cudaGraphExecDestroy (e );e = nullptr ; } 674graph_taps_ = nullptr ; 675ndraft_ = n ; 676} 677 678bool Dflash2Drafter ::prepare (const float * taps , std::string & err ) { 679if (!bound_ ) {err = "dflash2: not bound" ;return false; } 680if (prof_ != nullptr )return true;// the profile runs without graphs 681const OnDevice on_device (device_ ); 682const Clock ::time_point t0 = Clock ::now (); 683for (int i = 0 ;i < 8 ;++ i )h_meta_ [i ]= i ; 684for (int n = 1 ;n <=kRows ;++ n ) 685if (!capture (n ,taps ,err ))return false; 686graph_taps_ = taps ; 687ms_capture = ms_since (t0 ); 688return true; 689} 690 691// ---- ring log ----------------------------------------------------------------------------------------------------------------------------------------- 692// The ring holds the last 2064 positions of the lineage it was filled for. Resuming a prompt below the highest position written (a repeated or rewound 693// prefix, a parked conversation brought back) leaves the part of the first draft's window [n - 2047, resume) either overwritten by the later positions 694// (the slots are position % 2064) or never written for this lineage. The drafts are then poor until the window refills, and the engine said nothing for the 695// first kind. The K/V rows are a function of the quantized hidden rows (codes and block scales after hidden_norm) alone, so those rows are logged as the 696// updates make them (2.9 KB a position; the K/V is 40 KB and the taps 51 KB), per lineage, and a rebuild runs record_kv over them: the same kernels on the 697// same bytes, so the rebuilt K/V rows are bitwise those of the original update. 698bool Dflash2Drafter ::Lineage ::logged (int64_t pos )const { 699const size_t c = (size_t ) (pos /kLogChunk ); 700return pos >=0 && c < chunks .size ()&& chunks [c ]&& chunks [c ]-> ok [(size_t ) (pos %kLogChunk )]!= 0 ; 701} 702 703uint64_t Dflash2Drafter ::Lineage ::bytes ()const { 704uint64_t b = (uint64_t )hist .capacity ()* 4 ; 705for (const auto & c :chunks ) 706if (c )b += c -> q .size ()+ c -> d .size ()* 4 + c -> ok .size (); 707return b ; 708} 709 710Dflash2Drafter ::LogChunk & Dflash2Drafter ::Lineage ::writable (size_t chunk ) { 711if (chunks .size () <=chunk )chunks .resize (chunk + 1 ); 712if (!chunks [chunk ]) { 713auto c = std::make_shared < LogChunk > (); 714c -> q .assign ((size_t )kLogChunk * 2560 ,0 ); 715c -> d .assign ((size_t )kLogChunk * 80 ,0.0f ); 716c -> ok .assign ((size_t )kLogChunk ,0 ); 717chunks [chunk ]= std::move (c ); 718 }else if (chunks [chunk ].use_count ()> 1 ) { 719chunks [chunk ]= std::make_shared < LogChunk > (* chunks [chunk ]);// copy on write: a stashed copy keeps the old rows 720 } 721return * chunks [chunk ]; 722} 723 724void Dflash2Drafter ::Lineage ::truncate (int64_t keep ) { 725keep = std::max < int64_t > (0 ,keep ); 726const size_t c0 = (size_t ) (keep /kLogChunk ); 727for (size_t c = c0 + 1 ;c < chunks .size ();++ c )chunks [c ].reset (); 728if (chunks .size ()> c0 + 1 )chunks .resize (c0 + 1 ); 729if (c0 < chunks .size ()&& chunks [c0 ]) { 730if (keep %kLogChunk == 0 ) { 731chunks [c0 ].reset (); 732 }else { 733LogChunk & ch = writable (c0 ); 734for (int i = (int ) (keep %kLogChunk );i < kLogChunk ;++ i )ch .ok [(size_t )i ]= 0 ; 735 } 736 } 737} 738 739uint64_t Dflash2Drafter ::ring_log_bytes ()const {return cur_ .bytes (); } 740uint64_t Dflash2Drafter ::ring_stash_bytes ()const { 741uint64_t b = 0 ; 742for (const Lineage & l :stash_ )b += l .bytes (); 743return b ; 744} 745 746// The log is OFF until this has allocated its pinned staging: a drafter that never ran alloc() (a --parallel slot's clone) keeps the old behaviour instead of 747// copying into a null staging buffer. Callable again by a clone's allocation, on the drafter's device. 748void Dflash2Drafter ::init_ring_log () { 749const OnDevice on_device (device_ ); 750for (int64_t & t :slot_pos_ )t = -1 ; 751const char * off = std::getenv ("STRATA_DF2_RING_LOG" ); 752if (off && off [0 ]== '0' ) {log_on_ = false;return ; } 753if (const char * e = std::getenv ("STRATA_DF2_LOG_MIB" );e && e [0 ])stash_budget_ = (uint64_t ) std::max (0 , std::atoi (e )) <<20 ; 754if (h_logq_ == nullptr && cudaHostAlloc ((void ** )& h_logq_ , (size_t )kRows * N_ ,cudaHostAllocDefault )!= cudaSuccess )h_logq_ = nullptr ; 755if (h_logd_ == nullptr && cudaHostAlloc ((void ** )& h_logd_ , (size_t )kRows * (N_ /32 )* 4 ,cudaHostAllocDefault )!= cudaSuccess )h_logd_ = nullptr ; 756log_on_ = h_logq_ != nullptr && h_logd_ != nullptr ; 757if (!log_on_ ) { 758 (void )cudaGetLastError (); 759 std::fprintf (stderr ,"strata dflash2: the ring log's staging does not fit in pinned memory: the log is off\n" ); 760 } 761} 762 763void Dflash2Drafter ::reset () { 764have_ctx_ = 0 ; 765cur_ = Lineage {}; 766stash_ .clear (); 767invalidate_ring (); 768} 769 770void Dflash2Drafter ::copy_log_state_from (const Dflash2Drafter & src ) { 771cur_ .hist = src .cur_ .hist ; 772cur_ .chunks = src .cur_ .chunks ; 773 std::memcpy (slot_pos_ ,src .slot_pos_ ,sizeof (slot_pos_ )); 774epoch_ = src .epoch_ ; 775ring_hi_ = src .ring_hi_ ; 776have_ctx_ = src .have_ctx_ ; 777} 778 779void Dflash2Drafter ::invalidate_ring () { 780++ epoch_ ; 781ring_hi_ = 0 ; 782for (int64_t & t :slot_pos_ )t = -1 ; 783} 784 785void Dflash2Drafter ::stash_push (Lineage && l ) { 786if (!log_on_ || stash_budget_ == 0 || l .hist .size ()< 128 || l .chunks .empty ())return ; 787stash_ .push_back (std::move (l )); 788++ ring_stats .stash_stores ; 789uint64_t total = ring_stash_bytes (); 790while (!stash_ .empty ()&& total > stash_budget_ ) { 791total -= std::min (total ,stash_ .front ().bytes ()); 792stash_ .pop_front (); 793++ ring_stats .stash_evictions ; 794 } 795} 796 797void Dflash2Drafter ::log_stage (int64_t pos0 ,int n ) { 798if (!log_on_ )return ; 799pend_pos0_ = pos0 ; 800pend_n_ = n ; 801for (int i = 0 ;i < n ;++ i )slot_pos_ [(size_t ) ((pos0 + i ) %kRing )]= ((int64_t )epoch_ <<32 ) | (pos0 + i ); 802} 803 804void Dflash2Drafter ::log_flush () { 805if (!log_on_ || pend_pos0_ < 0 )return ; 806for (int i = 0 ;i < pend_n_ ;++ i ) { 807const int64_t pos = pend_pos0_ + i ; 808LogChunk & ch = cur_ .writable ((size_t ) (pos /kLogChunk )); 809const size_t r = (size_t ) (pos %kLogChunk ); 810 std::memcpy (& ch .q [r * 2560 ],h_logq_ + (size_t )i * 2560 ,2560 ); 811 std::memcpy (& ch .d [r * 80 ],h_logd_ + (size_t )i * 80 ,80 * sizeof (float )); 812ch .ok [r ]= 1 ; 813 } 814pend_pos0_ = -1 ; 815} 816 817bool Dflash2Drafter ::rebuild (int64_t lo ,int64_t hi ,int64_t * rebuilt ,int64_t * missing , std::string & err ) { 818* rebuilt = 0 ; 819* missing = 0 ; 820 std::vector < int32_t > pos ; 821for (int64_t p = lo ;p < hi ;++ p ) { 822if (slot_pos_ [(size_t ) (p %kRing )]== (((int64_t )epoch_ <<32 ) |p ))continue ;// the ring already holds this row 823if (cur_ .logged (p ))pos .push_back ((int32_t )p ); 824else { 825if (++* missing <=8 && std::getenv ("STRATA_DF2_RING_STATS" )!= nullptr ) std::fprintf (stderr ,"strata dflash2 ring: position %lld was never logged (hist %zu)\n" , (long long )p ,cur_ .hist .size ()); 826 } 827 } 828if (pos .empty ())return true; 829const OnDevice on_device (device_ ); 830const size_t rows = pos .size (); 831const size_t cap = (size_t )kRing ;// a window is at most 2048 rows 832if (rb_q_ == nullptr ) { 833if (cudaMalloc ((void ** )& rb_q_ , (cap + kRows )* 2560 )!= cudaSuccess || cudaMalloc ((void ** )& rb_d_ , (cap + kRows )* 80 * sizeof (float ))!= cudaSuccess || 834cudaMalloc ((void ** )& rb_pos_ , (cap + kRows )* sizeof (int32_t ))!= cudaSuccess ) { 835if (rb_q_ )cudaFree (rb_q_ ); 836if (rb_d_ )cudaFree (rb_d_ ); 837rb_q_ = nullptr ;rb_d_ = nullptr ;rb_pos_ = nullptr ; 838 (void )cudaGetLastError (); 839err = "dflash2: the ring rebuild's scratch does not fit" ; 840return false; 841 } 842cudaMemset (rb_q_ ,0 , (cap + kRows )* 2560 ); 843cudaMemset (rb_d_ ,0 , (cap + kRows )* 80 * sizeof (float )); 844rb_bytes_ = (cap + kRows )* (2560 + 80 * sizeof (float )+ sizeof (int32_t )); 845vram_ += rb_bytes_ ; 846 } 847 std::vector < int8_t > q (rows * 2560 ); 848 std::vector < float > d (rows * 80 ); 849for (size_t i = 0 ;i < rows ;++ i ) { 850const int64_t p = pos [i ]; 851const LogChunk & ch = * cur_ .chunks [(size_t ) (p /kLogChunk )]; 852const size_t r = (size_t ) (p %kLogChunk ); 853 std::memcpy (& q [i * 2560 ],& ch .q [r * 2560 ],2560 ); 854 std::memcpy (& d [i * 80 ],& ch .d [r * 80 ],80 * sizeof (float )); 855 } 856h_meta_ [18 ]= epoch_ ; 857 std::atomic_thread_fence (std::memory_order_seq_cst ); 858 kernels::copy_i32_from_mapped (d_meta_ ,m_meta_ ,32 ,cs_ ); 859cudaMemcpyAsync (rb_q_ ,q .data (),q .size (),cudaMemcpyHostToDevice ,cs_ ); 860cudaMemcpyAsync (rb_d_ ,d .data (),d .size ()* sizeof (float ),cudaMemcpyHostToDevice ,cs_ ); 861cudaMemcpyAsync (rb_pos_ ,pos .data (),rows * sizeof (int32_t ),cudaMemcpyHostToDevice ,cs_ ); 862// (the host vectors die with this scope: wait for the copies) 863if (cudaStreamSynchronize (cs_ )!= cudaSuccess ) {err = std::string ("dflash2: ring rebuild: " )+ cudaGetErrorString (cudaGetLastError ());return false; } 864const bool was_fork = fork_ ; 865fork_ = false; 866bool ok = true; 867for (size_t r0 = 0 ;ok && r0 < rows ;r0 += kRows ) { 868const int m = (int ) std::min < size_t > (kRows ,rows - r0 ); 869try { kernels::df2_rope_table_inv (rb_pos_ + r0 ,m ,rope_inv_ ,rt_ctx_ ,cs_ ); }catch (const std::exception & e ) {err = e .what ();ok = false;break ; } 870ok = record_kv (m ,cs_ ,reinterpret_cast < const uint8_t *> (rb_q_ )+ r0 * 2560 ,rb_d_ + r0 * 80 ,rb_pos_ + r0 ,err ); 871 } 872fork_ = was_fork ; 873if (!ok )return false; 874if (cudaStreamSynchronize (cs_ )!= cudaSuccess ) {err = std::string ("dflash2: ring rebuild: " )+ cudaGetErrorString (cudaGetLastError ());return false; } 875for (int32_t p :pos )slot_pos_ [(size_t ) (p %kRing )]= ((int64_t )epoch_ <<32 ) |p ; 876* rebuilt = (int64_t )rows ; 877return true; 878} 879 880bool Dflash2Drafter ::begin_request (const int32_t * ids ,int64_t n ,int64_t resume ,bool * cold ) { 881resume = std::max < int64_t > (0 , std::min (resume ,n )); 882if (cold )* cold = false; 883++ ring_stats .requests ; 884last_rebuilt = last_missing = 0 ; 885last_ms = 0 ; 886last_swapped = false; 887 std::string err ; 888 (void )context_wait (err ); 889const Clock ::time_point t0 = Clock ::now (); 890auto lcp_of = [& ](const std::vector < int32_t >& h ) { 891int64_t l = 0 ; 892const int64_t lim = std::min < int64_t > ((int64_t )h .size (),resume ); 893while (l < lim && h [(size_t )l ]== ids [l ])++ l ; 894return l ; 895 }; 896if (!log_on_ ) {// the pre-log rule: a history that does not cover the resumed prefix starts the ring over 897const int64_t lcp = lcp_of (cur_ .hist ); 898const bool stale = ring_hi_ > lcp && lcp < resume ; 899if (stale ) {++ epoch_ ;ring_hi_ = 0 ; } 900if (cold )* cold = stale ; 901cur_ .hist .assign (ids ,ids + resume ); 902return true; 903 } 904bool covered = lcp_of (cur_ .hist ) >=resume ; 905bool swapped = false; 906if (!covered ) {// a parked lineage may be the one this request resumes 907for (size_t i = stash_ .size ();i -- > 0 ;) { 908if (lcp_of (stash_ [i ].hist )< resume )continue ; 909Lineage got = std::move (stash_ [i ]); 910stash_ .erase (stash_ .begin ()+ (std::ptrdiff_t )i ); 911stash_push (std::move (cur_ )); 912cur_ = std::move (got ); 913invalidate_ring (); 914covered = swapped = true; 915++ ring_stats .stash_hits ; 916break ; 917 } 918 } 919if (!covered ) {// another conversation: the live lineage is parked, this one starts empty 920stash_push (std::move (cur_ )); 921cur_ = Lineage {}; 922invalidate_ring (); 923++ ring_stats .cold_starts ; 924 }else if ((int64_t )cur_ .hist .size () >=resume + 128 ) { 925// the rows past `resume` are about to be rewritten (a rewound or branching request): keep the old branch as it is, sharing the log's chunks 926Lineage copy ; 927copy .hist = cur_ .hist ; 928copy .chunks = cur_ .chunks ; 929stash_push (std::move (copy )); 930 } 931if ((int64_t )cur_ .hist .size ()> resume ) {cur_ .hist .resize ((size_t )resume );cur_ .truncate (resume ); } 932if (!covered )cur_ .hist .assign (ids ,ids + resume ); 933// the window the first draft reads, below `resume` (the prompt's own taps cover [resume, n)): every slot that does not hold its row is rebuilt from the log 934int64_t rebuilt = 0 ,missing = 0 ; 935const int64_t lo = std::max < int64_t > (0 ,n - (window_ - 1 )),hi = resume ; 936if (hi > lo ) { 937if (!rebuild (lo ,hi ,& rebuilt ,& missing ,err )) { 938 std::fprintf (stderr ,"strata dflash2: %s: the ring starts over for this request\n" ,err .c_str ()); 939invalidate_ring (); 940missing = hi - lo ; 941rebuilt = 0 ; 942 } 943 } 944static const bool verbose = std::getenv ("STRATA_DF2_RING_STATS" )!= nullptr ; 945if (verbose ) 946 std::fprintf (stderr ,"strata dflash2 ring: request %lld resume %lld of %lld: live log %.1f MiB (%lld positions), parked %zu lineages %.1f MiB, rebuilt %lld rows (missing %lld) in %.2f ms%s\n" , 947 (long long )ring_stats .requests , (long long )resume , (long long )n , (double )cur_ .bytes () /1048576.0 , (long long )cur_ .hist .size (),stash_ .size (), 948 (double )ring_stash_bytes () /1048576.0 , (long long )rebuilt , (long long )missing ,ms_since (t0 ),swapped ?" (swapped in)" :"" ); 949ring_stats .rows_rebuilt += rebuilt ; 950ring_stats .rows_missing += missing ; 951if (rebuilt > 0 )++ ring_stats .rebuilds ; 952const double ms = ms_since (t0 ); 953if (rebuilt > 0 )ring_stats .ms_rebuild += ms ; 954if (swapped )ring_stats .ms_swap += ms ; 955if (cold )* cold = missing > 0 ; 956last_rebuilt = rebuilt ; 957last_missing = missing ; 958last_ms = ms ; 959last_swapped = swapped ; 960return true; 961} 962 963void Dflash2Drafter ::note_rows (const int32_t * toks ,int64_t n ,int64_t pos0 ) { 964if (pos0 < 0 )return ; 965if ((int64_t )cur_ .hist .size ()> pos0 ) {cur_ .hist .resize ((size_t )pos0 );if (log_on_ )cur_ .truncate (pos0 ); } 966if ((int64_t )cur_ .hist .size ()< pos0 )return ;// a gap: the history stops being a prefix, so it stays where it is (the next begin_request starts over) 967cur_ .hist .insert (cur_ .hist .end (),toks ,toks + n ); 968} 969 970bool Dflash2Drafter ::context (const float * taps ,int64_t n ,int64_t pos0 , std::string & err ) { 971if (!context_wait (err ))return false; 972const OnDevice on_device (device_ ); 973const int tap_n = (int )taps_ .size ()* N_ ; 974for (int64_t r0 = 0 ;r0 < n ;r0 += kRows ) { 975const int m = (int ) std::min < int64_t > (kRows ,n - r0 ); 976for (int i = 0 ;i < m ;++ i )h_meta_ [i ]= (int32_t ) (pos0 + r0 + i ); 977h_meta_ [18 ]= epoch_ ; 978 std::atomic_thread_fence (std::memory_order_seq_cst ); 979 kernels::copy_i32_from_mapped (d_meta_ ,m_meta_ ,32 ,cs_ ); 980log_stage (pos0 + r0 ,m ); 981if (!record_context (taps + (size_t )r0 * (size_t )tap_n ,m ,cs_ ,err ))return false; 982if (cudaStreamSynchronize (cs_ )!= cudaSuccess ) {err = std::string ("dflash2: " )+ cudaGetErrorString (cudaGetLastError ());return false; } 983log_flush (); 984 } 985have_ctx_ = std::max < int64_t > (have_ctx_ ,pos0 + n ); 986ring_hi_ = std::max < int64_t > (ring_hi_ ,pos0 + n ); 987return true; 988} 989 990bool Dflash2Drafter ::context_async (const float * taps ,int64_t n ,int64_t pos0 , std::string & err ) { 991if (n < 1 || n > kRows ) {err = "dflash2: context_async rows out of range" ;return false; } 992if (!context_wait (err ))return false;// h_meta_ is read by the queued copy: the previous call must be done 993const OnDevice on_device (device_ ); 994for (int i = 0 ;i < (int )n ;++ i )h_meta_ [i ]= (int32_t ) (pos0 + i ); 995h_meta_ [18 ]= epoch_ ; 996 std::atomic_thread_fence (std::memory_order_seq_cst ); 997 kernels::copy_i32_from_mapped (d_meta_ ,m_meta_ ,32 ,cs_ ); 998log_stage (pos0 , (int )n ); 999if (!record_context (taps , (int )n ,cs_ ,err ))return false; 1000ctx_pending_ = true; 1001have_ctx_ = std::max < int64_t > (have_ctx_ ,pos0 + n ); 1002ring_hi_ = std::max < int64_t > (ring_hi_ ,pos0 + n ); 1003return true; 1004} 1005 1006bool Dflash2Drafter ::context_wait (std::string & err ) { 1007if (!ctx_pending_ )return true; 1008ctx_pending_ = false; 1009const OnDevice on_device (device_ ); 1010if (cudaStreamSynchronize (cs_ )!= cudaSuccess ) {err = std::string ("dflash2: " )+ cudaGetErrorString (cudaGetLastError ());return false; } 1011log_flush (); 1012return true; 1013} 1014 1015bool Dflash2Drafter ::draft (const float * taps ,int n_new ,int64_t pos0 ,int32_t anchor ,int32_t * drafts ,float * probs , std::string & err ) { 1016return draft_launch (taps ,n_new ,pos0 ,anchor ,err )&& draft_finish (drafts ,probs ,err ); 1017} 1018 1019bool Dflash2Drafter ::draft_launch (const float * taps ,int n_new ,int64_t pos0 ,int32_t anchor , std::string & err ) { 1020if (!bound_ ) {err = "dflash2: not bound" ;return false; } 1021if (!context_wait (err ))return false; 1022if (n_new < 1 || n_new > kRows ) {err = "dflash2: draft rows out of range" ;return false; } 1023const OnDevice on_device (device_ ); 1024const Clock ::time_point t0 = Clock ::now (); 1025if (graph_taps_ != nullptr && graph_taps_ != taps ) {err = "dflash2: the taps buffer moved after capture" ;return false; } 1026if (!prof_ && !exec_ [n_new ]) { 1027// the staging must hold valid positions while the capture runs the (empty) kernels' parameter checks 1028for (int i = 0 ;i < 8 ;++ i )h_meta_ [i ]= (int32_t ) (pos0 + i ); 1029if (!capture (n_new ,taps ,err ))return false; 1030graph_taps_ = taps ; 1031 } 1032const int64_t s = pos0 + n_new ; 1033for (int i = 0 ;i < 8 ;++ i ) {h_meta_ [i ]= (int32_t ) (pos0 + std::min (i ,n_new - 1 ));h_meta_ [8 + i ]= (int32_t ) (s + i ); } 1034h_meta_ [16 ]= anchor ; 1035h_meta_ [18 ]= epoch_ ; 1036h_meta_ [17 ]= (int32_t )s ; 1037h_meta_ [24 ]= anchor ; 1038for (int i = 1 ;i < 8 ;++ i )h_meta_ [24 + i ]= mask_token_ ; 1039for (int i = 0 ;i < kDrafts ;++ i ) { ((volatile int32_t * )h_out_ )[i ]= -1 ; } 1040 std::atomic_thread_fence (std::memory_order_seq_cst ); 1041log_stage (pos0 ,n_new ); 1042if (timing_ )cudaEventRecord (ev_a_ ,cs_ ); 1043if (prof_ ) {// the same round without its graph, an event after every stage 1044cudaStreamSynchronize (cs_ ); 1045for (cudaEvent_t e :prof_ -> ev )cudaEventDestroy (e );// the stamps of context() calls are not a round 1046prof_ -> ev .clear (); 1047prof_ -> name .clear (); 1048 kernels::copy_i32_from_mapped (d_meta_ ,m_meta_ ,32 ,cs_ ); 1049stamp ("start" ); 1050if (!record_context (taps ,n_new ,cs_ ,err )|| !record_block (cs_ ,err ))return false; 1051prof_collect (); 1052 }else 1053if (cudaGraphLaunch (exec_ [n_new ],cs_ )!= cudaSuccess ) {err = std::string ("dflash2 draft: " )+ cudaGetErrorString (cudaGetLastError ());return false; } 1054if (timing_ )cudaEventRecord (ev_b_ ,cs_ ); 1055 (void )cudaStreamQuery (cs_ ); 1056launch_t0_ = t0 ; 1057launch_n_ = n_new ; 1058launch_pos0_ = pos0 ; 1059launched_ = true; 1060return true; 1061} 1062 1063bool Dflash2Drafter ::draft_finish (int32_t * drafts ,float * probs , std::string & err ) { 1064if (!launched_ ) {err = "dflash2: draft_finish without draft_launch" ;return false; } 1065launched_ = false; 1066const OnDevice on_device (device_ ); 1067const int n_new = launch_n_ ; 1068const int64_t pos0 = launch_pos0_ ,s = pos0 + n_new ; 1069const Clock ::time_point t0 = launch_t0_ ; 1070if (cudaStreamSynchronize (cs_ )!= cudaSuccess ) {err = std::string ("dflash2 draft: " )+ cudaGetErrorString (cudaGetLastError ());return false; } 1071log_flush (); 1072for (int i = 0 ;i < kDrafts ;++ i ) { 1073const bool made = i < ndraft_ ; 1074drafts [i ]= made ? ((volatile int32_t * )h_out_ )[i ] :0 ; 1075if (probs )probs [i ]= made ? ((volatile float * )h_out_ )[16 + i ] :0.0f ; 1076 } 1077if (timing_ ) { 1078float ms = 0 ; 1079if (cudaEventElapsedTime (& ms ,ev_a_ ,ev_b_ )== cudaSuccess )ms_gpu += ms ; 1080 } 1081have_ctx_ = std::max < int64_t > (have_ctx_ ,s ); 1082ring_hi_ = std::max < int64_t > (ring_hi_ ,pos0 + n_new ); 1083ms_draft += ms_since (t0 ); 1084++ rounds ; 1085return true; 1086} 1087 1088bool Dflash2Drafter ::debug_ring (std::vector < float >& kv , std::vector < int64_t >& tags , std::string & err ) { 1089const OnDevice on_device (device_ ); 1090if (!context_wait (err ))return false; 1091const size_t per = (size_t )kRing * NKV_ * HD_ ; 1092kv .resize ((size_t )L_ * 2 * per ); 1093tags .resize ((size_t )kRing ); 1094if (cudaDeviceSynchronize ()!= cudaSuccess ) {err = "dflash2: debug ring sync" ;return false; } 1095for (int l = 0 ;l < L_ ;++ l ) { 1096if (cudaMemcpy (kv .data ()+ ((size_t )l * 2 )* per ,kring_ [l ],per * 4 ,cudaMemcpyDeviceToHost )!= cudaSuccess || 1097cudaMemcpy (kv .data ()+ ((size_t )l * 2 + 1 )* per ,vring_ [l ],per * 4 ,cudaMemcpyDeviceToHost )!= cudaSuccess ) {err = "dflash2: debug ring copy" ;return false; } 1098 } 1099if (cudaMemcpy (tags .data (),tag_ , (size_t )kRing * 8 ,cudaMemcpyDeviceToHost )!= cudaSuccess ) {err = "dflash2: debug tag copy" ;return false; } 1100return true; 1101} 1102 1103bool Dflash2Drafter ::debug_rows (std::vector < float >& rows , std::string & err ) { 1104rows .resize ((size_t )kRows * (size_t )N_ ); 1105if (cudaMemcpy (rows .data (),fn_ ,rows .size ()* 4 ,cudaMemcpyDeviceToHost )!= cudaSuccess ) {err = "dflash2: debug copy" ;return false; } 1106return true; 1107} 1108 1109} // namespace strata::core