okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd19246dc
main
1#include "strata/core/native_head.hpp" 2#include "strata/core/spill_gate.hpp" 3#include "strata/core/run_manifest.hpp" 4#include "strata/artifact/gguf_reader.hpp" 5#include "strata/kernels/iq_kernels.hpp" 6#include "strata/kernels/native_mmvq.hpp" 7#include "strata/platform/memory.hpp" 8 9#include <cuda_runtime.h> 10#include <climits> 11#include <cstdio> 12#include <cstdlib> 13#include <cstring> 14#include <exception> 15 16namespace strata::core { 17 18NativeHead ::~NativeHead () { 19unload (); 20} 21 22void NativeHead ::unload () { 23if (weights_ ) strata::kernels::native_q6_k_unpack (weights_ ); 24if (weights_ ) strata::kernels::native_q8_0_sm60_release (weights_ ); 25if (scratch_ )cudaFree (scratch_ ); 26if (host_ )cudaFreeHost (host_ );// the mapped-host fallback (weights_ is its device alias) 27else if (weights_ )cudaFree (weights_ ); 28scratch_ = nullptr ; 29weights_ = nullptr ; 30host_ = nullptr ; 31} 32 33bool NativeHead ::load (const std::vector < std::string >& shards ,int64_t n_in ,int64_t n_out , std::string & err ) { 34if (loaded ()) {err = "native head is already loaded" ;return false; } 35if (n_in <=0 || n_out <=0 || n_in > INT_MAX || n_out > INT_MAX || n_in %256 ) { 36err = "native head requires positive int32 dimensions and whole 256-value rows" ; 37return false; 38 } 39try { 40// The architecture is the metadata shard's; output.weight comes from whichever shard holds it (shard 2 41// of Unsloth's UD-Q4_K_XL, whose shard 1 holds no tensor). GgufModel refuses a duplicate across shards. 42const strata::GgufModel model (shards ); 43err = strata::check_engine_architecture (model .meta ()); 44if (!err .empty ())return false; 45size_t at = 0 ; 46const strata::TensorInfo * tensor = model .find ("output.weight" ,& at ); 47const strata::GgufFile & gguf = model .shard (at ); 48if (!tensor || !strata::kernels::native_mmvq_supported ((int )tensor -> type )|| tensor -> shape .size ()!= 2 || 49tensor -> shape [0 ]!= (uint64_t )n_in || tensor -> shape [1 ]!= (uint64_t )n_out ) { 50// opt-in head: unsupported (e.g. all-BF16 latent models) -> keep the canonical head (loaded() stays false) 51 std::fprintf (stderr ,"strata generate: the native head is not loaded (output.weight unsupported/non-native); the canonical BF16 head stays\n" ); 52return true; 53 } 54const uint64_t bytes = strata::kernels::native_mmvq_weight_bytes ((int )tensor -> type , (int )n_in , (int )n_out ); 55const uint64_t payload = gguf .file_size ()- gguf .data_start (); 56if (tensor -> offset > payload || bytes > payload - tensor -> offset ) { 57err = "native head: truncated output.weight payload" ; 58return false; 59 } 60void * weights = nullptr ; 61void * scratch = nullptr ; 62void * host = nullptr ; 63// SHORT OF VRAM: the head in mapped pinned host memory. The head (about 0.4 GiB) is the one buffer a card that holds its sessions and weights but not this can 64// spill whole; every logits row then reads it over PCIe (about 18 ms per row at 28 GB/s), so decode is slower, but the start works. Taken only when the 65// allocation in VRAM fails (or STRATA_HEAD_HOST=1 asks for it); the GEMV kernels read the same pointer either way. Q5_K and the plain MMVQ types: the 66// repacked Q6_K / SM60 layouts rewrite the weights in place and stay in VRAM. 67const bool ask_host = std::getenv ("STRATA_HEAD_HOST" )!= nullptr ; 68cudaError_t status = ask_host ?cudaErrorMemoryAllocation :cudaMalloc (& weights ,bytes ); 69bool discrete = false; 70 {int d = 0 ;cudaDeviceProp pr {};if (cudaGetDevice (& d )== cudaSuccess && cudaGetDeviceProperties (& pr ,d )== cudaSuccess )discrete = strata::spill_allowed (strata::kSpillMetalBuild ,pr .integrated != 0 );else (void )cudaGetLastError (); } 71if (status != cudaSuccess && discrete && std::getenv ("STRATA_HEAD_HOST_OFF" )== nullptr && !strata::kernels::native_q6_k_packed_enabled ()) { 72 (void )cudaGetLastError (); 73void * hp = nullptr ; 74void * dp = nullptr ; 75if (cudaHostAlloc (& hp ,bytes ,cudaHostAllocMapped |cudaHostAllocPortable )== cudaSuccess && cudaHostGetDevicePointer (& dp ,hp ,0 )== cudaSuccess ) { 76 std::memcpy (hp ,gguf .tensor_data (* tensor ),bytes ); 77host = hp ; 78weights = dp ; 79status = cudaSuccess ; 80 std::fprintf (stderr ,"strata generate: short of GPU memory: the output head (%llu MiB) stays in pinned host memory and is read over PCIe for every logits row: " 81"decode is slower%s" , (unsigned long long ) (bytes >>20 ),"\n" ); 82 }else { 83if (hp )cudaFreeHost (hp ); 84 (void )cudaGetLastError (); 85 } 86 } 87if (status == cudaSuccess ) 88status = cudaMalloc (& scratch , strata::kernels::native_q8_1_bytes ((int )n_in ,1 )); 89 strata::platform::advise_willneed (gguf .tensor_data (* tensor ),bytes ); 90if (status == cudaSuccess && host == nullptr ) 91status = cudaMemcpy (weights ,gguf .tensor_data (* tensor ),bytes ,cudaMemcpyHostToDevice ); 92if (status != cudaSuccess ) { 93if (host )cudaFreeHost (host ); 94weights = host ?nullptr :weights ; 95if (scratch )cudaFree (scratch ); 96if (weights )cudaFree (weights ); 97err = std::string ("native head upload: " )+ cudaGetErrorString (status ); 98return false; 99 } 100weights_ = weights ; 101host_ = host ; 102 {int d = -1 ;if (cudaGetDevice (& d )== cudaSuccess )device_ = d ; } 103scratch_ = scratch ; 104bytes_ = bytes ; 105n_in_ = (int )n_in ; 106n_out_ = (int )n_out ; 107type_ = (int )tensor -> type ; 108if (type_ == 14 && strata::kernels::native_q6_k_packed_enabled ())// STRATA_Q6_PACKED=1 109 strata::kernels::native_q6_k_pack (weights_ ,n_in_ ,n_out_ ,"output head" ); 110if (type_ == 8 )// STRATA_Q8_SM60=1 (a no-op otherwise); the MTP draft head reads the same matrix 111 strata::kernels::native_q8_0_sm60_pack (weights_ ,n_in_ ,n_out_ ,"output head" ); 112if (strata::core::manifest::enabled ()) {// STRATA_MANIFEST: what the head holds and where 113namespace mf= strata::core::manifest; 114 mf::instance ().tensors ("head" , strata::ggml_type_name ((uint32_t )type_ ),1 ,bytes ); 115 mf::instance ().path ("head" ,"output.weight" , true, 116host_ != nullptr ?"held in mapped pinned host memory (short of VRAM or STRATA_HEAD_HOST)" :"held in VRAM" , 117 std::string ("type " )+ strata::ggml_type_name ((uint32_t )type_ )+ 118 (type_ == 14 && strata::kernels::native_q6_k_packed_enabled () ?", repacked (STRATA_Q6_PACKED)" :"" )+ 119 (type_ == 8 && std::getenv ("STRATA_Q8_SM60" )!= nullptr ?", repacked (STRATA_Q8_SM60)" :"" )); 120 } 121return true; 122 }catch (const std::exception & error ) { 123err = std::string ("native head: " )+ error .what (); 124return false; 125 } 126} 127 128bool NativeHead ::to_host (std::string & err ) { 129if (weights_ == nullptr || host_ != nullptr || (type_ == 14 && strata::kernels::native_q6_k_packed_enabled ())|| (type_ == 8 && std::getenv ("STRATA_Q8_SM60" )!= nullptr ))return false;// (repacked in place: those stay in VRAM) 130 {int d = 0 ;cudaDeviceProp pr {};if (cudaGetDevice (& d )!= cudaSuccess || cudaGetDeviceProperties (& pr ,d )!= cudaSuccess || !strata::spill_allowed (strata::kSpillMetalBuild ,pr .integrated != 0 )) { (void )cudaGetLastError ();return false; } }// (Q6_K / Q8_0 may be repacked in place: those stay) 131void * hp = nullptr ; 132void * dp = nullptr ; 133if (cudaHostAlloc (& hp ,bytes_ ,cudaHostAllocMapped |cudaHostAllocPortable )!= cudaSuccess ) { 134 (void )cudaGetLastError (); 135err = "native head: no pinned host memory for the head" ; 136return false; 137 } 138if (cudaHostGetDevicePointer (& dp ,hp ,0 )!= cudaSuccess || cudaMemcpy (hp ,weights_ ,bytes_ ,cudaMemcpyDeviceToHost )!= cudaSuccess ) { 139 (void )cudaGetLastError (); 140cudaFreeHost (hp ); 141err = "native head: the head could not be moved to host memory" ; 142return false; 143 } 144cudaFree (weights_ ); 145weights_ = dp ; 146host_ = hp ; 147return true; 148} 149 150bool NativeHead ::run (const float * mixed ,float * logits ,void * stream , std::string & err )const { 151if (!loaded ()|| !mixed || !logits || !stream ) { 152err = "native head requires loaded weights, device buffers and an explicit stream" ; 153return false; 154 } 155try { 156if (type_ == 13 ) { 157 strata::kernels::native_q5_k_f32 (weights_ ,mixed ,scratch_ ,logits ,n_in_ ,n_out_ ,1 ,stream ); 158 }else { 159 strata::kernels::native_quantize_q8_1 (mixed ,scratch_ ,n_in_ ,1 ,stream ); 160 strata::kernels::native_mmvq (type_ ,weights_ ,scratch_ ,logits ,n_in_ ,n_out_ ,1 ,stream ); 161 } 162 }catch (const std::exception & error ) { 163err = std::string ("native head launch: " )+ error .what (); 164return false; 165 } 166const cudaError_t status = cudaPeekAtLastError (); 167if (status != cudaSuccess ) { 168err = std::string ("native head launch: " )+ cudaGetErrorString (status ); 169return false; 170 } 171return true; 172} 173 174// ================================ plan v0.3 P6: THE NATIVE EMBEDDING ================================ 175 176namespace { 177const NativeEmbed * g_embed = nullptr ; 178} 179void set_native_embed (const NativeEmbed * e ) {g_embed = e ; } 180const NativeEmbed * native_embed () {return g_embed ; } 181 182NativeEmbed ::~NativeEmbed () { 183if (host_ )cudaFreeHost (host_ ); 184else if (dev_ )cudaFree (const_cast < void *> (dev_ ));// the VRAM fallback below 185} 186 187bool NativeEmbed ::load (const std::vector < std::string >& shards ,int64_t n_embd ,int64_t n_vocab , std::string & err ) { 188try { 189const strata::GgufModel model (shards ); 190// --embd-gguf's one-tensor file (tools/embd_bf16_pack.py) says "strata-embd": only its tensor is checked 191const strata::MetaValue * arch = model .meta ().get ("general.architecture" ); 192err = arch != nullptr && arch -> s == "strata-embd" ? std::string () : strata::check_engine_architecture (model .meta ()); 193if (!err .empty ()) {err = "native embedding: " + err ;return false; } 194size_t at = 0 ; 195const strata::TensorInfo * t = model .find ("token_embd.weight" ,& at ); 196const strata::GgufFile & gguf = model .shard (at ); 197if (!t || t -> shape .size ()!= 2 || t -> shape [0 ]!= (uint64_t )n_embd || t -> shape [1 ]!= (uint64_t )n_vocab || 198 !strata::kernels::embed_type_supported ((int )t -> type )|| n_embd %256 ) { 199err = "native embedding: token_embd.weight is absent, of another shape, or of a type without a GPU " 200"dequantizer" ; 201return false; 202 } 203row_ = strata::kernels::iq_row_bytes ((int )t -> type ,n_embd ); 204bytes_ = (uint64_t )row_ * (uint64_t )n_vocab ; 205// the table is copied out of the mapping below: a truncated shard must be an error, not a read past EOF 206if (!model .in_bounds (* t ,at )|| strata::tensor_payload_bytes (* t )!= bytes_ ) { 207err = "native embedding: token_embd.weight's payload is truncated or not " + std::to_string (bytes_ )+ 208" B (" + gguf .path ()+ ")" ; 209bytes_ = 0 ; 210return false; 211 } 212 strata::platform::advise_willneed (gguf .tensor_data (* t ),bytes_ );// copied out of the mapping below 213// STRATA_EMBED_VRAM=1: the table in the current device's VRAM instead of mapped host memory. The same 214// bytes, read by the same gather kernels through dev_ (bitwise the same rows); what changes is where a 215// prompt's scattered row reads go: over a PCIe Gen2 x4 link they cost more than the table's size in VRAM 216// is worth. Taken only with the table plus 512 MiB free; otherwise, or when the upload fails, the mapped 217// placement below is used as before (and the fallback is said). 218if (const char * ev = std::getenv ("STRATA_EMBED_VRAM" );ev != nullptr && ev [0 ]== '1' ) { 219size_t free_b = 0 ,total_b = 0 ; 220const bool have_free = cudaMemGetInfo (& free_b ,& total_b )== cudaSuccess ; 221void * d = nullptr ; 222if (have_free && (uint64_t )free_b > bytes_ + ((uint64_t )512 <<20 )&& 223cudaMalloc (& d ,bytes_ )== cudaSuccess ) { 224if (cudaMemcpy (d ,gguf .tensor_data (* t ),bytes_ ,cudaMemcpyHostToDevice )== cudaSuccess ) { 225 std::fprintf (stderr ,"strata: native embedding: STRATA_EMBED_VRAM=1: %llu MiB placed in VRAM " 226"(%llu MiB were free)\n" , 227 (unsigned long long ) (bytes_ >>20 ), (unsigned long long ) (free_b >>20 )); 228dev_ = d ;// host_ stays null: the destructor frees dev_ 229type_ = (int )t -> type ; 230n_embd_ = n_embd ; 231n_vocab_ = n_vocab ; 232return true; 233 } 234 (void )cudaFree (d ); 235 } 236 (void )cudaGetLastError (); 237 std::fprintf (stderr ,"strata: native embedding: STRATA_EMBED_VRAM=1 not taken (%llu MiB free, the table " 238"needs %llu MiB plus 512 MiB): kept in mapped host memory\n" , 239 (unsigned long long ) (have_free ?free_b >>20 :0 ), (unsigned long long ) (bytes_ >>20 )); 240 } 241cudaError_t host_err = cudaHostAlloc (& host_ ,bytes_ ,cudaHostAllocMapped |cudaHostAllocPortable ); 242if (host_err != cudaSuccess ) { 243// Under WSL2 the driver's pinned/mapped host budget (~1 GiB) can be spent by the GPU contexts 244// themselves (three cards). The table is only gathered from, so keep it in the current device's VRAM 245// instead: it costs its size there and reads faster than over PCIe. 246cudaGetLastError (); 247host_ = nullptr ; 248void * d = nullptr ; 249if (cudaMalloc (& d ,bytes_ )!= cudaSuccess || 250cudaMemcpy (d ,gguf .tensor_data (* t ),bytes_ ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 251if (d )cudaFree (d ); 252cudaGetLastError (); 253err = "native embedding: cannot pin " + std::to_string (bytes_ >>20 )+ " MiB: " + 254cudaGetErrorString (host_err )+ ", nor place it in VRAM" ; 255return false; 256 } 257 std::fprintf (stderr ,"strata: native embedding: cannot pin %llu MiB, kept in VRAM instead\n" , 258 (unsigned long long ) (bytes_ >>20 )); 259dev_ = d ; 260 }else { 261 std::memcpy (host_ ,gguf .tensor_data (* t ),bytes_ ); 262void * d = nullptr ; 263#if defined(STRATA_USE_HIP ) 264// #325: the Windows HIP stack can refuse the device alias of a mapped allocation (and, when it gives 265// one, it is the host address itself - unified addressing; kernels read it correctly there, a 266// device-to-device copy into it does not land: tests/hip/mapped_alias). The table is only gathered from, 267// so without an alias it goes into VRAM like the unpinnable case above, instead of failing the start. 268if (cudaHostGetDevicePointer (& d ,host_ ,0 )!= cudaSuccess || d == nullptr ) { 269cudaGetLastError (); 270d = nullptr ; 271if (cudaMalloc (& d ,bytes_ )!= cudaSuccess || 272cudaMemcpy (d ,gguf .tensor_data (* t ),bytes_ ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 273if (d )cudaFree (d ); 274cudaGetLastError (); 275err = "native embedding: no device alias for the mapped table, and no VRAM to copy it into" ; 276return false; 277 } 278cudaFreeHost (host_ );// the destructor frees dev_ when host_ is null 279host_ = nullptr ; 280 std::fprintf (stderr ,"strata: native embedding: no device alias for the mapped table, kept in VRAM\n" ); 281 } 282#else 283if (cudaHostGetDevicePointer (& d ,host_ ,0 )!= cudaSuccess ) { 284err = "native embedding: no device alias for the mapped table" ; 285return false; 286 } 287#endif 288dev_ = d ; 289 } 290type_ = (int )t -> type ; 291n_embd_ = n_embd ; 292n_vocab_ = n_vocab ; 293return true; 294 }catch (const std::exception & e ) { 295err = std::string ("native embedding: " )+ e .what (); 296return false; 297 } 298} 299 300void NativeEmbed ::gather_dev (const int32_t * tokens ,int64_t n_tok ,float * out ,void * stream )const { 301 strata::kernels::iq_embed_rows (type_ ,dev_ ,row_ ,tokens ,n_tok ,n_embd_ ,out ,stream ); 302} 303 304void NativeEmbed ::gather_one (int64_t token ,float * out ,void * stream )const { 305 strata::kernels::iq_dequant_f32 (type_ , (const uint8_t * )dev_ + (size_t )token * row_ ,n_embd_ ,out ,stream ); 306} 307 308}// namespace strata::core