okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f8c748fdf
main
1// src/core/weights.cpp - the dense-weight loader. See the header for the engine-vs-pack distinction. 2#include "strata/core/weights.hpp" 3#include <vector> 4#include <cmath> 5 6#include "strata/kernels/f16_bits.hpp" 7#include "strata/platform/memory.hpp" 8 9#include <cinttypes> 10#include <cuda_runtime.h> 11 12#include <chrono> 13#include <algorithm> 14#include <cstdio> 15#include <cstdlib> 16#include <cstring> 17 18#if defined(_WIN32 ) 19#include <io.h> 20#else 21#include <unistd.h> 22#endif 23 24namespace strata::core { 25namespace { 26 27constexpr uint64_t CHUNK = 8ull <<20 ;// 8 MiB of SOURCE per staging round 28 29double now_ms () { 30using namespace std::chrono ; 31return duration < double , std::milli > (steady_clock::now ().time_since_epoch ()).count (); 32} 33 34struct IndexRow { 35 std::string name ; 36int file = 0 ; 37WeightKind kind = WeightKind ::Verbatim ; 38uint64_t src_off = 0 ,src_bytes = 0 ,dst_off = 0 ,dst_bytes = 0 ; 39int64_t ne0 = 0 ,ne1 = 0 ; 40int code_bits = 0 ,code_bias = 0 ,group_elems = 0 ,codebook = 0 ,has_offset = 0 ; 41uint64_t codes_bytes = 0 ,scales_bytes = 0 ,offset_bytes = 0 ; 42int scales_fp16 = 0 ; 43int act_kind = 0 ; 44bool raw16 = false;///< plan v0.3 P6: already 16-bit in the file (kinds 4/5) 45}; 46 47/// How a segment's bytes must be transformed on the way from the pack to the arena. 48enum class Conv :int { 49Copy = 0 ,///< the bytes are already the engine form 50Bf16High = 1 ,///< f32 container holding a bf16 value: take the high 16 bits 51ToF16 = 2 ,///< f32 container holding an f16 value: a real round-to-nearest-even conversion 52WidenF16 = 3 ,///< fp16 bits to be held as f32: EXACT, and the reason this path exists at all 53}; 54 55/// One contiguous run of a tensor's source span with a single destination range and one transform. 56/// 57/// THE SEGMENT LIST IS WHY THIS LOADER CAN CHANGE WIDTHS PLANE BY PLANE. A quantized tensor used to be one 58/// verbatim span, which is only correct when every plane is already in engine form - and for 90 of the 303 59/// quantized tensors the scale plane is fp16 in the pack and must be f32 in the arena. 60struct Seg { 61uint64_t src_off = 0 ;///< relative to the row's src_off 62uint64_t src_bytes = 0 ; 63uint64_t dst_off = 0 ;///< relative to the row's dst_off 64uint64_t dst_bytes = 0 ; 65Conv conv = Conv ::Copy ; 66}; 67 68const char * file_name (int id ) { 69switch (id ) { 70case 0 :return "dense.bin" ; 71case 1 :return "embd.bin" ; 72case 2 :return "experts.bin" ; 73case 3 :return "extra.bin" ;// plan v0.3 P6: a native pack's float tensors that the base pack quantized 74default :return nullptr ; 75 } 76} 77 78/// UTF-16 path for CreateFile-free portability: the loader uses `std::fopen`, which on Windows takes an ANSI 79/// path. The pack lives beside the executable in practice, but a pack under a user directory with a 80/// non-ASCII name would silently fail to open, so the caller gets the errno rather than a null pointer. 81bool read_at (std::FILE * f ,uint64_t off ,void * dst ,size_t n , std::string & err ,const char * what ) { 82#if defined(_WIN32 ) 83if (_fseeki64 (f , (long long )off ,SEEK_SET )!= 0 ) {err = std::string (what )+ ": seek failed" ;return false; } 84#else 85if (fseeko (f , (off_t )off ,SEEK_SET )!= 0 ) {err = std::string (what )+ ": seek failed" ;return false; } 86#endif 87if (std::fread (dst ,1 ,n ,f )!= n ) {err = std::string (what )+ ": short read" ;return false; } 88return true; 89} 90 91}// namespace 92 93bool WeightTable ::pool_bytes (const std::string & pack_dir ,uint64_t & out , std::string & err , 94const std::set < std::string >* skip ) { 95const std::string path = pack_dir + "/index.txt" ; 96 std::FILE * f = std::fopen (path .c_str (),"rb" ); 97if (!f ) {err = "cannot open " + path ;return false; } 98char line [1024 ]; 99out = 0 ; 100uint64_t pool = 0 ,compact = 0 ; 101int align = 0 ; 102while (std::fgets (line ,sizeof line ,f )) { 103if (line [0 ]== '#' ) { 104unsigned long long p = 0 ; 105int a = 0 ,tensors = 0 ; 106if (std::sscanf (line ,"# align %d pool %llu tensors %d" ,& a ,& p ,& tensors )== 3 ) {pool = p ;align = a ; } 107continue ; 108 } 109if (skip == nullptr )continue ; 110char name [256 ]= {0 }; 111unsigned long long dst_bytes = 0 ,dummy = 0 ; 112int i1 = 0 ,i2 = 0 ; 113if (std::sscanf (line ,"%255s %d %d %llu %llu %llu %llu" ,name ,& i1 ,& i2 ,& dummy ,& dummy ,& dummy ,& dst_bytes )!= 7 ) 114continue ; 115if (skip -> count (name ))continue ; 116const uint64_t a = align > 0 ? (uint64_t )align :256 ; 117compact += (dst_bytes + a - 1 ) /a * a ; 118 } 119 std::fclose (f ); 120if (pool == 0 ) {err = "no '# align ... pool ...' header in " + path ;return false; } 121out = skip ?compact :pool ; 122return true; 123} 124 125bool WeightTable ::index_code_bits (const std::string & pack_dir ,const std::string & name ,int & code_bits , 126 std::string & err ) { 127const std::string path = pack_dir + "/index.txt" ; 128 std::FILE * f = std::fopen (path .c_str (),"rb" ); 129if (!f ) {err = "cannot open " + path ;return false; } 130char line [1024 ]; 131code_bits = -1 ; 132while (std::fgets (line ,sizeof line ,f )) { 133if (line [0 ]== '#' )continue ; 134char row [256 ]= {0 }; 135unsigned long long dummy = 0 ; 136long long ne = 0 ; 137int i1 = 0 ,i2 = 0 ,bits = 0 ; 138// the first ten fields of the row `load` parses: name file kind src_off src_bytes dst_off dst_bytes ne0 ne1 code_bits 139if (std::sscanf (line ,"%255s %d %d %llu %llu %llu %llu %lld %lld %d" ,row ,& i1 ,& i2 ,& dummy ,& dummy ,& dummy , 140& dummy ,& ne ,& ne ,& bits )!= 10 ) 141continue ; 142if (name == row ) {code_bits = bits ;break ; } 143 } 144 std::fclose (f ); 145return true; 146} 147 148bool WeightTable ::read_bf16_host (const std::string & name , std::vector < uint16_t >& out , std::string & err )const { 149const auto it = table_ .find (name ); 150if (it == table_ .end ()) {err = name + ": no such tensor" ;return false; } 151const WeightRef & r = it -> second ; 152const char * fn = file_name (r .file_id ); 153if (fn == nullptr || r .kind != WeightKind ::Bf16InF32 ) {err = name + ": not a bf16 row of a pack file" ;return false; } 154const uint64_t elems = (uint64_t )r .elements ; 155const bool raw16 = r .src_bytes == elems * 2 ; 156if (!raw16 && r .src_bytes != elems * 4 ) {err = name + ": unexpected source size" ;return false; } 157 std::FILE * f = std::fopen ((pack_dir_ + "/" + fn ).c_str (),"rb" ); 158if (!f ) {err = "cannot open " + pack_dir_ + "/" + fn ;return false; } 159out .resize ((size_t )elems ); 160bool ok = true; 161if (raw16 ) { 162ok = read_at (f ,r .src_off ,out .data (), (size_t ) (elems * 2 ),err ,name .c_str ()); 163 }else { 164 std::vector < uint32_t > tmp ((size_t ) std::min < uint64_t > (elems ,1u <<22 )); 165for (uint64_t done = 0 ;ok && done < elems ;) { 166const uint64_t n = std::min < uint64_t > (tmp .size (),elems - done ); 167ok = read_at (f ,r .src_off + done * 4 ,tmp .data (), (size_t ) (n * 4 ),err ,name .c_str ()); 168for (uint64_t i = 0 ;ok && i < n ;++ i )out [(size_t ) (done + i )]= (uint16_t ) (tmp [(size_t )i ] >>16 ); 169done += n ; 170 } 171 } 172 std::fclose (f ); 173return ok ; 174} 175 176bool WeightTable ::load (const std::string & pack_dir ,void * arena_base ,uint64_t arena_bytes , std::string & err , 177const std::set < std::string >* skip ) { 178const std::string path = pack_dir + "/index.txt" ; 179 std::FILE * idx = std::fopen (path .c_str (),"rb" ); 180if (!idx ) {err = "cannot open " + path + " (run tools/pack_index.py)" ;return false; } 181 182uint64_t pool = 0 ; 183int align = 0 ; 184 std::vector < IndexRow > rows ; 185char line [1024 ]; 186while (std::fgets (line ,sizeof line ,idx )) { 187if (line [0 ]== '#' ) { 188unsigned long long p = 0 ; 189int a = 0 ,t = 0 ; 190if (std::sscanf (line ,"# align %d pool %llu tensors %d" ,& a ,& p ,& t )== 3 ) {pool = p ;align = a ; } 191continue ; 192 } 193IndexRow r ; 194char name [256 ]= {0 }; 195int kind = 0 ; 196// The format is written by tools/pack_index.py and is space-separated with no quoting; a name with a 197// space in it would break the parse, which is why the parser REFUSES rather than taking what it got. 198const int n = std::sscanf (line , 199"%255s %d %d %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNu64 " %" SCNd64 " %" SCNd64 " %d %d %d %d %d %" SCNu64 " %" SCNu64 " %" SCNu64 " %d %d" , 200name ,& r .file ,& kind ,& r .src_off ,& r .src_bytes ,& r .dst_off ,& r .dst_bytes , 201& r .ne0 ,& r .ne1 ,& r .code_bits ,& r .code_bias ,& r .group_elems ,& r .codebook , 202& r .has_offset ,& r .codes_bytes ,& r .scales_bytes ,& r .offset_bytes , 203& r .scales_fp16 ,& r .act_kind ); 204if (n != 19 ) { 205// A malformed index line is a WRONG BYTE OFFSET waiting to happen, and a wrong offset decodes to 206// a plausible weight. Refuse loudly instead of loading the rows that happened to parse. 207err = "index.txt: could not parse a row (" + std::to_string (n )+ " of 19 fields)" ; 208 std::fclose (idx ); 209return false; 210 } 211r .name = name ; 212// plan v0.3 P6: a standalone native pack (tools/iq_pack.py) stores 16-bit floats as they are in the GGUF: 213// index kinds 4 (BF16) and 5 (F16) are copied and take the engine forms of kinds 1 and 3 214if (kind == 4 || kind == 5 ) { 215r .raw16 = true; 216kind = kind == 4 ? (int )WeightKind ::Bf16InF32 : (int )WeightKind ::F16InF32 ; 217 } 218r .kind = (WeightKind )kind ; 219rows .push_back (r ); 220 } 221 std::fclose (idx ); 222 223if (pool == 0 || rows .empty ()) {err = "index.txt has no header or no rows" ;return false; } 224// Plan v0.3 P1: a skip set compacts the arena. Kept rows are re-placed in index order at the index's 225// alignment; skipped rows keep their metadata and get no bytes. 226 std::vector < bool > skipped (rows .size (), false); 227if (skip != nullptr ) { 228const uint64_t a = align > 0 ? (uint64_t )align :256 ; 229uint64_t at = 0 ; 230for (size_t i = 0 ;i < rows .size ();++ i ) { 231if (skip -> count (rows [i ].name )) {skipped [i ]= true;continue ; } 232rows [i ].dst_off = at ; 233at += (rows [i ].dst_bytes + a - 1 ) /a * a ; 234 } 235pool = at ; 236 } 237if (arena_bytes < pool ) { 238err = "arena is " + std::to_string (arena_bytes )+ " B but the index needs " + std::to_string (pool ); 239return false; 240 } 241 242// Two pinned staging buffers, both reused. Pinned because a 5 GB pageable upload spends its time in the 243// driver copying through a bounce buffer, and bounded by CHUNK rather than by the largest tensor. 244// 245// STAGE_OUT IS NOT OPTIONAL. The first version of this loop converted the values straight into the 246// destination pointer - which is DEVICE memory - from host code. A host write to a device address is 247// undefined behaviour, and on this driver it does not fault: it corrupts whatever the address maps to in 248// the host's own space, which is nothing at all, so the tensor would have loaded as the UNCONVERTED pack 249// bytes and every BF16 weight would have been read as 32-bit garbage. Converted data goes to a host 250// buffer and crosses the bus once. 251// 252// STAGE_OUT IS TWICE STAGE_IN because a conversion can now GROW: widening an fp16 scale plane to f32 253// doubles it. Sized at CHUNK it would have written 8 MiB past the end of a pinned allocation for every 254// one of the 90 widened tensors - a heap corruption that would have been blamed on whatever ran next. 255void * stage_in = nullptr ; 256void * stage_out = nullptr ; 257if (cudaHostAlloc (& stage_in ,CHUNK ,cudaHostAllocDefault )!= cudaSuccess || 258cudaHostAlloc (& stage_out ,CHUNK * 2 ,cudaHostAllocDefault )!= cudaSuccess ) { 259err = "cudaHostAlloc for the staging buffers failed" ; 260if (stage_in )cudaFreeHost (stage_in ); 261if (stage_out )cudaFreeHost (stage_out ); 262return false; 263 } 264 265uint8_t * dst_base = (uint8_t * )arena_base ; 266 std::FILE * cur = nullptr ; 267int cur_file = -1 ; 268table_ .clear (); 269report_ = LoadReport {}; 270pack_dir_ = pack_dir ; 271 272const double t_read0 = now_ms (); 273double upload_ms = 0 ; 274for (size_t row_i = 0 ;row_i < rows .size ();++ row_i ) { 275const IndexRow & r = rows [row_i ]; 276if (skipped [row_i ]) { 277WeightRef wr ; 278wr .data = nullptr ; 279wr .resident = false; 280wr .bytes = r .dst_bytes ; 281wr .ne0 = r .ne0 ; 282wr .ne1 = r .ne1 ; 283wr .elements = r .ne0 * (r .ne1 > 0 ?r .ne1 :1 ); 284wr .kind = r .kind ; 285wr .code_bits = r .code_bits ; 286wr .code_bias = r .code_bias ; 287wr .group_elems = r .group_elems ; 288wr .codebook_iq4nl = r .codebook != 0 ; 289wr .has_offset = r .has_offset != 0 ; 290wr .codes_bytes = r .codes_bytes ; 291wr .scales_bytes = r .scales_bytes ; 292wr .offset_bytes = r .offset_bytes ; 293wr .src_off = r .src_off ; 294wr .src_bytes = r .src_bytes ; 295wr .file_id = r .file ; 296wr .scales_fp16 = r .scales_fp16 != 0 ; 297wr .act_kind = r .act_kind ; 298table_ [r .name ]= wr ; 299++ report_ .tensors ; 300continue ; 301 } 302if (r .code_bits != 0 && r .dst_bytes == 0 ) { 303// plan v0.3 P6: a native pack's row that carries a shape only - the GGUF form must serve it 304err = r .name + ": this pack holds the tensor only in its GGUF form (run with --native SHARD1)" ; 305cudaFreeHost (stage_in );cudaFreeHost (stage_out ); 306return false; 307 } 308if (r .file != cur_file ) { 309if (cur ) std::fclose (cur ); 310const char * fn = file_name (r .file ); 311const std::string p = pack_dir + "/" + (fn ?fn :"?" ); 312cur = std::fopen (p .c_str (),"rb" ); 313if (!cur ) {err = "cannot open " + p ;cudaFreeHost (stage_in );cudaFreeHost (stage_out );return false; } 314cur_file = r .file ; 315#if !defined(_WIN32 ) 316// ask for this file's remaining rows up front so their reads overlap 317for (size_t j = row_i ;j < rows .size ();++ j ) 318if (rows [j ].file == r .file && !skipped [j ]) 319 strata::platform::advise_willneed (fileno (cur ),rows [j ].src_off ,rows [j ].src_bytes ); 320#endif 321 } 322 323// ---- the segment list: what this tensor's bytes are, plane by plane, in both forms 324Seg segs [3 ]; 325int n_segs = 0 ; 326bool bad = false; 327uint64_t sum_src = 0 ,sum_dst = 0 ; 328if (r .codes_bytes != 0 ) { 329// A quantized tensor: codes, then scales, then the optional offset plane, each contiguous in the 330// source span in that order (pack_index.py verifies the contiguity and refuses otherwise). 331segs [n_segs ++ ]= Seg {0 ,r .codes_bytes ,0 ,r .codes_bytes ,Conv ::Copy }; 332if (r .scales_bytes ) { 333const uint64_t src_scale_bytes = r .scales_fp16 ?r .scales_bytes /2 :r .scales_bytes ; 334if (r .scales_fp16 && (r .scales_bytes %2 || src_scale_bytes * 2 != r .scales_bytes )) { 335err = r .name + ": an fp16 scale plane of an odd byte count" ; 336bad = true; 337 } 338segs [n_segs ++ ]= Seg {r .codes_bytes ,src_scale_bytes ,r .codes_bytes ,r .scales_bytes , 339r .scales_fp16 ?Conv ::WidenF16 :Conv ::Copy }; 340 } 341if (r .offset_bytes ) { 342const uint64_t after = r .codes_bytes + (r .scales_fp16 ?r .scales_bytes /2 :r .scales_bytes ); 343segs [n_segs ++ ]= Seg {after ,r .offset_bytes ,r .codes_bytes + r .scales_bytes ,r .offset_bytes , 344Conv ::Copy }; 345 } 346 }else { 347// Everything else is one run whose transform is the row's kind. The two promoted types shrink 348// 4 B/elem to 2; the rest are already the engine form. 349Conv c = Conv ::Copy ; 350if (r .raw16 )c = Conv ::Copy ; 351else if (r .kind == WeightKind ::Bf16InF32 )c = Conv ::Bf16High ; 352else if (r .kind == WeightKind ::F16InF32 )c = Conv ::ToF16 ; 353const uint64_t elems = (uint64_t )r .ne0 * (uint64_t ) (r .ne1 > 0 ?r .ne1 :1 ); 354if (c != Conv ::Copy && (r .src_bytes != elems * 4 || r .dst_bytes != elems * 2 )) { 355// A promoted type is 4 B/elem in and 2 B/elem out, and nothing else. If those two numbers do 356// not say so, the shape and the byte counts disagree and the element count this loop would 357// use to walk the source is not the element count the pack wrote. 358char buf [320 ]; 359 std::snprintf (buf ,sizeof buf , 360"%s: a promoted tensor of %llu elements is %llu B in and %llu B out, not %llu/%llu" , 361r .name .c_str (), (unsigned long long )elems , (unsigned long long )r .src_bytes , 362 (unsigned long long )r .dst_bytes , (unsigned long long ) (elems * 4 ), 363 (unsigned long long ) (elems * 2 )); 364err = buf ; 365bad = true; 366 } 367segs [n_segs ++ ]= Seg {0 ,r .src_bytes ,0 ,r .dst_bytes ,c }; 368 } 369for (int i = 0 ;i < n_segs ;++ i ) {sum_src += segs [i ].src_bytes ;sum_dst += segs [i ].dst_bytes ; } 370// The segment list is this loop's own idea of the layout, and it is the ONLY thing standing between a 371// mis-sized plane and a wrong byte offset. It is checked against both recorded totals, not trusted. 372if (!bad && (sum_src != r .src_bytes || sum_dst != r .dst_bytes )) { 373char buf [360 ]; 374 std::snprintf (buf ,sizeof buf , 375"%s: the segments cover %llu/%llu B but the index says %llu/%llu - the plane layout " 376"this loader built is not the one the index describes" , 377r .name .c_str (), (unsigned long long )sum_src , (unsigned long long )sum_dst , 378 (unsigned long long )r .src_bytes , (unsigned long long )r .dst_bytes ); 379err = buf ; 380bad = true; 381 } 382if (bad ) {cudaFreeHost (stage_in );cudaFreeHost (stage_out );return false; } 383 384for (int si = 0 ;si < n_segs ;++ si ) { 385const Seg & s = segs [si ]; 386const bool widening = (s .conv == Conv ::WidenF16 ); 387if (widening && (s .src_bytes & 1ull )) { 388err = r .name + ": an fp16 plane with an odd source byte count" ; 389cudaFreeHost (stage_in );cudaFreeHost (stage_out ); 390return false; 391 } 392uint64_t done = 0 ; 393while (done < s .src_bytes ) { 394uint64_t n = std::min (CHUNK ,s .src_bytes - done ); 395// WIDENING NEVER SPLITS AN ELEMENT. CHUNK is even, so a full chunk cannot, but the tail of a 396// plane whose length is odd would - and half an fp16 is a plausible-looking scale. 397if (widening && (n & 1ull )) { 398if (n == 1 ) {err = r .name + ": an fp16 plane ending on a half element" ;cudaFreeHost (stage_in );cudaFreeHost (stage_out );return false; } 399n -= 1 ; 400 } 401if (!read_at (cur ,r .src_off + s .src_off + done ,stage_in , (size_t )n ,err ,r .name .c_str ())) { 402cudaFreeHost (stage_in );cudaFreeHost (stage_out ); 403return false; 404 } 405const uint8_t * src = (const uint8_t * )stage_in ; 406const void * host_src = src ; 407uint64_t out_bytes = n ; 408uint64_t out_at = s .dst_off + done ; 409 410switch (s .conv ) { 411case Conv ::Copy : 412break ; 413case Conv ::Bf16High : { 414// THE HIGH 16 BITS ARE THE BF16 ENCODING, exactly - not a rounding. A bf16 value is 415// the top half of its f32 image, and the pack promoted it without changing it, so 416// this is a copy with a stride. 417const uint64_t elems = n /4 ; 418out_bytes = elems * 2 ; 419uint8_t * o = (uint8_t * )stage_out ; 420for (uint64_t i = 0 ;i < elems ;++ i ) { 421uint32_t v ; 422 std::memcpy (& v ,src + i * 4 ,4 ); 423const uint16_t h = (uint16_t ) (v >>16 ); 424 std::memcpy (o + i * 2 ,& h ,2 ); 425 } 426host_src = stage_out ; 427out_at = s .dst_off + done /2 ; 428break ; 429 } 430case Conv ::ToF16 : { 431const uint64_t elems = n /4 ; 432out_bytes = elems * 2 ; 433uint8_t * o = (uint8_t * )stage_out ; 434for (uint64_t i = 0 ;i < elems ;++ i ) { 435float v ; 436 std::memcpy (& v ,src + i * 4 ,4 ); 437const uint16_t h = strata::kernels::f16_from_f32 (v ); 438 std::memcpy (o + i * 2 ,& h ,2 ); 439 } 440host_src = stage_out ; 441out_at = s .dst_off + done /2 ; 442break ; 443 } 444case Conv ::WidenF16 : { 445// fp16 bits -> f32. EXACT: every fp16 value is an f32 value, including the 446// subnormals, so this cannot change a single weight - which is why the engine may do 447// it at all, and why doing it costs 10.88 MiB rather than a second kernel family. 448const uint64_t elems = n /2 ; 449out_bytes = elems * 4 ; 450float * o = (float * )stage_out ; 451for (uint64_t i = 0 ;i < elems ;++ i ) { 452uint16_t h ; 453 std::memcpy (& h ,src + i * 2 ,2 ); 454o [i ]= strata::kernels::f32_from_f16 (h ); 455 } 456host_src = stage_out ; 457out_at = s .dst_off + done * 2 ; 458break ; 459 } 460 } 461 462const double u0 = now_ms (); 463if (cudaMemcpy (dst_base + r .dst_off + out_at ,host_src ,out_bytes ,cudaMemcpyHostToDevice )!= 464cudaSuccess ) { 465err = "cudaMemcpy failed for " + r .name ; 466cudaFreeHost (stage_in );cudaFreeHost (stage_out ); 467return false; 468 } 469upload_ms += now_ms ()- u0 ; 470done += n ; 471 } 472 } 473 474WeightRef wr ; 475wr .data = dst_base + r .dst_off ; 476wr .bytes = r .dst_bytes ; 477wr .ne0 = r .ne0 ; 478wr .ne1 = r .ne1 ; 479wr .elements = r .ne0 * (r .ne1 > 0 ?r .ne1 :1 ); 480wr .kind = r .kind ; 481wr .code_bits = r .code_bits ; 482wr .code_bias = r .code_bias ; 483wr .group_elems = r .group_elems ; 484wr .codebook_iq4nl = r .codebook != 0 ; 485wr .has_offset = r .has_offset != 0 ; 486wr .codes_bytes = r .codes_bytes ; 487wr .scales_bytes = r .scales_bytes ; 488wr .offset_bytes = r .offset_bytes ; 489wr .src_off = r .src_off ; 490wr .src_bytes = r .src_bytes ; 491wr .file_id = r .file ; 492wr .scales_fp16 = r .scales_fp16 != 0 ; 493wr .act_kind = r .act_kind ; 494table_ [r .name ]= wr ; 495 496++ report_ .tensors ; 497if ((r .kind == WeightKind ::Bf16InF32 || r .kind == WeightKind ::F16InF32 )&& !r .raw16 ) { 498++ report_ .re_rounded ; 499report_ .bytes_saved += r .src_bytes - r .dst_bytes ; 500 } 501 } 502if (cur ) std::fclose (cur ); 503cudaFreeHost (stage_in ); 504cudaFreeHost (stage_out ); 505 506report_ .arena_bytes = pool ; 507report_ .read_ms = now_ms ()- t_read0 - upload_ms ; 508report_ .upload_ms = upload_ms ; 509if (cudaDeviceSynchronize ()!= cudaSuccess ) {err = "cudaDeviceSynchronize after the load failed" ;return false; } 510return true; 511} 512 513const WeightRef * WeightTable ::find (const std::string & name )const { 514const auto it = table_ .find (name ); 515return it == table_ .end () ?nullptr :& it -> second ; 516} 517 518WeightRef * WeightTable ::find_mut (const std::string & name ) { 519const auto it = table_ .find (name ); 520return it == table_ .end () ?nullptr :& it -> second ; 521} 522 523void WeightTable ::hc_q8_names (int64_t n_layers , std::set < std::string >& out ) { 524for (int64_t l = 0 ;l < n_layers ;++ l ) 525for (const char * h : {"hc_attn_" ,"hc_ffn_" }) 526for (const char * m : {"down" ,"up" }) 527out .insert ("blk." + std::to_string (l )+ "." + h + m + ".weight" ); 528} 529 530bool WeightTable ::load_hc_q8 (const std::string & pack_dir ,uint64_t & bytes , std::string & err ) { 531bytes = 0 ; 532 std::vector < WeightRef *> todo ; 533for (auto & [name ,w ] :table_ ) { 534const bool hc = name .find (".hc_attn_down." )!= std::string::npos || name .find (".hc_attn_up." )!= std::string::npos || 535name .find (".hc_ffn_down." )!= std::string::npos || name .find (".hc_ffn_up." )!= std::string::npos ; 536if (!hc || w .resident )continue ; 537// the pack holds BF16 either promoted to f32 (4 B/elem) or as it is in the GGUF (a native pack, 2 B/elem) 538if (w .kind != WeightKind ::Bf16InF32 || w .ne0 %32 != 0 || 539 (w .src_bytes != (uint64_t )w .elements * 4 && w .src_bytes != (uint64_t )w .elements * 2 )) { 540err = "STRATA_HC_REQ8: " + name + " is not a BF16 tensor of whole 32-value blocks" ; 541return false; 542 } 543todo .push_back (& w ); 544 } 545if (todo .empty ())return true; 546auto al = [](uint64_t b ) {return (b + 255 )& ~(uint64_t )255 ; }; 547uint64_t total = 0 ; 548for (const WeightRef * w :todo )total += al ((uint64_t )w -> elements )+ al ((uint64_t )w -> elements /32 * 4 ); 549uint8_t * dev = nullptr ; 550if (cudaMalloc ((void ** )& dev ,total )!= cudaSuccess ) {err = "STRATA_HC_REQ8: cudaMalloc failed" ;return false; } 551 std::vector < float > src ; 552 std::vector < int8_t > q ; 553 std::vector < float > sc ; 554uint64_t at = 0 ; 555for (WeightRef * w :todo ) { 556const char * fn = file_name (w -> file_id ); 557const std::string path = pack_dir + "/" + (fn ?fn :"?" ); 558 std::FILE * f = std::fopen (path .c_str (),"rb" ); 559if (!f ) {err = "STRATA_HC_REQ8: cannot open " + path ;return false; } 560src .resize ((size_t )w -> elements ); 561const bool raw16 = w -> src_bytes == (uint64_t )w -> elements * 2 ; 562#if defined(_WIN32 ) 563bool ok = _fseeki64 (f , (long long )w -> src_off ,SEEK_SET )== 0 ; 564#else 565bool ok = fseeko (f , (off_t )w -> src_off ,SEEK_SET )== 0 ;// 64-bit: a pack's dense file can pass 2 GiB 566#endif 567if (ok && raw16 ) { 568 std::vector < uint16_t > h (src .size ()); 569ok = std::fread (h .data (),2 ,h .size (),f )== h .size (); 570for (size_t i = 0 ;ok && i < h .size ();++ i ) { 571const uint32_t b = (uint32_t )h [i ] <<16 ;// bf16 -> f32 is exact 572 std::memcpy (& src [i ],& b ,4 ); 573 } 574 }else if (ok ) { 575ok = std::fread (src .data (),4 ,src .size (),f )== src .size (); 576 } 577 std::fclose (f ); 578if (!ok ) {err = "STRATA_HC_REQ8: cannot read the source bytes" ;return false; } 579const size_t nb = src .size () /32 ; 580q .resize (src .size ()); 581sc .resize (nb ); 582for (size_t b = 0 ;b < nb ;++ b ) {// Q8_0's rule: d = amax / 127, q = round-to-nearest-even(x / d) 583float amax = 0.f ; 584for (int j = 0 ;j < 32 ;++ j )amax = std::max (amax , std::fabs (src [b * 32 + j ])); 585const float d = amax /127.f ,id = d > 0.f ?1.f /d :0.f ; 586sc [b ]= d ; 587for (int j = 0 ;j < 32 ;++ j )q [b * 32 + j ]= (int8_t ) std::nearbyint (src [b * 32 + j ]* id ); 588 } 589uint8_t * codes = dev + at ; 590at += al (q .size ()); 591float * scales = (float * ) (dev + at ); 592at += al (sc .size ()* 4 ); 593if (cudaMemcpy (codes ,q .data (),q .size (),cudaMemcpyHostToDevice )!= cudaSuccess || 594cudaMemcpy (scales ,sc .data (),sc .size ()* 4 ,cudaMemcpyHostToDevice )!= cudaSuccess ) { 595err = "STRATA_HC_REQ8: upload failed" ; 596return false; 597 } 598w -> data = codes ; 599w -> q8_scale = scales ; 600w -> resident = true; 601w -> bytes = q .size ()+ sc .size ()* 4 ; 602 } 603bytes = total ; 604return true; 605} 606 607}// namespace strata::core