okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c5e84612
main
1#define DPCT_PROFILING_ENABLED 2#include <sycl/sycl.hpp> 3#include <dpct/dpct.hpp> 4#include "strata/sycl_queue.hpp" 5#include "strata/core/native_head.hpp" 6#include "strata/artifact/gguf_reader.hpp" 7#include "strata/kernels/iq_kernels.hpp" 8#include "strata/kernels/native_mmvq.hpp" 9#include "strata/platform/memory.hpp" 10 11#include <climits> 12#include <cstdio> 13#include <cstring> 14#include <exception> 15 16namespace strata::core { 17 18NativeHead ::~NativeHead () { 19if (weights_ ) strata::kernels::native_q6_k_unpack (weights_ ); 20if (scratch_ ) sycl::free (scratch_ , dpct::get_in_order_queue ()); 21if (weights_ ) sycl::free (weights_ , dpct::get_in_order_queue ()); 22} 23 24bool NativeHead ::load (const std::vector < std::string > & shards ,int64_t n_in , 25int64_t n_out , std::string & err )try { 26if (loaded ()) {err = "native head is already loaded" ;return false; } 27if (n_in <=0 || n_out <=0 || n_in > INT_MAX || n_out > INT_MAX || n_in %256 ) { 28err = "native head requires positive int32 dimensions and whole 256-value rows" ; 29return false; 30 } 31try { 32// The architecture is the metadata shard's; output.weight comes from whichever shard holds it (shard 2 33// of Unsloth's UD-Q4_K_XL, whose shard 1 holds no tensor). GgufModel refuses a duplicate across shards. 34const strata::GgufModel model (shards ); 35err = strata::check_engine_architecture (model .meta ()); 36if (!err .empty ())return false; 37size_t at = 0 ; 38const strata::TensorInfo * tensor = model .find ("output.weight" ,& at ); 39const strata::GgufFile & gguf = model .shard (at ); 40if (!tensor || !strata::kernels::native_mmvq_supported ((int )tensor -> type )|| tensor -> shape .size ()!= 2 || 41tensor -> shape [0 ]!= (uint64_t )n_in || tensor -> shape [1 ]!= (uint64_t )n_out ) { 42err = "native head: expected a natively supported output.weight with the canonical head dimensions" ; 43return false; 44 } 45const uint64_t bytes = strata::kernels::native_mmvq_weight_bytes ((int )tensor -> type , (int )n_in , (int )n_out ); 46const uint64_t payload = gguf .file_size ()- gguf .data_start (); 47if (tensor -> offset > payload || bytes > payload - tensor -> offset ) { 48err = "native head: truncated output.weight payload" ; 49return false; 50 } 51void * weights = nullptr ; 52void * scratch = nullptr ; 53 dpct::err0 status = 54DPCT_CHECK_ERROR (weights = (void * )strata::malloc_device_guarded ( 55bytes , dpct::get_in_order_queue ())); 56if (status == 0 ) 57status = DPCT_CHECK_ERROR ( 58scratch = (void * )strata::malloc_device_guarded ( 59 strata::kernels::native_q8_1_bytes ((int )n_in ,1 ), 60 dpct::get_in_order_queue ())); 61 strata::platform::advise_willneed (gguf .tensor_data (* tensor ),bytes ); 62if (status == 0 ) 63status = DPCT_CHECK_ERROR ( 64 dpct::get_in_order_queue () 65 .memcpy (weights ,gguf .tensor_data (* tensor ),bytes ) 66 .wait ()); 67/* 68DPCT1000: Error handling if-stmt was detected but could not be 69rewritten. 70*/ 71if (status != 0 ) { 72if (scratch ) sycl::free (scratch , dpct::get_in_order_queue ()); 73if (weights ) sycl::free (weights , dpct::get_in_order_queue ()); 74/* 75DPCT1009: SYCL reports errors using exceptions and does not use 76error codes. Please replace the "get_error_string_dummy(...)" with a 77real error-handling function. 78*/ 79/* 80DPCT1001: The statement could not be removed. 81*/ 82err = std::string ("native head upload: " )+ 83 dpct::get_error_string_dummy (status ); 84return false; 85 } 86weights_ = weights ; 87scratch_ = scratch ; 88bytes_ = bytes ; 89n_in_ = (int )n_in ; 90n_out_ = (int )n_out ; 91type_ = (int )tensor -> type ; 92if (type_ == 14 && strata::kernels::native_q6_k_packed_enabled ())// STRATA_Q6_PACKED=1 93 strata::kernels::native_q6_k_pack (weights_ ,n_in_ ,n_out_ ,"output head" ); 94if (type_ == 14 && !strata::kernels::native_q6_k_packed_enabled ()&& strata::kernels::native_q6_k_planar_enabled ())// STRATA_Q6_PLANAR: stored as planes (same bytes) 95weights_ = strata::kernels::native_q6_k_planar_adopt (weights_ ,n_in_ ,n_out_ ,"output head" ); 96return true; 97 }catch (const std::exception & error ) { 98err = std::string ("native head: " )+ error .what (); 99return false; 100 } 101} 102catch (sycl::exception const & exc ) { 103 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 104 <<", line:" <<__LINE__ << std::endl ; 105 std::exit (1 ); 106} 107 108bool NativeHead ::run (const float * mixed ,float * logits ,void * stream , 109 std::string & err )const try { 110if (!loaded ()|| !mixed || !logits || !stream ) { 111err = "native head requires loaded weights, device buffers and an explicit stream" ; 112return false; 113 } 114try { 115if (type_ == 13 ) { 116 strata::kernels::native_q5_k_f32 (weights_ ,mixed ,scratch_ ,logits ,n_in_ ,n_out_ ,1 ,stream ); 117 }else { 118 strata::kernels::native_quantize_q8_1 (mixed ,scratch_ ,n_in_ ,1 ,stream ); 119 strata::kernels::native_mmvq (type_ ,weights_ ,scratch_ ,logits ,n_in_ ,n_out_ ,1 ,stream ); 120 } 121 }catch (const std::exception & error ) { 122err = std::string ("native head launch: " )+ error .what (); 123return false; 124 } 125/* 126DPCT1010: SYCL uses exceptions to report errors and does not use the 127error codes. The cudaPeekAtLastError function call was replaced with 0. You 128need to rewrite this code. 129*/ 130const dpct::err0 status = 0 ; 131/* 132DPCT1000: Error handling if-stmt was detected but could not be 133rewritten. 134*/ 135if (status != 0 ) { 136/* 137DPCT1009: SYCL reports errors using exceptions and does not use 138error codes. Please replace the "get_error_string_dummy(...)" with a 139real error-handling function. 140*/ 141/* 142DPCT1001: The statement could not be removed. 143*/ 144err = std::string ("native head launch: " )+ 145 dpct::get_error_string_dummy (status ); 146return false; 147 } 148return true; 149} 150catch (sycl::exception const & exc ) { 151 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 152 <<", line:" <<__LINE__ << std::endl ; 153 std::exit (1 ); 154} 155 156// ================================ plan v0.3 P6: THE NATIVE EMBEDDING ================================ 157 158namespace { 159const NativeEmbed * g_embed = nullptr ; 160} 161void set_native_embed (const NativeEmbed * e ) {g_embed = e ; } 162const NativeEmbed * native_embed () {return g_embed ; } 163 164NativeEmbed ::~NativeEmbed () { 165if (host_ ) sycl::free (host_ , dpct::get_in_order_queue ()); 166else if (dev_ ) 167 sycl::free ((void * )dev_ , dpct::get_in_order_queue ());// the VRAM fallback below 168} 169 170bool NativeEmbed ::load (const std::vector < std::string > & shards ,int64_t n_embd , 171int64_t n_vocab , std::string & err )try { 172try { 173const strata::GgufModel model (shards ); 174// --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked 175const strata::MetaValue * arch = model .meta ().get ("general.architecture" ); 176err = arch != nullptr && arch -> s == "strata-embd" ? std::string () : strata::check_engine_architecture (model .meta ()); 177if (!err .empty ()) {err = "native embedding: " + err ;return false; } 178size_t at = 0 ; 179const strata::TensorInfo * t = model .find ("token_embd.weight" ,& at ); 180const strata::GgufFile & gguf = model .shard (at ); 181if (!t || t -> shape .size ()!= 2 || t -> shape [0 ]!= (uint64_t )n_embd || t -> shape [1 ]!= (uint64_t )n_vocab || 182 !strata::kernels::embed_type_supported ((int )t -> type )|| n_embd %256 ) { 183err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU " 184"dequantizer" ; 185return false; 186 } 187row_ = strata::kernels::iq_row_bytes ((int )t -> type ,n_embd ); 188bytes_ = (uint64_t )row_ * (uint64_t )n_vocab ; 189// the table is copied out of the mapping below: a truncated shard must be an error, not a read past EOF 190if (!model .in_bounds (* t ,at )|| strata::tensor_payload_bytes (* t )!= bytes_ ) { 191err = "native embedding: token_embd.weight's payload is truncated or not " + std::to_string (bytes_ )+ 192" B (" + gguf .path ()+ ")" ; 193bytes_ = 0 ; 194return false; 195 } 196 strata::platform::advise_willneed (gguf .tensor_data (* t ),bytes_ );// copied out of the mapping below 197/* 198DPCT1048: The original value cudaHostAllocMapped is not meaningful in 199the migrated code and was removed or replaced with 0. You may need to 200check the migrated code. 201*/ 202/* 203DPCT1048: The original value cudaHostAllocPortable is not meaningful 204in the migrated code and was removed or replaced with 0. You may need to 205check the migrated code. 206*/ 207if (DPCT_CHECK_ERROR (host_ = (void * )sycl::malloc_host ( 208bytes_ , dpct::get_in_order_queue ()))!= 0 ) { 209// Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts 210// themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM 211// instead: it costs its size there and reads faster than over PCIe. 212/* 213DPCT1026: The call to cudaGetLastError was removed because this 214functionality is redundant in SYCL. 215*/ 216host_ = nullptr ; 217void * d = nullptr ; 218if (DPCT_CHECK_ERROR (d = (void * )strata::malloc_device_guarded ( 219bytes_ , dpct::get_in_order_queue ()))!= 2200 || 221/* 222DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 223assuming in the original code the source host memory is pageable 224memory. If the memory is not pageable, call wait() on event 225return by memcpy API to ensure synchronization behavior. 226*/ 227DPCT_CHECK_ERROR (dpct::get_in_order_queue ().memcpy ( 228d ,gguf .tensor_data (* t ),bytes_ ).wait ())!= 0 ) { 229if (d ) sycl::free (d , dpct::get_in_order_queue ()); 230/* 231DPCT1026: The call to cudaGetLastError was removed because 232this functionality is redundant in SYCL. 233*/ 234err = "native embedding: cannot pin " + 235 std::to_string (bytes_ >>20 )+ 236" MiB, nor place it in VRAM" ; 237return false; 238 } 239 std::fprintf (stderr ,"strata: native embedding: cannot pin %llu MiB, kept in VRAM instead\n" , 240 (unsigned long long ) (bytes_ >>20 )); 241dev_ = d ; 242 }else { 243 std::memcpy (host_ ,gguf .tensor_data (* t ),bytes_ ); 244void * d = nullptr ; 245#if defined(STRATA_USE_HIP ) 246// #325: the Windows HIP stack can refuse the device alias of a mapped allocation (and, when it gives 247// one, it is the host address itself - unified addressing; kernels read it correctly there, a 248// device-to-device copy into it does not land: tests/hip/mapped_alias). The table is only gathered from, 249// so without an alias it goes into VRAM like the unpinnable case above, instead of failing the start. 250if (cudaHostGetDevicePointer (& d ,host_ ,0 )!= cudaSuccess || d == nullptr ) { 251cudaGetLastError (); 252d = nullptr ; 253if (cudaMalloc (& d ,bytes_ )!= cudaSuccess || 254cudaMemcpy (d ,gguf .tensor_data (* t ),bytes_ ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 255if (d )cudaFree (d ); 256cudaGetLastError (); 257err = "native embedding: no device alias for the mapped table, and no VRAM to copy it into" ; 258return false; 259 } 260cudaFreeHost (host_ );// the destructor frees dev_ when host_ is null 261host_ = nullptr ; 262 std::fprintf (stderr ,"strata: native embedding: no device alias for the mapped table, kept in VRAM\n" ); 263 } 264#else 265if (DPCT_CHECK_ERROR (d = (void * )host_ )!= 0 ) { 266err = "native embedding: no device alias for the mapped table" ; 267return false; 268 } 269#endif 270dev_ = d ; 271 } 272type_ = (int )t -> type ; 273n_embd_ = n_embd ; 274n_vocab_ = n_vocab ; 275return true; 276 }catch (const std::exception & e ) { 277err = std::string ("native embedding: " )+ e .what (); 278return false; 279 } 280} 281catch (sycl::exception const & exc ) { 282 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 283 <<", line:" <<__LINE__ << std::endl ; 284 std::exit (1 ); 285} 286 287void NativeEmbed ::gather_dev (const int32_t * tokens ,int64_t n_tok ,float * out ,void * stream )const { 288 strata::kernels::iq_embed_rows (type_ ,dev_ ,row_ ,tokens ,n_tok ,n_embd_ ,out ,stream ); 289} 290 291void NativeEmbed ::gather_one (int64_t token ,float * out ,void * stream )const { 292 strata::kernels::iq_dequant_f32 (type_ , (const uint8_t * )dev_ + (size_t )token * row_ ,n_embd_ ,out ,stream ); 293} 294 295}// namespace strata::core