okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
fd19246dc
main
1#include "strata/core/native_dense.hpp" 2#include "strata/core/run_manifest.hpp" 3#include <cstdlib> 4#include "strata/core/weights.hpp" 5#include "strata/artifact/gguf_reader.hpp" 6#include "strata/kernels/fused_gr.hpp" 7#include "strata/kernels/gfx_arch.hpp" 8#include "strata/kernels/native_mmvq.hpp" 9#include "strata/platform/memory.hpp" 10 11#include <cuda_runtime.h> 12#include <algorithm> 13#include <climits> 14#include <cstdio> 15#include <cstdlib> 16#include <exception> 17#include <limits> 18#include <memory> 19#include <set> 20#include <cmath> 21#include <cstring> 22#include <map> 23#include <mutex> 24#include <thread> 25#include <vector> 26 27namespace strata::core { 28namespace { 29// `load` makes one cudaMalloc per projection matrix, and the driver backs each call with 2 MiB granules 30// (measured on the RTX 5060: 300 buffers of 6.73 MiB asked 2019 MiB and cost 2400). So a stage's real 31// footprint is the granule-rounded sum, not the payload sum. This rule - a granule for every matrix of a 32// MiB or more, the payload for the rest - prices the iq3_s pack's 300 matrices at 2255 MiB where they 33// really take 2238 (+0.8%). It over-prices, which is the safe side. (Pricing every matrix at a granule is 34// far worse, 2378 MiB: the driver packs the sub-MiB matrices into the slack of the rounded ones.) 35constexpr uint64_t kAllocGranule = 2ull <<20 ; 36constexpr uint64_t kSmallAlloc = 1ull <<20 ; 37uint64_t alloc_bytes (uint64_t bytes ) { 38return bytes < kSmallAlloc ?bytes : (bytes + kAllocGranule - 1 ) /kAllocGranule * kAllocGranule ; 39} 40int g_layer_lb = -1 ,g_layer_le = -1 ;// set_layer_range; -1: every layer 41bool in_range (const std::string & name ) { 42if (g_layer_lb < 0 || name .rfind ("blk." ,0 )!= 0 )return true; 43const int l = std::atoi (name .c_str ()+ 4 ); 44return l >=g_layer_lb && l < g_layer_le ; 45} 46// S23 experiment (STRATA_HC_Q8=1): the hyper-connection projections' Q8_0 bytes for the verify read 47bool hc_q8_env () { 48// STRATA_HC_Q8: 1 = on (the GGUF's own Q8_0 projections, or - a bf16 pack - a Q8_0 copy quantized at load); 0 = off; 49// unset / auto = on for gfx12 (RDNA4: the R9700 decode +2.5 to +4%, KL 0.0003-0.0010 over its noise floor) unless 50// STRATA_GFX12_DEFAULTS=0; also on for gfx1151 (Strix Halo, STRATA_HC_Q8=0 turns it off), off elsewhere 51static const bool on = [] { 52const char * v = std::getenv ("STRATA_HC_Q8" ); 53if (v != nullptr && v [0 ]== '1' )return true; 54if (v != nullptr && v [0 ]!= '\0' && std::strcmp (v ,"auto" )!= 0 )return false; 55#if defined(STRATA_USE_HIP ) 56 {// Strix Halo (gfx1151): on by default (decode +9.5%, json/code/tool/chat/agent +7.9..+10.7%); the answers differ in 57// near-tie tokens by about the size of the engine's own CPU-vs-GPU expert rounding (docs/AMD_HIP.md); 58// STRATA_HC_Q8=0 keeps the bf16 read 59int dev1151 = 0 ; 60cudaDeviceProp p1151 ; 61const bool g1151 = cudaGetDevice (& dev1151 )== cudaSuccess && cudaGetDeviceProperties (& p1151 ,dev1151 )== cudaSuccess && 62 strata::kernels::gfx_arch_is_gfx1151 (p1151 .gcnArchName ); 63 (void )cudaGetLastError (); 64if (g1151 ) { 65 std::fprintf (stderr ,"strata: Strix Halo (gfx1151): 8-bit hyper-connection weights are on (decode about 9%% faster, " 66"answers can differ in near-tie tokens); STRATA_HC_Q8=0 keeps the bf16 read\n" ); 67return true; 68 } 69 } 70const char * d = std::getenv ("STRATA_GFX12_DEFAULTS" ); 71if (d != nullptr && d [0 ]== '0' )return false; 72int dev = 0 ; 73cudaDeviceProp p ; 74const bool g12 = cudaGetDevice (& dev )== cudaSuccess && cudaGetDeviceProperties (& p ,dev )== cudaSuccess && 75 strata::kernels::gfx_arch_is_gfx12 (p .gcnArchName ); 76 (void )cudaGetLastError (); 77if (g12 ) std::fprintf (stderr ,"strata: gfx12 (RDNA4): the hyper-connection projections are read as Q8_0 (quantized at load, " 78"decode faster, answers differ slightly); STRATA_HC_Q8=0 keeps the bf16 read\n" ); 79return g12 ; 80#else 81return false; 82#endif 83 }(); 84return on ; 85} 86// STRATA_HC_Q8_ALL_STAGES=1: the Q8_0 hyper-connection rows of every layer are copied to every stage (the behaviour before #3559) 87bool hc_q8_stage_local () { 88static const bool on = [] {const char * v = std::getenv ("STRATA_HC_Q8_ALL_STAGES" );return !(v != nullptr && v [0 ]== '1' ); }(); 89return on ; 90} 91// STRATA_HC_Q8_INJECT=1: the F32 inject rows get a Q8_0 copy too (S25) 92bool hc_q8_inject_env () { 93static const bool on = [] {const char * v = std::getenv ("STRATA_HC_Q8_INJECT" );return v && v [0 ]== '1' ; }(); 94return on ; 95} 96bool hc_q8_name (const std::string & name ) { 97if (name == "output_hc_down.weight" || name == "output_hc_up.weight" )return true;// S25: the final mixer too 98if (name .rfind ("blk." ,0 )!= 0 )return false; 99static const char * suffixes []= {".hc_attn_down.weight" ,".hc_attn_up.weight" ,".hc_attn_inject.weight" , 100".hc_ffn_down.weight" ,".hc_ffn_up.weight" ,".hc_ffn_inject.weight" }; 101for (const char * suffix :suffixes )if (name .ends_with (suffix ))return true; 102return false; 103} 104// S25: the GGUF keeps the inject rows as F32 - quantized here to Q8_0 (ggml's reference rounding) so the Q8_0 read 105// covers every hc projection 106uint16_t half_bits (float f ) { 107uint32_t x ; 108 std::memcpy (& x ,& f ,4 ); 109const uint32_t sign = (x >>16 )& 0x8000u ; 110int32_t e = (int32_t ) ((x >>23 )& 0xff )- 127 + 15 ; 111uint32_t m = x & 0x7fffffu ; 112if (e <=0 ) {// subnormal or zero 113if (e < -10 )return (uint16_t )sign ; 114m |=0x800000u ; 115const uint32_t shift = (uint32_t ) (14 - e ); 116uint32_t h = m >>shift ; 117const uint32_t rem = m & ((1u <<shift )- 1 ),half = 1u << (shift - 1 ); 118if (rem > half || (rem == half && (h & 1u )))++ h ; 119return (uint16_t ) (sign |h ); 120 } 121if (e >=31 )return (uint16_t ) (sign |0x7c00u ); 122uint32_t h = ((uint32_t )e <<10 ) | (m >>13 ); 123const uint32_t rem = m & 0x1fffu ; 124if (rem > 0x1000u || (rem == 0x1000u && (h & 1u )))++ h ; 125return (uint16_t ) (sign |h ); 126} 127std::vector < uint8_t > q8_0_of (const float * x ,uint64_t n ) { 128 std::vector < uint8_t > out ((size_t ) (n /32 * 34 )); 129for (uint64_t b = 0 ;b < n /32 ;++ b ) { 130float amax = 0.0f ; 131for (int j = 0 ;j < 32 ;++ j )amax = (std::max )(amax , std::fabs (x [b * 32 + j ])); 132const float d = amax /127.0f ,id = d != 0.0f ?1.0f /d :0.0f ; 133uint8_t * o = out .data ()+ b * 34 ; 134const uint16_t hb = half_bits (d ); 135 std::memcpy (o ,& hb ,2 ); 136for (int j = 0 ;j < 32 ;++ j )o [2 + j ]= (uint8_t ) (int8_t ) std::lround (x [b * 32 + j ]* id ); 137 } 138return out ; 139} 140// A bf16 matrix (the pack file's values) as Q8_0, ggml's reference rounding; the blocks are independent, so a few threads 141std::vector < uint8_t > q8_0_of_bf16 (const uint16_t * x ,uint64_t n ) { 142 std::vector < uint8_t > out ((size_t ) (n /32 * 34 )); 143const uint64_t nb = n /32 ; 144auto work = [& ](uint64_t b0 ,uint64_t b1 ) { 145for (uint64_t b = b0 ;b < b1 ;++ b ) { 146float v [32 ],amax = 0.0f ; 147for (int j = 0 ;j < 32 ;++ j ) { 148const uint32_t u = (uint32_t )x [b * 32 + j ] <<16 ; 149 std::memcpy (& v [j ],& u ,4 ); 150amax = (std::max )(amax , std::fabs (v [j ])); 151 } 152const float d = amax /127.0f ,id = d != 0.0f ?1.0f /d :0.0f ; 153uint8_t * o = out .data ()+ b * 34 ; 154const uint16_t hb = half_bits (d ); 155 std::memcpy (o ,& hb ,2 ); 156for (int j = 0 ;j < 32 ;++ j )o [2 + j ]= (uint8_t ) (int8_t ) std::lround (v [j ]* id ); 157 } 158 }; 159const unsigned nt = (std::min )(8u , (std::max )(1u , std::thread::hardware_concurrency ())); 160 std::vector < std::thread > pool ; 161for (unsigned i = 0 ;i < nt ;++ i )pool .emplace_back (work ,nb * i /nt ,nb * (i + 1 ) /nt ); 162for (auto & th :pool )th .join (); 163return out ; 164} 165bool eligible (const strata::TensorInfo & tensor ,bool include_ple_key ) { 166const auto & name = tensor .name ; 167if (name .rfind ("blk." ,0 )!= 0 )return false; 168// Match the native PLE kernel: Q2_0, IQ3_XXS, IQ4_XS and Q8_0 (UD-Q4_K_XL). Other keys retain the packed BF16 169// fallback. 170if (name == "blk.1.ple_key.weight" ) 171return include_ple_key && (tensor .type == 42 || tensor .type == 18 || tensor .type == 23 || tensor .type == 8 ); 172static const char * suffixes []= {".attn_qkv.weight" ,".attn_gate.weight" ,".ssm_out.weight" , 173".attn_q.weight" ,".attn_k.weight" ,".attn_v.weight" ,".attn_output.weight" , 174".ffn_gate_shexp.weight" ,".ffn_up_shexp.weight" ,".ffn_down_shexp.weight" }; 175for (const char * suffix :suffixes )if (name .ends_with (suffix ))return true; 176return false; 177} 178// #4741: a native-eligible projection a pack keeps unquantized (BF16, GGUF type 30; Heretic v2 IQ4_NL has its layer-0 attn_gate so) 179// has no native kernel. Its siblings are Q8_0, so it is served as Q8_0 made from the file's BF16 values (ggml's rounding), and 180// the dispatchers that need a native projection find one. The pack's BF16 copy stays where it is. 181bool bf16_as_q8_0 (const strata::TensorInfo & tensor ,const WeightRef & ref ) { 182return tensor .type == 30 && tensor .name != "blk.1.ple_key.weight" && tensor .shape .size ()== 2 && 183 !ref .quantized ()&& ref .kind == WeightKind ::Bf16InF32 && 184ref .ne0 > 0 && ref .ne0 <=INT_MAX && ref .ne1 > 0 && ref .ne1 <=INT_MAX && ref .ne0 %32 == 0 && 185tensor .shape [0 ]== (uint64_t )ref .ne0 && tensor .shape [1 ]== (uint64_t )ref .ne1 ; 186} 187struct DeviceFree {void operator()(void * p )const {if (p )cudaFree (p ); } }; 188using DevicePtr = std::unique_ptr < void ,DeviceFree > ; 189struct Pending { 190WeightRef * ref ; 191int type ; 192uint64_t bytes ; 193DevicePtr data ; 194DevicePtr packed ;// STRATA_Q8_PACKED=1 copy, or null 195}; 196} 197 198bool NativeDense ::served_names (const std::vector < std::string >& shards ,bool include_ple_key , 199 std::set < std::string >& out , std::string & err ) { 200try { 201for (const auto & path :shards ) { 202 strata::GgufFile gguf (path ); 203for (const auto & tensor :gguf .tensors ()) 204if (eligible (tensor ,include_ple_key )&& strata::kernels::native_mmvq_supported (tensor .type )&& 205tensor .shape .size ()== 2 ) 206out .insert (tensor .name ); 207 } 208return true; 209 }catch (const std::exception & error ) { 210err = std::string ("native dense: " )+ error .what (); 211return false; 212 } 213} 214 215void NativeDense ::set_layer_range (int lb ,int le ) {g_layer_lb = lb ;g_layer_le = le ; } 216// The byte walk `load` does for the layers [lb, le), without the allocations: the same filters in the same order, 217// reading the GGUF headers and the canonical table only, so it needs no device. A later stage's projections are not 218// on the card when the split search prices that stage, and `load` runs one cudaMalloc per matrix (#1238). The two 219// have to stay in step. A repeated name is skipped rather than refused (`load` refuses it). 220bool NativeDense ::weight_bytes_for (const std::vector < std::string >& shards ,WeightTable & table ,bool include_ple_key , 221int64_t lb ,int64_t le ,uint64_t & out , std::string & err ) { 222out = 0 ; 223try { 224 std::set < std::string > seen ,hc_seen ; 225uint64_t total = 0 ; 226auto in_stage = [& ](const std::string & name ) {// a blk.<l>. tensor of layers [lb, le); the rest belongs to every stage 227if (name .rfind ("blk." ,0 )!= 0 )return true; 228const long l = std::strtol (name .c_str ()+ 4 ,nullptr ,10 ); 229return l >=lb && l < le ; 230 }; 231for (const auto & path :shards ) { 232 strata::GgufFile gguf (path ); 233for (const auto & tensor :gguf .tensors ()) { 234// STRATA_HC_Q8: `load` copies the GGUF's Q8_0 hyper-connection rows of its layers (and the final mixer's) 235// to the card, one cudaMalloc each, and the pack's bf16 rows get a Q8_0 copy below: priced as `load` makes them 236if (hc_q8_env ()&& hc_q8_name (tensor .name )&& tensor .shape .size ()== 2 ) { 237const bool f32_inject = hc_q8_inject_env ()&& tensor .type == 0 && tensor .name .ends_with ("_inject.weight" ); 238if ((tensor .type == 8 || f32_inject )&& (!hc_q8_stage_local ()|| in_stage (tensor .name ))&& 239hc_seen .insert (tensor .name ).second ) { 240const auto found = table .table_ .find (tensor .name ); 241if (found != table .table_ .end ()&& found -> second .ne0 %32 == 0 && 242tensor .shape [0 ]== (uint64_t )found -> second .ne0 && tensor .shape [1 ]== (uint64_t )found -> second .ne1 ) 243total += alloc_bytes ((uint64_t )found -> second .ne0 /32 * 34 * (uint64_t )found -> second .ne1 ); 244 } 245 } 246if (!eligible (tensor ,include_ple_key ))continue ; 247if (tensor .name .rfind ("blk." ,0 )== 0 && tensor .name .find ("ple" )== std::string::npos ) {// `load` takes the PLE key on every stage 248const long l = std::strtol (tensor .name .c_str ()+ 4 ,nullptr ,10 ); 249if (l < lb || l >=le )continue ; 250 } 251if (!seen .insert (tensor .name ).second )continue ; 252auto found = table .table_ .find (tensor .name ); 253if (found == table .table_ .end ()) { 254err = "native dense: tensor absent from canonical table: " + tensor .name ; 255return false; 256 } 257const auto & ref = found -> second ; 258if (bf16_as_q8_0 (tensor ,ref )) {// #4741 259total += alloc_bytes ((uint64_t )ref .ne0 /32 * 34 * (uint64_t )ref .ne1 ); 260continue ; 261 } 262if (!strata::kernels::native_mmvq_supported (tensor .type ))continue ; 263if (tensor .name == "blk.1.ple_key.weight" && !ref .quantized ())continue ; 264if (!ref .quantized ()|| tensor .shape .size ()!= 2 || 265ref .ne0 <=0 || ref .ne0 > INT_MAX || ref .ne1 <=0 || ref .ne1 > INT_MAX || 266tensor .shape [0 ]!= (uint64_t )ref .ne0 || tensor .shape [1 ]!= (uint64_t )ref .ne1 ) { 267err = "native dense: incompatible matrix " + tensor .name ; 268return false; 269 } 270total += alloc_bytes (strata::kernels::native_mmvq_weight_bytes (tensor .type , (int )ref .ne0 , (int )ref .ne1 )); 271 } 272 } 273if (hc_q8_env ())// a bf16 pack: `load` quantizes the layers' down / up projections that the GGUF does not carry as Q8_0 274for (const auto & [name ,ref ] :table .table_ ) { 275if (name .rfind ("blk." ,0 )!= 0 || !in_stage (name )|| !hc_q8_name (name )|| hc_seen .count (name )|| 276 !(name .ends_with ("_down.weight" )|| name .ends_with ("_up.weight" ))) 277continue ; 278if (ref .ne0 %32 == 0 && ref .elements == ref .ne0 * ref .ne1 )total += alloc_bytes ((uint64_t )ref .elements /32 * 34 ); 279 } 280out = total ; 281return true; 282 }catch (const std::exception & error ) { 283err = std::string ("native dense: " )+ error .what (); 284return false; 285 } 286} 287bool NativeDense ::keep_unquantized_ple_key (const std::string & pack_dir , std::set < std::string >& skip , 288 std::string & err ) { 289const std::string key = "blk.1.ple_key.weight" ; 290if (!skip .count (key ))return true; 291int code_bits = -1 ; 292if (!WeightTable ::index_code_bits (pack_dir ,key ,code_bits ,err ))return false; 293if (code_bits == 0 )skip .erase (key ); 294return true; 295} 296 297// STRATA_HC_Q8 without a bf16 copy: the two dequantization scratches (one bf16 matrix each) of `hc_bf16_view`, per device, 298// allocated by `load` - never on first use, so a graph capture cannot meet the allocation 299static void * g_hc_scratch [64 ][2 ][2 ]= {};// [device][class][slot] 300static cudaEvent_t g_hc_ev [64 ][2 ]= {};// [device][slot]: the prompt path's last reader of the slot 301static bool g_hc_ev_set [64 ][2 ]= {}; 302 303NativeDense ::~NativeDense () { 304release (); 305} 306 307void NativeDense ::release () { 308// what the destructor always did first: no HC scratch pointer and no packed-Q8 registry key may outlive the memory 309for (auto & dev :g_hc_scratch ) 310for (auto & cl :dev ) 311for (void *& b :cl ) 312if (b != nullptr && std::find (weights_ .begin (),weights_ .end (),b )!= weights_ .end ())b = nullptr ; 313for (const void * p :packed_keys_ ) strata::kernels::native_q8_0_packed_unregister (p ); 314if (scratch_ )cudaFree (scratch_ ); 315for (void * p :weights_ )cudaFree (p ); 316scratch_ = nullptr ; 317weights_ .clear (); 318packed_keys_ .clear (); 319layer_bytes_ .clear (); 320bytes_ = 0 ; 321} 322 323uint64_t NativeDense ::bytes_in (int64_t lo ,int64_t hi )const { 324uint64_t n = 0 ; 325for (int64_t l = std::max < int64_t > (lo ,0 );l < hi && l < (int64_t )layer_bytes_ .size ();++ l )n += layer_bytes_ [(size_t )l ]; 326return n ; 327} 328 329bool NativeDense ::load (const std::vector < std::string >& shards ,WeightTable & table , std::string & err , 330bool include_ple_key ,int64_t layer_lo ,int64_t layer_hi ) { 331auto outside = [& ](const std::string & name ) {// a blk.<l>. tensor of another stage's layers 332if (layer_hi < 0 || name .rfind ("blk." ,0 )!= 0 )return false; 333const long l = std::strtol (name .c_str ()+ 4 ,nullptr ,10 ); 334return l < layer_lo || l >=layer_hi ; 335 }; 336auto layer_of = [& ](const std::string & name )-> int64_t {// the layer of a blk.<l>. tensor, -1 otherwise 337if (name .rfind ("blk." ,0 )!= 0 )return -1 ; 338return std::strtoll (name .c_str ()+ 4 ,nullptr ,10 ); 339 }; 340if (scratch_ || !weights_ .empty ()) {err = "native dense: already loaded" ;return false; } 341if (shards .empty ()) {err = "native dense: at least one GGUF shard is required" ;return false; } 342try { 343 std::vector < Pending > pending ; 344 std::set < std::string > seen ; 345int max_in = 0 ; 346uint64_t total = 0 ,hc_q8_bytes = 0 ,allocated = 0 ,hc_q8_skipped_bytes = 0 ,hc_q8_skipped = 0 ; 347 std::vector < uint64_t > per_layer ; 348uint64_t split_count = 0 ,split_tensors = 0 ; 349 std::set < uint64_t > split_numbers ; 350bool have_architecture = false; 351for (const auto & path :shards ) { 352 strata::GgufFile gguf (path ); 353const auto * count = gguf .get ("split.count" ); 354const auto * number = gguf .get ("split.no" ); 355const auto * tensors = gguf .get ("split.tensors.count" ); 356if (gguf .get ("general.architecture" )&& (!number || number -> u == 0 )) { 357// splitter may copy general.architecture into every shard (Huihui abliterated re-split) 358err = strata::check_engine_architecture (gguf ); 359if (!err .empty ())return false; 360have_architecture = true; 361if (count && number && tensors && number -> u == 0 && count -> u > 1 ) { 362split_count = count -> u ; 363split_tensors = tensors -> u ; 364 } 365 }else if (!have_architecture || !split_count || !count || !number || !tensors || 366count -> u != split_count || number -> u == 0 || number -> u >=split_count || 367tensors -> u != split_tensors ) { 368err = "native dense: additional shard must match the architecture-validated first shard's split metadata" ; 369return false; 370 } 371if (number && !split_numbers .insert (number -> u ).second ) { 372err = "native dense: duplicate split shard number" ;return false; 373 } 374 std::vector < uint64_t > offsets ; 375for (const auto & tensor :gguf .tensors ())offsets .push_back (tensor .offset ); 376 std::sort (offsets .begin (),offsets .end ()); 377if (std::adjacent_find (offsets .begin (),offsets .end ())!= offsets .end ()) { 378err = "native dense: tensor payload offsets overlap" ;return false; 379 } 380// Validate every directory span, including tensors we do not upload: 381// an ignored tensor must not overlap the native matrix that follows it. 382const uint64_t payload = gguf .file_size ()- gguf .data_start (); 383for (const auto & tensor :gguf .tensors ()) { 384int block_elements = 0 ,block_bytes = 0 ; 385uint64_t elements = 1 ; 386if (tensor .shape .empty ()|| !strata::block_geometry (tensor .type ,block_elements ,block_bytes )|| 387tensor .shape [0 ] % (uint64_t )block_elements != 0 ) { 388err = "native dense: invalid block geometry " + tensor .name ;return false; 389 } 390for (uint64_t dimension :tensor .shape ) { 391if (!dimension || elements > (std::numeric_limits < uint64_t > ::max )() /dimension ) { 392err = "native dense: invalid tensor extent " + tensor .name ;return false; 393 } 394elements *=dimension ; 395 } 396const uint64_t blocks = elements / (uint64_t )block_elements ; 397if (blocks > (std::numeric_limits < uint64_t > ::max )() / (uint64_t )block_bytes ) { 398err = "native dense: tensor byte count overflow " + tensor .name ;return false; 399 } 400const uint64_t bytes = blocks * (uint64_t )block_bytes ; 401if (tensor .offset > payload || bytes > payload - tensor .offset ) { 402err = "native dense: truncated payload " + tensor .name ;return false; 403 } 404const auto next = std::upper_bound (offsets .begin (),offsets .end (),tensor .offset ); 405if (next != offsets .end ()&& bytes > * next - tensor .offset ) { 406err = "native dense: overlapping payload " + tensor .name ;return false; 407 } 408// the uploads below read these: ask for them now so the reads overlap 409if (eligible (tensor ,include_ple_key )&& !outside (tensor .name )&& 410 strata::kernels::native_mmvq_supported (tensor .type )) 411 strata::platform::advise_willneed (gguf .tensor_data (tensor ),bytes ); 412 } 413for (const auto & tensor :gguf .tensors ()) { 414if (!eligible (tensor ,include_ple_key )|| outside (tensor .name ))continue ; 415if (!in_range (tensor .name )&& tensor .name .find ("ple" )== std::string::npos )continue ; 416if (!seen .insert (tensor .name ).second ) { 417err = "native dense: duplicate tensor " + tensor .name ;return false; 418 } 419auto found = table .table_ .find (tensor .name ); 420if (found == table .table_ .end ()) { 421err = "native dense: tensor absent from canonical table: " + tensor .name ;return false; 422 } 423auto & ref = found -> second ; 424if (ref .native_data ) {err = "native dense: override already attached" ;return false; } 425if (bf16_as_q8_0 (tensor ,ref )) {// #4741: a BF16 projection of the pack, served as Q8_0 426const uint64_t n = (uint64_t )ref .ne0 * (uint64_t )ref .ne1 ; 427const std::vector < uint8_t > q8 = q8_0_of_bf16 ((const uint16_t * )gguf .tensor_data (tensor ),n ); 428void * allocation = nullptr ; 429auto status = cudaMalloc (& allocation ,q8 .size ()); 430DevicePtr data (allocation ); 431if (status == cudaSuccess )status = cudaMemcpy (data .get (),q8 .data (),q8 .size (),cudaMemcpyHostToDevice ); 432if (status != cudaSuccess ) { 433err = "native dense upload " + tensor .name + ": " + cudaGetErrorString (status );return false; 434 } 435max_in = (std::max )(max_in , (int )ref .ne0 ); 436total += q8 .size (); 437allocated += alloc_bytes (q8 .size ()); 438 std::fprintf (stderr ,"native dense: %s is BF16 in the file: served as Q8_0 like its siblings (#4741)\n" , 439tensor .name .c_str ()); 440pending .push_back (Pending {& ref ,8 , (uint64_t )q8 .size (), std::move (data ),DevicePtr ()}); 441continue ; 442 } 443if (!strata::kernels::native_mmvq_supported (tensor .type ))continue ; 444// #326: the pack keeps an unquantized (--compat-bf16) key, which the PLE reads from the arena 445if (tensor .name == "blk.1.ple_key.weight" && !ref .quantized ())continue ; 446if (!ref .quantized ()|| tensor .shape .size ()!= 2 || 447ref .ne0 <=0 || ref .ne0 > INT_MAX || ref .ne1 <=0 || ref .ne1 > INT_MAX || 448tensor .shape [0 ]!= (uint64_t )ref .ne0 || tensor .shape [1 ]!= (uint64_t )ref .ne1 ) { 449err = "native dense: incompatible matrix " + tensor .name ;return false; 450 } 451const auto bytes = strata::kernels::native_mmvq_weight_bytes ( 452tensor .type , (int )ref .ne0 , (int )ref .ne1 ); 453void * allocation = nullptr ; 454auto status = cudaMalloc (& allocation ,bytes ); 455DevicePtr data (allocation ); 456if (status == cudaSuccess ) 457status = cudaMemcpy (data .get (),gguf .tensor_data (tensor ),bytes ,cudaMemcpyHostToDevice ); 458if (status != cudaSuccess ) { 459err = "native dense upload " + tensor .name + ": " + cudaGetErrorString (status );return false; 460 } 461max_in = (std::max )(max_in , (int )ref .ne0 ); 462total += bytes ; 463allocated += alloc_bytes (bytes ); 464 { 465const int64_t layer = layer_of (tensor .name ); 466if (layer >=0 ) { 467if (per_layer .size () <= (size_t )layer )per_layer .resize ((size_t )layer + 1 ,0 ); 468per_layer [(size_t )layer ]+= bytes ; 469 } 470 } 471// STRATA_Q8_PACKED=1: a second, packed copy of an eligible Q8_0 matrix for the decode MMVQ (the GGUF 472// copy stays: the prompt path's GEMMs read it). 473DevicePtr packed ; 474if (tensor .type == 8 && tensor .name != "blk.1.ple_key.weight" && // the PLE has its own kernel 475 strata::kernels::native_q8_0_packed_enabled ()&& 476 strata::kernels::native_q8_0_packed_eligible ((int )ref .ne0 , (int )ref .ne1 )) { 477 std::vector < uint8_t > host (bytes ); 478 strata::kernels::native_q8_0_pack_host (gguf .tensor_data (tensor ),host .data (), (int )ref .ne0 , 479 (int )ref .ne1 ); 480void * packed_allocation = nullptr ; 481auto packed_status = cudaMalloc (& packed_allocation ,bytes ); 482packed .reset (packed_allocation ); 483if (packed_status == cudaSuccess ) 484packed_status = cudaMemcpy (packed .get (),host .data (),bytes ,cudaMemcpyHostToDevice ); 485if (packed_status != cudaSuccess ) { 486err = "native dense packed upload " + tensor .name + ": " + cudaGetErrorString (packed_status ); 487return false; 488 } 489 } 490if (strata::core::manifest::enabled ()) {// STRATA_MANIFEST: the dense formats as held, and the packed copies 491 strata::core::manifest::instance ().tensors ("dense" , strata::ggml_type_name ((uint32_t )tensor .type ),1 ,bytes ); 492if (packed ) strata::core::manifest::instance ().tensors ("dense_packed_copy" ,"Q8_0" ,1 ,bytes ); 493 } 494pending .push_back (Pending {& ref , (int )tensor .type ,bytes , std::move (data ), std::move (packed )}); 495 } 496if (strata::core::manifest::enabled ()) { 497const char * v = std::getenv ("STRATA_HC_Q8" ); 498 strata::core::manifest::instance ().path ("dense" ,"hc_q8" ,hc_q8_env (), 499hc_q8_env () ? (v != nullptr && v [0 ]== '1' ?"STRATA_HC_Q8=1" :"architecture default (gfx12 / gfx1151 HIP)" ) 500 : (v != nullptr && v [0 ]!= '\0' && std::strcmp (v ,"auto" )!= 0 ?"STRATA_HC_Q8 turned it off" 501 :"off by default on this backend" )); 502 } 503if (hc_q8_env ()) 504for (const auto & tensor :gguf .tensors ()) { 505// S25: the F32 inject rows hold BF16-exact values: the read takes the pack's BF16 rows unless 506// STRATA_HC_Q8_INJECT=1 asks for a Q8_0 copy 507const bool f32_inject = hc_q8_inject_env ()&& tensor .type == 0 && tensor .name .ends_with ("_inject.weight" ); 508if ((tensor .type != 8 && !f32_inject )|| !hc_q8_name (tensor .name )|| tensor .shape .size ()!= 2 )continue ; 509// a trimmed layer split: another stage's layers are never read here, so their rows are not copied (the upload 510// loop above and the bf16 pack path below already filter this way; PR #3559, havok2-htwo). 511// STRATA_HC_Q8_ALL_STAGES=1 copies them as before. 512if (hc_q8_stage_local ()&& (outside (tensor .name )|| !in_range (tensor .name ))) { 513hc_q8_skipped_bytes += (uint64_t )tensor .shape [0 ] /32 * 34 * (uint64_t )tensor .shape [1 ]; 514++ hc_q8_skipped ; 515continue ; 516 } 517auto found = table .table_ .find (tensor .name ); 518if (found == table .table_ .end ()|| found -> second .hc_q8 != nullptr )continue ; 519auto & ref = found -> second ; 520if (tensor .shape [0 ]!= (uint64_t )ref .ne0 || tensor .shape [1 ]!= (uint64_t )ref .ne1 || ref .ne0 %32 != 0 ) { 521err = "native dense (STRATA_HC_Q8): incompatible matrix " + tensor .name ;return false; 522 } 523const uint64_t bytes = (uint64_t )ref .ne0 /32 * 34 * (uint64_t )ref .ne1 ; 524void * p = nullptr ; 525 std::vector < uint8_t > q8 ; 526if (f32_inject )q8 = q8_0_of ((const float * )gguf .tensor_data (tensor ), (uint64_t )ref .ne0 * (uint64_t )ref .ne1 ); 527if (cudaMalloc (& p ,bytes )!= cudaSuccess || 528cudaMemcpy (p ,f32_inject ? (const void * )q8 .data () :gguf .tensor_data (tensor ),bytes , 529cudaMemcpyHostToDevice )!= cudaSuccess ) { 530err = "native dense (STRATA_HC_Q8) upload " + tensor .name ;return false; 531 } 532ref .hc_q8 = p ; 533weights_ .push_back (p ); 534hc_q8_bytes += bytes ; 535allocated += alloc_bytes (bytes ); 536 strata::core::manifest::instance ().tensors ("dense_hc_q8_copy" ,f32_inject ?"F32->Q8_0" :"Q8_0" ,1 ,bytes ); 537 } 538 } 539if (hc_q8_env ()) { 540// a bf16 pack stores no Q8_0 copy: quantize the layers' down / up projections. A row the arena kept 541// (--keep-canonical, a layer split) is quantized on the GPU from the arena's bf16; a skipped row (the 542// single-GPU default: add_hc_skip) from the pack file on the host, and has no bf16 copy at all. The 543// inject rows stay bf16 (82 KB), the final mixer stays bf16 (it runs once a window). 544uint64_t made = 0 ; 545for (auto & [name ,ref ] :table .table_ ) { 546if (ref .hc_q8 != nullptr || name .rfind ("blk." ,0 )!= 0 || !in_range (name )|| 547 !hc_q8_name (name )|| !(name .ends_with ("_down.weight" )|| name .ends_with ("_up.weight" )))continue ; 548const bool skipped = ref .data == nullptr ; 549if (skipped && ref .resident )continue ; 550if (ref .ne0 %32 != 0 || ref .elements != ref .ne0 * ref .ne1 || (!skipped && ref .bytes != (uint64_t )ref .elements * 2 )) { 551err = "native dense (STRATA_HC_Q8): " + name + " is not a bf16 matrix" ;return false; 552 } 553const uint64_t nb = (uint64_t )ref .elements /32 ,bytes = nb * 34 ; 554void * p = nullptr ; 555if (cudaMalloc (& p ,bytes )!= cudaSuccess ) {err = "native dense (STRATA_HC_Q8) alloc " + name ;return false; } 556weights_ .push_back (p ); 557if (skipped ) { 558 std::vector < uint16_t > host ; 559if (!table .read_bf16_host (name ,host ,err ))return false; 560const std::vector < uint8_t > q8 = q8_0_of_bf16 (host .data (), (uint64_t )host .size ()); 561if (cudaMemcpy (p ,q8 .data (),bytes ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 562err = "native dense (STRATA_HC_Q8) upload " + name ;return false; 563 } 564 }else { 565 strata::kernels::fused_gr_quantize_q8_0 ((const uint16_t * )ref .data , (uint8_t * )p , (int64_t )nb ,nullptr ); 566 } 567ref .hc_q8 = p ; 568hc_q8_bytes += bytes ; 569allocated += alloc_bytes (bytes ); 570++ made ; 571 } 572if (made && (cudaGetLastError ()!= cudaSuccess || cudaDeviceSynchronize ()!= cudaSuccess )) { 573err = "native dense (STRATA_HC_Q8): quantizing the projections failed" ;return false; 574 } 575 } 576if (hc_q8_env ()) {// the scratches of hc_bf16_view (rows without a bf16 copy), here and not on first use 577uint64_t elems = 0 ; 578for (const auto & [name ,ref ] :table .table_ ) 579if (ref .hc_q8 != nullptr && ref .data == nullptr )elems = (std::max )(elems , (uint64_t )ref .elements ); 580int dev = 0 ; 581if (elems != 0 && cudaGetDevice (& dev )== cudaSuccess && dev >=0 && dev < 64 && g_hc_scratch [dev ][0 ][0 ]== nullptr ) { 582for (int c = 0 ;c < 2 ;++ c ) 583for (int i = 0 ;i < 2 ;++ i ) { 584void * b = nullptr ; 585if (cudaMalloc (& b , (size_t )elems * 2 )!= cudaSuccess ) {err = "native dense (STRATA_HC_Q8): scratch alloc" ;return false; } 586weights_ .push_back (b ); 587g_hc_scratch [dev ][c ][i ]= b ; 588 } 589for (int i = 0 ;i < 2 ;++ i ) 590if (g_hc_ev [dev ][i ]== nullptr && cudaEventCreateWithFlags (& g_hc_ev [dev ][i ],cudaEventDisableTiming )!= cudaSuccess ) { 591err = "native dense (STRATA_HC_Q8): scratch event" ;return false; 592 } 593 } 594 } 595// Edge0 latent / all-BF16 native shards: every projection is canonical-pack BF16 and the GEMMs read it 596// from the arena ("BF16 weights as they are"); no native quantization to publish, and nothing left to do. 597if (pending .empty ())return true; 598void * allocation = nullptr ; 599const auto status = cudaMalloc (& allocation , strata::kernels::native_q8_1_bytes (max_in )); 600DevicePtr scratch (allocation ); 601if (status != cudaSuccess ) {err = std::string ("native dense scratch: " )+ cudaGetErrorString (status );return false; }// All checks and allocations finish before publishing any reference. 602weights_ .reserve (pending .size ()); 603uint64_t packed_bytes = 0 ; 604size_t packed_count = 0 ; 605for (auto & item :pending ) { 606item .ref -> native_data = item .data .get (); 607item .ref -> native_type = item .type ; 608item .ref -> native_q8_1 = scratch .get (); 609if (item .packed ) { 610 strata::kernels::native_q8_0_packed_register (item .data .get (),item .packed .get (), (int )item .ref -> ne0 , 611 (int )item .ref -> ne1 ); 612packed_keys_ .push_back (item .data .get ()); 613packed_bytes += item .bytes ; 614++ packed_count ; 615weights_ .push_back (item .packed .release ()); 616 } 617weights_ .push_back (item .data .release ()); 618 } 619if (packed_count ) 620 std::fprintf (stderr ,"native dense: STRATA_Q8_PACKED=1 packed %zu Q8_0 matrices for decode (+%.1f MiB)\n" , 621packed_count ,packed_bytes /1048576.0 ); 622scratch_ = scratch .release (); 623bytes_ = total + hc_q8_bytes ; 624layer_bytes_ = std::move (per_layer ); 625allocated_ = allocated ; 626if (hc_q8_skipped != 0 && strata::core::manifest::enabled ())// STRATA_MANIFEST: what the stage filter did not copy 627 strata::core::manifest::instance ().tensors ("dense_hc_q8_out_of_stage_not_copied" ,"Q8_0" ,hc_q8_skipped ,hc_q8_skipped_bytes ); 628if (hc_q8_env ()) 629 std::fprintf (stderr ,"strata: STRATA_HC_Q8=1: %.2f GiB of Q8_0 hyper-connection projections for the verify read\n" , 630 (double )hc_q8_bytes /1073741824.0 ); 631return true; 632 }catch (const std::exception & error ) { 633err = std::string ("native dense: " )+ error .what (); 634return false; 635 } 636} 637bool NativeDense ::gguf_carries_q8_hc (const std::vector < std::string >& shards ) { 638try { 639for (const auto & path :shards ) { 640const strata::GgufFile g (path ); 641for (const auto & tensor :g .tensors ()) 642if (tensor .type == 8 && tensor .shape .size ()== 2 && hc_q8_name (tensor .name )&& !tensor .name .ends_with ("_inject.weight" ))return true; 643 } 644 }catch (const std::exception & ) {} 645return false; 646} 647 648bool NativeDense ::apply_hc_q8_default (const std::vector < std::string >& shards ) { 649if (std::getenv ("STRATA_HC_Q8" )!= nullptr || !gguf_carries_q8_hc (shards ))return false; 650#if defined(_WIN32 ) 651_putenv_s ("STRATA_HC_Q8" ,"1" ); 652#else 653setenv ("STRATA_HC_Q8" ,"1" ,0 ); 654#endif 655return true; 656} 657 658bool NativeDense ::hc_q8_requested () {return hc_q8_env (); } 659 660bool NativeDense ::add_hc_skip (const std::string & pack_dir , std::set < std::string >& skip ) { 661 std::FILE * f = std::fopen ((pack_dir + "/index.txt" ).c_str (),"rb" ); 662if (!f )return false; 663char line [1024 ],name [256 ]; 664while (std::fgets (line ,sizeof line ,f )) { 665if (line [0 ]== '#' || std::sscanf (line ,"%255s" ,name )!= 1 )continue ; 666const std::string n = name ; 667if (n .rfind ("blk." ,0 )== 0 && hc_q8_name (n )&& (n .ends_with ("_down.weight" )|| n .ends_with ("_up.weight" )))skip .insert (n ); 668 } 669 std::fclose (f ); 670return true; 671} 672 673const uint16_t * NativeDense ::hc_bf16_view (const WeightRef & w ,void * stream ,int slot ,int cls ) { 674if (w .data != nullptr )return (const uint16_t * )w .data ; 675if (w .hc_q8 == nullptr )return nullptr ; 676// the device's scratch (allocated at load, one pair per device): the prompt path and the single-token read run one 677// after the other on a device, and each use is stream-ordered after the previous GEMM that read the slot 678int dev = 0 ; 679if (cudaGetDevice (& dev )!= cudaSuccess || dev < 0 || dev >=64 || slot < 0 || slot > 1 || cls < 0 || cls > 1 )return nullptr ; 680void * buf = g_hc_scratch [dev ][cls ][slot ]; 681if (buf == nullptr )return nullptr ; 682// the prompt path: the scratch may still be read by a GEMM another stream enqueued (batch serving: several slots' prompts) 683if (cls == 0 && g_hc_ev_set [dev ][slot ])cudaStreamWaitEvent ((cudaStream_t )stream ,g_hc_ev [dev ][slot ],0 ); 684 strata::kernels::fused_gr_dequant_q8_0 ((const uint8_t * )w .hc_q8 , (uint16_t * )buf ,w .elements /32 ,stream ); 685return (const uint16_t * )buf ; 686} 687 688void NativeDense ::hc_bf16_release (void * stream ,int slot ,int cls ) { 689int dev = 0 ; 690if (cls != 0 || slot < 0 || slot > 1 || cudaGetDevice (& dev )!= cudaSuccess || dev < 0 || dev >=64 || g_hc_ev [dev ][slot ]== nullptr )return ; 691cudaEventRecord (g_hc_ev [dev ][slot ], (cudaStream_t )stream ); 692g_hc_ev_set [dev ][slot ]= true; 693} 694}// namespace strata::core