okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4dad59ab3
main
1// src/kernels/ngram.cpp - P2.S4: the PLE n-gram hash and the IQ4_NL table read. 2// 3// See include/strata/kernels/ngram.hpp for the semantics, the rival readings, and the note on MADV_RANDOM. 4#include "strata/kernels/ngram.hpp" 5#include "strata/artifact/gguf_reader.hpp" 6#include "strata/artifact/dequant.hpp" 7#include "strata/kernels/f16_bits.hpp" 8#include "strata/ngram/ple_reader.hpp" 9#include "strata/platform/memory.hpp" 10 11#include <cerrno> 12#include <cmath> 13#include <cstdio> 14#include <cstdlib> 15#include <cstring> 16#include <fstream> 17#include <limits> 18#if !defined(_WIN32 ) 19#include <sys/mman.h> 20#include <sys/resource.h> 21#endif 22#include <algorithm> 23#include <atomic> 24#include <mutex> 25#include <thread> 26#include <vector> 27#include <stdexcept> 28 29#if defined(_WIN32 ) 30// `PrefetchVirtualMemory` (memoryapi.h, Windows 8+) is the whole point of the change in `gather` below. 31#define WIN32_LEAN_AND_MEAN 32#define NOMINMAX 33#include <windows.h> 34#endif 35 36namespace strata::kernels { 37 38namespace { 39/// The A/B arm. Host-token-path only, so it needs no atomics; see the note on `ple_prefetch_enable`. 40bool g_ple_prefetch = true; 41}// namespace 42 43void ple_prefetch_enable (bool on ) {g_ple_prefetch = on ; } 44bool ple_prefetch_enabled () {return g_ple_prefetch ; } 45 46PleConsts ple_artifact_consts () { 47// docs/gguf-dump-shard1.txt, verbatim. Written once here rather than derived, because `head_offsets` is 48// ALSO in the metadata as its own array - and deriving one from the other would hide a mismatch between 49// them instead of surfacing it. The parity test checks the two agree. 50PleConsts c {}; 51c .mult [0 ]= 23703573157769ull ; 52c .mult [1 ]= 20109073645365ull ; 53c .mult [2 ]= 8052911324071ull ; 54const uint64_t vocab [PLE_N_HEADS ]= { 5520000003 ,20000023 ,20000033 ,20000047 ,20000059 ,20000063 ,20000069 ,20000077 , 5620000081 ,20000093 ,20000107 ,20000147 ,20000153 ,20000159 ,20000161 ,20000171 }; 57const uint64_t offset [PLE_N_HEADS ]= { 580 ,20000003 ,40000026 ,60000059 ,80000106 ,100000165 ,120000228 ,140000297 , 59160000374 ,180000455 ,200000548 ,220000655 ,240000802 ,260000955 ,280001114 ,300001275 }; 60for (int i = 0 ;i < PLE_N_HEADS ;++ i ) { 61c .vocab [i ]= vocab [i ]; 62c .offset [i ]= offset [i ]; 63 } 64return c ; 65} 66 67bool ple_consts_from_arrays (const std::vector < uint64_t >& mult ,const std::vector < uint64_t >& vocab , 68const std::vector < uint64_t >& offset ,uint64_t table_rows ,PleConsts & out , std::string & err ) { 69if (mult .size ()!= (size_t )NGRAM_SIZE || vocab .size ()!= (size_t )PLE_N_HEADS || offset .size ()!= (size_t )PLE_N_HEADS ) { 70err = "the PLE metadata holds " + std::to_string (mult .size ())+ " multipliers, " + std::to_string (vocab .size ())+ 71" head sizes and " + std::to_string (offset .size ())+ " head offsets; the engine needs " + 72 std::to_string (NGRAM_SIZE )+ ", " + std::to_string (PLE_N_HEADS )+ " and " + std::to_string (PLE_N_HEADS ); 73return false; 74 } 75PleConsts c {}; 76for (int i = 0 ;i < NGRAM_SIZE ;++ i )c .mult [i ]= mult [i ]; 77for (int h = 0 ;h < PLE_N_HEADS ;++ h ) { 78if (vocab [h ]== 0 ) {err = "PLE head " + std::to_string (h )+ " has a hash modulus of 0" ;return false; } 79if (table_rows != 0 && (offset [h ]> table_rows || vocab [h ]> table_rows - offset [h ])) { 80err = "PLE head " + std::to_string (h )+ " (offset " + std::to_string (offset [h ])+ ", " + std::to_string (vocab [h ])+ 81" rows) reaches past the table's " + std::to_string (table_rows )+ " rows" ; 82return false; 83 } 84c .vocab [h ]= vocab [h ]; 85c .offset [h ]= offset [h ]; 86 } 87out = c ; 88return true; 89} 90 91uint64_t ngram_mixed (const int64_t * ctx ,const uint64_t * mult ,int n ) { 92// The first term is an ASSIGNMENT and the rest are XORed into it, which is how the source writes it 93// (`uint64_t mixed = ctx[0]*m[0]; for j=1.. mixed ^= ctx[j]*m[j];`). Every product wraps mod 2^64, 94// which is what the `(uint64_t)` casts in the source make explicit. 95uint64_t mixed = (uint64_t )ctx [0 ]* mult [0 ]; 96for (int j = 1 ;j < n ;++ j )mixed ^= (uint64_t )ctx [j ]* mult [j ]; 97return mixed ; 98} 99 100void ngram_rows (const int32_t * tokens ,const int32_t * prev ,int n_tokens ,const PleConsts & c ,uint32_t * out ) { 101const int n_prev = NGRAM_SIZE - 1 ; 102for (int i = 0 ;i < n_tokens ;++ i ) { 103int64_t ctx [NGRAM_SIZE ]; 104ctx [0 ]= tokens [i ]; 105bool cut = false; 106for (int s = 1 ;s < NGRAM_SIZE ;++ s ) { 107// `prev` is OLDEST FIRST, so predecessor `s` positions back is entry (n_prev - s): s=1 reads the 108// NEWEST. Reading index (s-1) instead walks the window backwards, which still produces indices 109// in range and so cannot be caught by a range check - only by an oracle. 110const int32_t t = cut ?TOKEN_NULL :prev [i * n_prev + (n_prev - s )]; 111// The cut is evaluated BEFORE the value is stored, so the position whose predecessor was EOS is 112// itself EOS. Storing first and then cutting would leave position s holding the real token while 113// position s+1 became EOS - one token of history too much. 114cut = cut || t < 0 || t == PLE_EOS_TOKEN_ID ; 115ctx [s ]= cut ?PLE_EOS_TOKEN_ID :t ; 116 } 117for (int n = 2 ;n <=NGRAM_SIZE ;++ n ) { 118const uint64_t mixed = ngram_mixed (ctx ,c .mult ,n ); 119const int base = (n - 2 )* HEADS_PER_NGRAM ; 120for (int g = 0 ;g < HEADS_PER_NGRAM ;++ g ) { 121const int h = base + g ; 122out [i * PLE_N_HEADS + h ]= (uint32_t ) (mixed %c .vocab [h ]+ c .offset [h ]); 123 } 124 } 125 } 126} 127 128namespace { 129const int8_t kIq4Nl [16 ]= {-127 ,-104 ,-83 ,-65 ,-49 ,-35 ,-22 ,-10 ,1 ,13 ,25 ,38 ,53 ,69 ,89 ,113 }; 130} 131 132int iq4nl_code (int code ) {return kIq4Nl [code & 15 ]; } 133 134void iq4nl_dequant_row (const uint8_t * row ,float * out160 ) { 135for (int b = 0 ;b < PLE_HEAD_DIM /32 ;++ b ) { 136const uint8_t * blk = row + (size_t )b * 18 ; 137uint16_t dbits ; 138 std::memcpy (& dbits ,blk ,2 ); 139const float d = f32_from_f16 (dbits ); 140const uint8_t * qs = blk + 2 ; 141// SPLIT HALVES: qs[j] holds elements j and j+16, not 2j and 2j+1. 142for (int j = 0 ;j < 16 ;++ j ) { 143out160 [b * 32 + j ]= d * (float )kIq4Nl [qs [j ]& 0x0F ]; 144out160 [b * 32 + j + 16 ]= d * (float )kIq4Nl [qs [j ] >>4 ]; 145 } 146 } 147} 148 149namespace { 150struct Fp8Table { 151float v [256 ]; 152Fp8Table () { 153for (int x = 0 ;x < 256 ;++ x ) { 154const int s = x >>7 ,e = (x >>3 )& 15 ,m = x & 7 ; 155float f ; 156if (e == 15 && m == 7 )f = 0.0f ;// NaN in e4m3fn; never in a real table, read as 0 157else if (e == 0 )f = std::ldexp ((float )m /8.0f ,-6 ); 158else f = std::ldexp (1.0f + (float )m /8.0f ,e - 7 ); 159v [x ]= s ?- f :f ; 160 } 161 } 162}; 163const Fp8Table kFp8 ; 164}// namespace 165 166void fp8_e4m3_dequant_row (const uint8_t * row ,float scale ,float * out160 ) { 167for (int j = 0 ;j < PLE_HEAD_DIM ;++ j )out160 [j ]= kFp8 .v [row [j ]]* scale ; 168} 169 170void bf16_dequant_row (const uint8_t * row ,float * out160 ) { 171// bfloat16 IS the top 16 bits of a float32, so widening is exact for every value, normal or not - no rounding, 172// no clamp, no scale. Bytes are assembled little-endian explicitly rather than reinterpreted, so this is the 173// same on a big-endian host. 174for (int j = 0 ;j < PLE_HEAD_DIM ;++ j ) { 175const uint32_t bits = (uint32_t )row [2 * j ] | ((uint32_t )row [2 * j + 1 ] <<8 ); 176const uint32_t wide = bits <<16 ; 177float v ; 178 std::memcpy (& v ,& wide ,sizeof v ); 179out160 [j ]= v ; 180 } 181} 182 183// NVIDIA's FP4-Local table: a row of 160 values is 80 bytes of E2M1 codes (element 2i in the low nibble, 2i+1 in the 184// high one) followed by 10 E4M3 block scales (one per 16 values, sign bit always 0); one F32 scales the whole table. 185// value = e2m1(code) * e4m3(block scale) * table scale, exactly what vLLM's nvfp4 PLE lookup computes. 186void nvfp4_row_dequant (const uint8_t * row ,float scale ,float * out160 ) { 187static const float kE2M1 [8 ]= {0.0f ,0.5f ,1.0f ,1.5f ,2.0f ,3.0f ,4.0f ,6.0f }; 188for (int j = 0 ;j < PLE_HEAD_DIM ;++ j ) { 189const uint8_t byte = row [j >>1 ]; 190const uint8_t code = (j & 1 ) ? (uint8_t ) (byte >>4 ) : (uint8_t ) (byte & 15 ); 191const float v = kE2M1 [code & 7 ]; 192const float s = kFp8 .v [row [PLE_HEAD_DIM /2 + (j >>4 )]]; 193out160 [j ]= ((code & 8 ) ?- v :v )* s * scale ; 194 } 195} 196 197// --------------------------------------------------------------------------------------------------- 198// THE FORMAT TABLE (see PleFormatInfo). One entry per table type; the block formats decode 5 blocks of 32. 199namespace { 200template < void (* Block )(const uint8_t * ,float * ),int BlockBytes > 201void dequant_blocks (const uint8_t * row ,float /*scale*/ ,float * out160 ) { 202for (int b = 0 ;b < PLE_HEAD_DIM /32 ;++ b )Block (row + (size_t )b * BlockBytes ,out160 + b * 32 ); 203} 204void dequant_iq4_nl (const uint8_t * row ,float ,float * out160 ) {iq4nl_dequant_row (row ,out160 ); } 205void dequant_fp8 (const uint8_t * row ,float scale ,float * out160 ) {fp8_e4m3_dequant_row (row ,scale ,out160 ); } 206void dequant_bf16 (const uint8_t * row ,float ,float * out160 ) {bf16_dequant_row (row ,out160 ); } 207void dequant_nvfp4 (const uint8_t * row ,float scale ,float * out160 ) {nvfp4_row_dequant (row ,scale ,out160 ); } 208 209const PleFormatInfo kPleFormats []= { 210 {PleFormat ::IQ4_NL ,"IQ4_NL" ,"IQ4_NL" ,PLE_ROW_BYTES , false,dequant_iq4_nl }, 211 {PleFormat ::Q5_0 ,"Q5_0" ,"Q5_0" , (PLE_HEAD_DIM /32 )* 22 , false,dequant_blocks < strata::dequantize_q5_0 ,22 > }, 212 {PleFormat ::F8_E4M3 ,"F8_E4M3" ,"I8" ,PLE_ROW_BYTES_FP8 , true,dequant_fp8 }, 213// Ordinary GGUFs ship the table in other types: Unsloth's UD-Q6_K_XL and Swift-1.5 Q4_K_L as Q8_0, a Q5_K_M finetune as Q5_1 214 {PleFormat ::Q5_1 ,"Q5_1" ,"Q5_1" ,PLE_ROW_BYTES_Q5_1 , false,dequant_blocks < strata::dequantize_q5_1 ,24 > }, 215 {PleFormat ::Q8_0 ,"Q8_0" ,"Q8_0" ,PLE_ROW_BYTES_Q8_0 , false,dequant_blocks < strata::dequantize_q8_0 ,34 > }, 216// Q4_0 (plain llama-quantize Q4_0 files, #599): 90-byte rows like IQ4_NL (18-byte blocks), a linear 4-bit grid 217 {PleFormat ::Q4_0 ,"Q4_0" ,"Q4_0" ,PLE_ROW_BYTES , false,dequant_blocks < strata::dequantize_q4_0 ,18 > }, 218// BF16 (#586): the checkpoint's own table at full precision, 320-byte rows; self-describing, so no scale and no 219// metadata to trust (tools/ple_fp8_pack.py writes the FP8 form of the same table) 220 {PleFormat ::BF16 ,"BF16" ,"BF16" ,PLE_ROW_BYTES_BF16 , false,dequant_bf16 }, 221// NVFP4 x16 (NVIDIA's Qwen3.8-Flash-Next-FP4-Local, tools/nvfp4_local_pack.py ple): 90-byte rows, I8 bytes marked 222// strata.ple.format = nvfp4x16 with strata.ple.scale. The tensor is [90, rows]: ne0 is the row's byte count. 223 {PleFormat ::NVFP4 ,"NVFP4" ,"I8" ,PLE_ROW_BYTES_NVFP4 , true,dequant_nvfp4 }, 224}; 225constexpr int kPleFormatCount = (int ) (sizeof kPleFormats /sizeof kPleFormats [0 ]); 226}// namespace 227 228const PleFormatInfo * ple_formats () {return kPleFormats ; } 229int ple_format_count () {return kPleFormatCount ; } 230const PleFormatInfo & ple_format_info (PleFormat f ) {return kPleFormats [(int )f ]; } 231const PleFormatInfo * ple_format_for_type (const char * gguf_type_name ) { 232for (const PleFormatInfo & f :kPleFormats ) 233if (std::strcmp (f .gguf_type ,gguf_type_name )== 0 )return & f ; 234return nullptr ; 235} 236std::string ple_format_list () { 237 std::string out ; 238for (int i = 0 ;i < kPleFormatCount ;++ i ) { 239const PleFormatInfo & f = kPleFormats [i ]; 240if (i > 0 )out += i + 1 == kPleFormatCount ?" or " :", " ; 241out += std::strcmp (f .gguf_type ,"I8" )== 0 ? (f .id == PleFormat ::NVFP4 ?"NVFP4 (I8)" :"FP8 (I8)" ) :f .name ; 242 } 243return out ; 244} 245 246static_assert(PLE_ROW_BYTES_MAX >=PLE_ROW_BYTES && PLE_ROW_BYTES_MAX >=PLE_ROW_BYTES_FP8 ,"row buffers too small" ); 247 248struct PleTable ::Impl { 249GgufFile * file = nullptr ; 250const uint8_t * data = nullptr ; 251uint64_t n_rows = 0 ; 252const PleFormatInfo * fmt = & ple_format_info (PleFormat ::IQ4_NL );// the table's format (#296: Q5_0 is one of them) 253mutable uint64_t bytes_read = 0 ; 254// Direct mode (plan v0.3 P2): the mapping above is released after the header parse and every row comes 255// from an unbuffered SSD read into `raw`. 256PleIo mode = PleIo ::Mmap ; 257 strata::ngram::PleReader reader ; 258 strata::ngram::PleReader ::Ticket ticket ; 259bool pending = false; 260bool locked = false; 261// the table is shared by the prompt path and the decode windows; they can use it at once (one on a worker thread) 262 std::recursive_mutex mu ; 263uint32_t rows [PLE_N_HEADS ]= {}; 264uint8_t raw [PLE_N_HEADS * PLE_ROW_BYTES_MAX ]= {}; 265static constexpr size_t kMaxPrefetch = 16 ; 266size_t n_prefetch = 0 ; 267 strata::ngram::PleReader ::Ticket prefetch_tickets [kMaxPrefetch ]= {}; 268uint32_t prefetch_keys [kMaxPrefetch ][PLE_N_HEADS ]= {}; 269uint8_t prefetch_raw [kMaxPrefetch ][PLE_N_HEADS * PLE_ROW_BYTES_MAX ]= {}; 270float scale = 1.0f ;// the FP8 table's one scale 271uint32_t rb = PLE_ROW_BYTES ;// bytes per row 272void decode (const uint8_t * row ,float * out160 )const {fmt -> dequant (row ,scale ,out160 ); } 273// STRATA_PLE_CHECK=1 (a diagnostic for #3602, off by default): the file and the table's offset, to re-read a row whose decoded 274// values are not plausible and compare the bytes the direct reader delivered with the file's own 275 std::string path ; 276uint64_t table_offset = 0 ; 277mutable int check_reports = 0 ; 278static bool check_on () { 279static const bool on = [] {const char * v = std::getenv ("STRATA_PLE_CHECK" );return v != nullptr && std::atoi (v )!= 0 ; }(); 280return on ; 281 } 282/// One decoded row (`out160`, from `raw`): when a value is not finite or beyond 1e5 (a real PLE value is orders smaller; the 283/// largest an IQ4_NL row can decode to is 8.3e6), say which row, where, and whether the delivered bytes are the file's. 284void check_row (const char * where ,uint32_t row ,const uint8_t * raw ,const float * out160 )const { 285if (check_reports >=8 || row >=n_rows )return ; 286int bad = -1 ; 287for (int j = 0 ;j < PLE_HEAD_DIM ;++ j ) 288if (!std::isfinite (out160 [j ])|| std::fabs (out160 [j ])> 1e5f ) {bad = j ;break ; } 289if (bad < 0 )return ; 290++ check_reports ; 291const uint64_t at = table_offset + (uint64_t )row * rb ; 292 std::vector < uint8_t > file (rb ,0 ); 293bool read = false; 294 { 295 std::ifstream f (path , std::ios::binary ); 296if (f ) { 297f .seekg ((std::streamoff )at ); 298f .read ((char * )file .data (), (std::streamsize )rb ); 299read = (uint32_t )f .gcount ()== rb ; 300 } 301 } 302 std::fprintf (stderr ,"strata ple check: %s: row %u (file offset %llu, page offset %llu): value %d of 160 decodes to %g" ,where , 303row , (unsigned long long )at , (unsigned long long ) (at %4096 ),bad , (double )out160 [bad ]); 304if (!read ) { 305 std::fprintf (stderr ,"; the file could not be re-read\n" ); 306return ; 307 } 308uint32_t first = rb ; 309for (uint32_t b = 0 ;b < rb ;++ b ) 310if (raw [b ]!= file [b ]) {first = b ;break ; } 311if (first == rb ) { 312 std::fprintf (stderr ,"; the delivered bytes ARE the file's bytes (the table itself holds this value)\n" ); 313 }else { 314 std::fprintf (stderr ,"; THE DELIVERED BYTES DIFFER FROM THE FILE from byte %u (delivered 0x%02x, file 0x%02x); first 8 delivered:" ,first , 315raw [first ],file [first ]); 316for (int b = 0 ;b < 8 && (uint32_t )b < rb ;++ b ) std::fprintf (stderr ," %02x" ,raw [b ]); 317 std::fprintf (stderr ,"; first 8 of the file:" ); 318for (int b = 0 ;b < 8 && (uint32_t )b < rb ;++ b ) std::fprintf (stderr ," %02x" ,file [b ]); 319 std::fprintf (stderr ,"\n" ); 320 } 321 } 322}; 323 324PleTable ::PleTable () :impl_ (new Impl ) {} 325PleTable ::~PleTable () {close ();delete impl_ ; } 326 327bool PleTable ::open (const std::string & gguf_path , std::string & err ) { 328return open (gguf_path ,err ,PleIoOptions {}); 329} 330 331bool PleTable ::open (const std::string & gguf_path , std::string & err ,const PleIoOptions & io ) { 332close (); 333try { 334impl_ -> file = new GgufFile (gguf_path ); 335 }catch (const std::exception & e ) { 336err = e .what (); 337return false; 338 } 339const TensorInfo * t = impl_ -> file -> find ("per_layer_token_embd.weight" ); 340if (t == nullptr ) { 341err = "per_layer_token_embd.weight is not in " + gguf_path ; 342close (); 343return false; 344 } 345// [160, 320001536]: ne0 = 160 is the FAST axis, so the ROW index is shape[1] and a row is contiguous. The NVFP4 table 346// is I8 bytes with ne0 = 90 (the row's byte count), marked strata.ple.format = nvfp4x16. 347const MetaValue * fmt_key = impl_ -> file -> get ("strata.ple.format" ); 348const bool nvfp4x16 = std::strcmp (t -> type_name (),"I8" )== 0 && fmt_key != nullptr && fmt_key -> s == "nvfp4x16" ; 349const uint64_t want_ne0 = nvfp4x16 ? (uint64_t )PLE_ROW_BYTES_NVFP4 : (uint64_t )PLE_HEAD_DIM ; 350if (t -> shape .size ()!= 2 || t -> shape [0 ]!= want_ne0 ) { 351err = "per_layer_token_embd.weight has an unexpected shape" ; 352close (); 353return false; 354 } 355// The table's type is looked up in the format list (ple_formats()): IQ4_NL (ISTA-DASLab's shard 2, the original's 356// own GGUF), Q5_0 (#296: OrcaRouter's GGUF), or the FP8 table as shipped: I8 bytes marked strata.ple.format = 357// f8_e4m3 with strata.ple.scale (tools/ple_fp8_pack.py) 358const PleFormatInfo * fmt = nvfp4x16 ?& ple_format_info (PleFormat ::NVFP4 ) :ple_format_for_type (t -> type_name ()); 359if (fmt == nullptr ) { 360err = std::string ("per_layer_token_embd.weight is " )+ t -> type_name ()+ ", not " + ple_format_list (); 361close (); 362return false; 363 } 364if (fmt -> needs_scale ) { 365const MetaValue * f = impl_ -> file -> get ("strata.ple.format" ); 366const MetaValue * s = impl_ -> file -> get ("strata.ple.scale" ); 367const char * want = nvfp4x16 ?"nvfp4x16" :"f8_e4m3" ; 368if (f == nullptr || f -> s != want || s == nullptr || !(s -> num ()> 0.0 )) { 369err = std::string ("per_layer_token_embd.weight is I8 without strata.ple.format = " )+ want + " and a positive strata.ple.scale" ; 370close (); 371return false; 372 } 373impl_ -> scale = (float )s -> num (); 374 } 375impl_ -> fmt = fmt ; 376impl_ -> rb = fmt -> row_bytes ; 377// PleReader's row_bytes has been a runtime parameter since the FP8 table (160 B rows) needed it; Q5_0's 378// 110 B rows go through the exact same generic path (ple_reader_test --selftest covers both 90 and 110 B 379// rows: straddling, caching, in-flight tickets, keep-alive). This refusal was stale. 380impl_ -> n_rows = t -> shape [1 ]; 381 382// THE CHECK THAT MAKES THE OFFSET FALSIFIABLE. The manifest's `shard2_tensor.offset` is 0, but that is 383// the offset within the GGUF's DATA SECTION: the file's first 192 bytes are a header, and reading at 0 384// would decode the header plus 192 bytes of shifted rows - still plausible IQ4_NL, and wrong for every 385// row. `GgufFile` parses the header, so `tensor_data` is already correct; this asserts the tensor 386// exactly fills the file from there, which is what makes the whole arrangement checkable rather than 387// assumed. A wrong data offset would leave a different remainder. 388// A shard may hold other tensors too (Swift 1.5's shard 1 holds layers 0-12 and the table): the table must 389// then fit inside the file at its own offset; alone in its shard (the original's shard 2) it fills it exactly. 390// The size arithmetic is checked before it is used (#865): a header that claims enough rows to wrap the 64-bit 391// product, or a data section that starts past the end of the file, must be refused, not compared after wrapping. 392if (impl_ -> n_rows > std::numeric_limits < uint64_t > ::max () /impl_ -> rb || 393impl_ -> file -> data_start ()> impl_ -> file -> file_size ()) { 394err = "PLE table size overflow or invalid data offset in " + gguf_path ; 395close (); 396return false; 397 } 398const uint64_t need = impl_ -> n_rows * (uint64_t )impl_ -> rb ; 399const uint64_t have = impl_ -> file -> file_size ()- impl_ -> file -> data_start (); 400const bool alone = impl_ -> file -> tensors ().size ()== 1 ; 401if (t -> offset > have || need > have - t -> offset || (alone && (t -> offset != 0 || need != have ))) { 402char buf [256 ]; 403 std::snprintf (buf ,sizeof buf , 404"PLE table size mismatch: %llu rows x %d B = %llu at offset %llu, but the file holds %llu from " 405"data_start %llu" , 406 (unsigned long long )impl_ -> n_rows , (int )impl_ -> rb , (unsigned long long )need , 407 (unsigned long long )t -> offset , (unsigned long long )have , 408 (unsigned long long )impl_ -> file -> data_start ()); 409err = buf ; 410if (alone && have > need )// #657: extra bytes after the table: a damaged or wrong file, not a format question 411err += "; the file is longer than its table - delete it and its .done mark and run setup again" ; 412close (); 413return false; 414 } 415impl_ -> data = impl_ -> file -> tensor_data (* t );// only a table that fits the file is mapped 416if (io .mode == PleIo ::Direct ) { 417// The parse above is the validated source of the offset; the mapping itself is not kept, so no page of 418// the table can enter this process's working set or the file cache through it. 419const uint64_t table_offset = impl_ -> file -> data_start ()+ t -> offset ; 420const uint64_t n_rows = impl_ -> n_rows ; 421impl_ -> path = gguf_path ; 422impl_ -> table_offset = table_offset ; 423delete impl_ -> file ; 424impl_ -> file = nullptr ; 425impl_ -> data = nullptr ; 426if (!impl_ -> reader .open (gguf_path ,table_offset ,n_rows ,io .max_inflight ,io .cache_rows ,err ,io .io_thread , 427impl_ -> rb )) { 428close (); 429return false; 430 } 431impl_ -> reader .set_keepalive (io .keepalive_ms ,io .keepalive_window_s ); 432impl_ -> n_rows = n_rows ; 433 } 434if (io .mode == PleIo ::Mmap && io .lock && impl_ -> data != nullptr ) { 435#if defined(_WIN32 ) 436// Windows has no mlock: the platform helper raises the process's minimum working set and 437// VirtualLocks the mapped table instead (ordinary accounts hold the privilege). A failure 438// falls back to touching the pages, i.e. plain mmap behaviour, with a warning - same as POSIX. 439// A table that is more than half of the RAM leaves the rest of the process little (the locked pages cannot be 440// paged out): say so, and go on (recommend, never force). 441MEMORYSTATUSEX ms ; 442ms .dwLength = sizeof (ms ); 443if (GlobalMemoryStatusEx (& ms )&& need > ms .ullTotalPhys /2 ) 444 std::fprintf (stderr ,"strata: warning: --ple-io ram locks %.1f GiB, more than half of this PC's %.1f GiB of RAM\n" , 445 (double )need / (1ull <<30 ), (double )ms .ullTotalPhys / (1ull <<30 )); 446const strata::platform::LockResult lr = 447 strata::platform::lock_resident ((void * )impl_ -> data ,need ); 448if (lr .ok && lr .locked_bytes >=need ) { 449impl_ -> locked = true; 450 }else { 451// a partial lock is not a lock: the unlocked rest would fault on the token path, so give it back 452if (lr .locked_bytes > 0 ) strata::platform::unlock_resident ((void * )impl_ -> data ,lr .locked_bytes ); 453 std::fprintf (stderr ,"strata: PLE table lock failed (%s): touching its pages instead\n" , 454lr .note .c_str ()); 455volatile uint8_t sink = 0 ; 456for (uint64_t off = 0 ;off < need ;off += 4096 )sink = sink + impl_ -> data [off ]; 457 (void )sink ; 458 } 459#else 460const uint64_t page = 4096 ; 461const uintptr_t a0 = (uintptr_t )impl_ -> data & ~(uintptr_t ) (page - 1 ); 462const uintptr_t a1 = (uintptr_t )impl_ -> data + (uintptr_t )need ; 463madvise ((void * )a0 ,a1 - a0 ,MADV_WILLNEED ); 464// Fault the table in with several threads first: mlock (and a single toucher) brings it in one page at a time 465// from one thread, ~0.5 GB/s from a cold file - 106 s for a 54 GB Q8_0 table. The pages are then resident 466// and mlock only pins them. 467 { 468constexpr uintptr_t kPiece = 64ull <<20 ; 469const uintptr_t pieces = (a1 - a0 + kPiece - 1 ) /kPiece ; 470const unsigned threads = std::max (1u , std::min (16u , std::thread::hardware_concurrency ())); 471 std::atomic < uintptr_t > next {0 }; 472auto touch = [& ] { 473volatile uint8_t sink = 0 ; 474for (uintptr_t i ; (i = next .fetch_add (1 ))< pieces ;) 475for (uintptr_t p = a0 + i * kPiece ,e = std::min (a1 ,p + kPiece );p < e ;p += page ) 476sink = sink + * (const volatile uint8_t * )p ; 477 (void )sink ; 478 }; 479 std::vector < std::thread > pool ; 480for (unsigned t = 0 ;t < threads ;++ t )pool .emplace_back (touch ); 481for (auto & t :pool )t .join (); 482 } 483// #4671: a systemd service without LimitMEMLOCK may lock 8 MiB (soft and hard), a login shell far more. Raise the soft limit 484// to what the hard limit allows first (no privilege needed); if the table still does not fit, say what to set. 485struct rlimit rl {}; 486if (getrlimit (RLIMIT_MEMLOCK ,& rl )== 0 && rl .rlim_cur != RLIM_INFINITY && (uint64_t )rl .rlim_cur < a1 - a0 && 487rl .rlim_max > rl .rlim_cur ) { 488const rlim_t room = (rlim_t ) (a1 - a0 )+ ((rlim_t )1 <<30 ); 489const rlim_t want = rl .rlim_max == RLIM_INFINITY ?room : std::min < rlim_t > (rl .rlim_max ,room ); 490struct rlimit up = rl ; 491up .rlim_cur = want ; 492if (setrlimit (RLIMIT_MEMLOCK ,& up )== 0 ) 493 std::fprintf (stderr ,"strata: the memory this program may lock was %llu MiB; raised to %llu MiB for the PLE table\n" , 494 (unsigned long long ) (rl .rlim_cur >>20 ), (unsigned long long ) (want >>20 )); 495 } 496if (mlock ((const void * )a0 ,a1 - a0 )== 0 ) { 497impl_ -> locked = true; 498 }else { 499const int why = errno ; 500struct rlimit now {}; 501if (getrlimit (RLIMIT_MEMLOCK ,& now )== 0 && now .rlim_cur != RLIM_INFINITY && (uint64_t )now .rlim_cur < a1 - a0 ) 502 std::fprintf (stderr ,"strata: the PLE table (%.1f GiB) was not locked in RAM: this program may lock only %.1f GiB " 503"(RLIMIT_MEMLOCK). It still works, with the table's pages faulted in but reclaimable; the lock was measured " 504"up to 6%% faster in decode (#4671). In a systemd service set LimitMEMLOCK=infinity, elsewhere run `ulimit -l unlimited`\n" , 505 (double ) (a1 - a0 ) / (1ull <<30 ), (double )now .rlim_cur / (1ull <<30 )); 506else 507 std::fprintf (stderr ,"strata: PLE table mlock failed (%s; raise `ulimit -l`): its pages stay faulted in " 508"but may be reclaimed\n" , std::strerror (why )); 509 } 510#endif 511 } 512impl_ -> mode = io .mode ; 513return true; 514} 515 516void PleTable ::wait_prefetches () { 517 std::lock_guard < std::recursive_mutex > lk (impl_ -> mu ); 518if (impl_ -> n_prefetch == 0 )return ; 519 std::string dummy ; 520for (size_t i = 0 ;i < impl_ -> n_prefetch ;++ i ) (void )impl_ -> reader .collect (impl_ -> prefetch_tickets [i ],dummy ); 521impl_ -> n_prefetch = 0 ; 522} 523 524void PleTable ::prefetch_rows (const uint32_t * rows16 ) { 525 std::lock_guard < std::recursive_mutex > lk (impl_ -> mu ); 526if (impl_ -> mode == PleIo ::Direct && impl_ -> reader .is_open ()) { 527for (size_t i = 0 ;i < impl_ -> n_prefetch ;++ i ) 528if (std::memcmp (impl_ -> prefetch_keys [i ],rows16 ,sizeof (uint32_t )* PLE_N_HEADS )== 0 )return ; 529if (impl_ -> n_prefetch >=Impl ::kMaxPrefetch )wait_prefetches (); 530const size_t slot = impl_ -> n_prefetch ++ ; 531 std::memcpy (impl_ -> prefetch_keys [slot ],rows16 ,sizeof (uint32_t )* PLE_N_HEADS ); 532impl_ -> prefetch_tickets [slot ]= impl_ -> reader .issue (impl_ -> prefetch_keys [slot ],PLE_N_HEADS ,impl_ -> prefetch_raw [slot ]); 533return ; 534 } 535#if defined(_WIN32 ) 536if (impl_ -> data != nullptr && g_ple_prefetch ) { 537WIN32_MEMORY_RANGE_ENTRY ranges [PLE_N_HEADS ]; 538ULONG_PTR n = 0 ; 539for (int h = 0 ;h < PLE_N_HEADS ;++ h ) { 540if (rows16 [h ] >=impl_ -> n_rows )continue ; 541ranges [n ].VirtualAddress = (PVOID ) (impl_ -> data + (size_t )rows16 [h ]* impl_ -> rb ); 542ranges [n ].NumberOfBytes = impl_ -> rb ; 543++ n ; 544 } 545if (n > 0 ) (void )PrefetchVirtualMemory (GetCurrentProcess (),n ,ranges ,0 ); 546 } 547#endif 548} 549 550void PleTable ::close () { 551wait_prefetches (); 552impl_ -> reader .close (); 553impl_ -> pending = false; 554impl_ -> locked = false;// the unmap below releases the lock 555impl_ -> mode = PleIo ::Mmap ; 556delete impl_ -> file ; 557impl_ -> file = nullptr ; 558impl_ -> data = nullptr ; 559impl_ -> n_rows = 0 ; 560impl_ -> rb = PLE_ROW_BYTES ; 561impl_ -> fmt = & ple_format_info (PleFormat ::IQ4_NL ); 562impl_ -> scale = 1.0f ; 563impl_ -> bytes_read = 0 ; 564} 565 566bool PleTable ::is_open ()const {return impl_ -> data != nullptr || impl_ -> reader .is_open (); } 567bool PleTable ::locked ()const {return impl_ -> locked ; } 568bool PleTable ::unlock () { 569 std::lock_guard < std::recursive_mutex > lk (impl_ -> mu ); 570if (!impl_ -> locked || impl_ -> data == nullptr )return false; 571 strata::platform::unlock_resident ((void * )impl_ -> data ,impl_ -> n_rows * (uint64_t )impl_ -> rb ); 572impl_ -> locked = false; 573return true; 574} 575const char * PleTable ::format ()const {return impl_ -> fmt -> name ; } 576PleIo PleTable ::mode ()const {return impl_ -> mode ; } 577uint64_t PleTable ::rows ()const {return impl_ -> n_rows ; } 578uint64_t PleTable ::table_bytes ()const {return impl_ -> n_rows * (uint64_t )impl_ -> rb ; } 579uint64_t PleTable ::bytes_read ()const {return impl_ -> bytes_read ; } 580 581void PleTable ::read_row (uint32_t row ,float * out160 )const { 582 std::lock_guard < std::recursive_mutex > lk (impl_ -> mu ); 583if (impl_ -> mode == PleIo ::Direct && impl_ -> reader .is_open ()) { 584uint8_t raw [PLE_ROW_BYTES_MAX ]; 585 std::string err ; 586const auto t = impl_ -> reader .issue (& row ,1 ,raw ); 587if (!impl_ -> reader .collect (t ,err )) { 588 std::memset (out160 ,0 , (size_t )PLE_HEAD_DIM * sizeof (float )); 589return ; 590 } 591impl_ -> decode (raw ,out160 ); 592if (Impl ::check_on ())impl_ -> check_row ("read_row" ,row ,raw ,out160 ); 593impl_ -> bytes_read += impl_ -> rb ; 594return ; 595 } 596if (impl_ -> data == nullptr || row >=impl_ -> n_rows ) { 597 std::memset (out160 ,0 , (size_t )PLE_HEAD_DIM * sizeof (float )); 598return ; 599 } 600impl_ -> decode (impl_ -> data + (size_t )row * impl_ -> rb ,out160 ); 601impl_ -> bytes_read += impl_ -> rb ; 602} 603 604bool PleTable ::issue (const uint32_t * rows16 ) { 605 std::lock_guard < std::recursive_mutex > lk (impl_ -> mu ); 606wait_prefetches (); 607 std::memcpy (impl_ -> rows ,rows16 ,sizeof impl_ -> rows ); 608if (impl_ -> mode == PleIo ::Direct ) { 609if (impl_ -> pending )return false;// one token in flight per table 610impl_ -> ticket = impl_ -> reader .issue (impl_ -> rows ,PLE_N_HEADS ,impl_ -> raw ); 611impl_ -> pending = true; 612return true; 613 } 614#if defined(_WIN32 ) 615if (impl_ -> data != nullptr && g_ple_prefetch ) { 616WIN32_MEMORY_RANGE_ENTRY ranges [PLE_N_HEADS ]; 617ULONG_PTR n = 0 ; 618for (int h = 0 ;h < PLE_N_HEADS ;++ h ) { 619if (rows16 [h ] >=impl_ -> n_rows )continue ; 620ranges [n ].VirtualAddress = (PVOID ) (impl_ -> data + (size_t )rows16 [h ]* impl_ -> rb ); 621ranges [n ].NumberOfBytes = impl_ -> rb ; 622++ n ; 623 } 624if (n > 0 ) (void )PrefetchVirtualMemory (GetCurrentProcess (),n ,ranges ,0 ); 625 } 626#endif 627impl_ -> pending = true; 628return true; 629} 630 631bool PleTable ::collect (float * out2560 , std::string & err ) { 632 std::lock_guard < std::recursive_mutex > lk (impl_ -> mu ); 633if (!impl_ -> pending ) {err = "PleTable::collect without issue" ;return false; } 634impl_ -> pending = false; 635if (impl_ -> mode == PleIo ::Direct ) { 636if (!impl_ -> reader .collect (impl_ -> ticket ,err ))return false; 637for (int h = 0 ;h < PLE_N_HEADS ;++ h ) 638impl_ -> decode (impl_ -> raw + (size_t )h * impl_ -> rb ,out2560 + (size_t )h * PLE_HEAD_DIM ); 639if (Impl ::check_on ()) 640for (int h = 0 ;h < PLE_N_HEADS ;++ h ) 641impl_ -> check_row ("collect" ,impl_ -> rows [h ],impl_ -> raw + (size_t )h * impl_ -> rb ,out2560 + (size_t )h * PLE_HEAD_DIM ); 642impl_ -> bytes_read += (uint64_t )PLE_N_HEADS * impl_ -> rb ; 643return true; 644 } 645for (int h = 0 ;h < PLE_N_HEADS ;++ h )read_row (impl_ -> rows [h ],out2560 + (size_t )h * PLE_HEAD_DIM ); 646return true; 647} 648 649bool PleTable ::gather_batch (const uint32_t * rows ,size_t n_tokens ,float * out , std::string & err ) { 650 std::lock_guard < std::recursive_mutex > lk (impl_ -> mu ); 651if (impl_ -> pending ) {err = "PleTable::gather_batch while a token is in flight" ;return false; } 652const size_t n = n_tokens * (size_t )PLE_N_HEADS ; 653if (impl_ -> mode == PleIo ::Direct ) { 654// Fast path: match each requested token to any in-flight/completed prefetch slot, then collect directly 655// without issuing a second PleReader ticket or copying through RowCache. 656if (n_tokens <=Impl ::kMaxPrefetch ) { 657size_t matched [Impl ::kMaxPrefetch ]; 658bool exact_match = true; 659for (size_t t = 0 ;t < n_tokens ;++ t ) { 660size_t i = 0 ; 661while (i < impl_ -> n_prefetch && 662 std::memcmp (impl_ -> prefetch_keys [i ],rows + t * PLE_N_HEADS , 663sizeof (uint32_t )* PLE_N_HEADS )!= 0 )++ i ; 664if (i == impl_ -> n_prefetch ) {exact_match = false;break ; } 665matched [t ]= i ;// duplicate requests may share one immutable prefetch slot 666 } 667if (exact_match ) { 668bool collect_ok = true; 669for (size_t i = 0 ;i < impl_ -> n_prefetch ;++ i ) { 670 std::string ignored ; 671if (!impl_ -> reader .collect (impl_ -> prefetch_tickets [i ],collect_ok ?err :ignored )) 672collect_ok = false;// retain the first error, but drain every output buffer 673 } 674impl_ -> n_prefetch = 0 ; 675if (!collect_ok )return false; 676for (size_t t = 0 ;t < n_tokens ;++ t ) { 677for (int h = 0 ;h < PLE_N_HEADS ;++ h ) { 678impl_ -> decode (impl_ -> prefetch_raw [matched [t ]]+ (size_t )h * impl_ -> rb , 679out + (t * PLE_N_HEADS + (size_t )h )* PLE_HEAD_DIM ); 680if (Impl ::check_on ()) 681impl_ -> check_row ("gather_batch (prefetched)" ,rows [t * PLE_N_HEADS + (size_t )h ], 682impl_ -> prefetch_raw [matched [t ]]+ (size_t )h * impl_ -> rb , 683out + (t * PLE_N_HEADS + (size_t )h )* PLE_HEAD_DIM ); 684 } 685 } 686impl_ -> bytes_read += (uint64_t )n * impl_ -> rb ; 687return true; 688 } 689 } 690wait_prefetches (); 691 std::vector < uint8_t > raw (n * impl_ -> rb ); 692const auto ticket = impl_ -> reader .issue (rows ,n ,raw .data ()); 693if (!impl_ -> reader .collect (ticket ,err ))return false; 694for (size_t i = 0 ;i < n ;++ i ) { 695impl_ -> decode (raw .data ()+ i * impl_ -> rb ,out + i * PLE_HEAD_DIM ); 696if (Impl ::check_on ())impl_ -> check_row ("gather_batch" ,rows [i ],raw .data ()+ i * impl_ -> rb ,out + i * PLE_HEAD_DIM ); 697 } 698impl_ -> bytes_read += (uint64_t )n * impl_ -> rb ; 699return true; 700 } 701wait_prefetches (); 702// #1984 #1971: a mapped table that is not in the file cache served this loop as serial demand faults, one random 703// 4 KiB page at a time (16 rows a token, 16 x the chunk's tokens for a prompt), and the first chunk of a prompt has 704// only layer 0 to hide it behind: a cold 27 GB table at ~0.2-1 ms a fault is minutes with no progress mark, which 705// is what the stall watchdog stops. Ask the OS for the next window's pages in one go (PrefetchVirtualMemory / 706// MADV_WILLNEED, a hint that cannot change a value: an unfetched page is faulted by the read) while this window is read. 707constexpr size_t kWin = 4096 ;// rows a window 708auto hint = [& ](size_t a ,size_t b ) { 709if (impl_ -> data == nullptr || !g_ple_prefetch )return ; 710#if defined(_WIN32 ) 711WIN32_MEMORY_RANGE_ENTRY ranges [kWin ]; 712ULONG_PTR k = 0 ; 713for (size_t i = a ;i < b ;++ i ) { 714if (rows [i ] >=impl_ -> n_rows )continue ; 715ranges [k ].VirtualAddress = (PVOID ) (impl_ -> data + (size_t )rows [i ]* impl_ -> rb ); 716ranges [k ].NumberOfBytes = impl_ -> rb ; 717++ k ; 718 } 719if (k > 0 ) (void )PrefetchVirtualMemory (GetCurrentProcess (),k ,ranges ,0 ); 720#else 721for (size_t i = a ;i < b ;++ i ) { 722if (rows [i ] >=impl_ -> n_rows )continue ; 723const uintptr_t r0 = (uintptr_t ) (impl_ -> data + (size_t )rows [i ]* impl_ -> rb ); 724const uintptr_t p0 = r0 & ~(uintptr_t )4095 ; 725 (void )madvise ((void * )p0 , (size_t ) (r0 + impl_ -> rb - p0 ),MADV_WILLNEED ); 726 } 727#endif 728 }; 729hint (0 , std::min (n ,kWin )); 730for (size_t w = 0 ;w < n ;w += kWin ) { 731if (w + kWin < n )hint (w + kWin , std::min (n ,w + 2 * kWin )); 732const size_t e = std::min (n ,w + kWin ); 733for (size_t i = w ;i < e ;++ i )read_row (rows [i ],out + i * PLE_HEAD_DIM ); 734 } 735return true; 736} 737 738bool PleTable ::gather_raw_iq4nl (const uint32_t * rows ,size_t n_tokens ,uint8_t * out )const { 739 std::lock_guard < std::recursive_mutex > lk (impl_ -> mu ); 740if (impl_ -> data == nullptr || impl_ -> fmt -> id != PleFormat ::IQ4_NL || impl_ -> rb != PLE_ROW_BYTES )return false; 741const size_t n = n_tokens * (size_t )PLE_N_HEADS ; 742for (size_t i = 0 ;i < n ;++ i ) { 743uint8_t * o = out + i * PLE_ROW_BYTES ; 744if (rows [i ] >=impl_ -> n_rows ) { 745// a row past the table reads as +0.0f (read_row): scale 0 and code 8 (value +1) in every nibble decode to +0.0f 746// on the device, where all-zero bytes would decode to -0.0f (scale 0 times code 0's value -127) 747for (int b = 0 ;b < PLE_HEAD_DIM /32 ;++ b ) { 748uint8_t * blk = o + (size_t )b * 18 ; 749 std::memset (blk ,0 ,2 ); 750 std::memset (blk + 2 ,0x88 ,16 ); 751 } 752 }else std::memcpy (o ,impl_ -> data + (size_t )rows [i ]* PLE_ROW_BYTES ,PLE_ROW_BYTES ); 753 } 754impl_ -> bytes_read += (uint64_t )n * PLE_ROW_BYTES ; 755return true; 756} 757 758void PleTable ::set_injected_delay_us (double us ) {impl_ -> reader .set_injected_delay_us (us ); } 759 760std::string PleTable ::io_report ()const { 761if (impl_ -> mode != PleIo ::Direct || !impl_ -> reader .is_open ())return {}; 762const strata::ngram::ReaderStats s = impl_ -> reader .snapshot (); 763char buf [400 ]; 764int n = std::snprintf (buf ,sizeof buf , 765"ple io: %llu rows, %.1f%% row-cache hits, %llu SSD reads (%.1f MB), read p50 %.0f us p99 %.0f us, " 766"blocked %.3f ms total (submit %.3f ms), cache %llu/%llu rows" , 767 (unsigned long long )s .requests ,s .requests ?100.0 * (double )s .cache_hits / (double )s .requests :0.0 , 768 (unsigned long long )s .reads , (double )s .bytes /1e6 ,s .percentile (0.5 ),s .percentile (0.99 ), 769s .wait_us /1000.0 ,s .submit_us /1000.0 , (unsigned long long )impl_ -> reader .cache_size (), 770 (unsigned long long )impl_ -> reader .cache_capacity ()); 771if (s .keepalive_reads > 0 && n > 0 && n < (int )sizeof buf ) 772 std::snprintf (buf + n ,sizeof buf - (size_t )n ,", SSD kept awake by %llu reads (slowest %.1f ms)" , 773 (unsigned long long )s .keepalive_reads ,s .keepalive_us_max /1000.0 ); 774return buf ; 775} 776 777void PleTable ::gather (const uint32_t * rows16 ,float * out2560 )const { 778 std::lock_guard < std::recursive_mutex > lk (impl_ -> mu );// issue + collect as one 779if (impl_ -> mode == PleIo ::Direct ) { 780// `gather` stays const for its existing callers; the reader's state is the table's I/O state. 781PleTable * self = const_cast < PleTable *> (this ); 782 std::string err ; 783if (!self -> issue (rows16 )|| !self -> collect (out2560 ,err )) { 784 std::fprintf (stderr ,"PleTable::gather: %s\n" ,err .empty () ?"a token is already in flight" :err .c_str ()); 785 std::memset (out2560 ,0 , (size_t )NG_N_EMBD * sizeof (float )); 786 } 787return ; 788 } 789// ================================ SIXTEEN SERIAL PAGE FAULTS, MEASURED ================================ 790// 791// **THIS COST 2.10-2.61 ms PER TOKEN AND HAD NEVER BEEN IN THE PLAN'S BUDGET AT ALL.** The round-309 792// `token host phases` line put it second behind the layer loop among avoidable terms, and the arithmetic 793// says why: the table is 320,001,536 rows of `PLE_ROW_BYTES` = 90 B in a 26.8 GB mapping, so the sixteen 794// rows a token needs are 1,440 B - **0.5 MB/s**. That is not bandwidth, it is latency: sixteen reads into 795// sixteen different 4 KB pages scattered across 26.8 GB, taken ONE AT A TIME, and on this machine the PLE 796// shard is 26.8 GB against 63 GB of RAM that the 31.6 GB expert arena is also competing for, so they are 797// not in the OS cache. Sixteen serial NVMe reads at ~150 us is 2.4 ms, which is the measurement. 798// 799// `PrefetchVirtualMemory` issues all sixteen in ONE call and lets them complete in parallel. It is a hint 800// and cannot change the answer - a range it does not fetch is simply faulted in by the read that follows - 801// so the only risk is that it does nothing. 802#if defined(_WIN32 ) 803if (impl_ -> data != nullptr && g_ple_prefetch ) { 804WIN32_MEMORY_RANGE_ENTRY ranges [PLE_N_HEADS ]; 805ULONG_PTR n = 0 ; 806for (int h = 0 ;h < PLE_N_HEADS ;++ h ) { 807// Out-of-range rows are handled by `read_row` as zeros and have no address to prefetch. 808if (rows16 [h ] >=impl_ -> n_rows )continue ; 809ranges [n ].VirtualAddress = (PVOID ) (impl_ -> data + (size_t )rows16 [h ]* impl_ -> rb ); 810ranges [n ].NumberOfBytes = impl_ -> rb ; 811++ n ; 812 } 813if (n > 0 ) (void )PrefetchVirtualMemory (GetCurrentProcess (),n ,ranges ,0 ); 814 } 815#endif 816// HEAD-SLOWEST, which is what `ggml_get_rows` does and what the source's own comment says: head h's 160 817// values occupy [h*160, (h+1)*160). A head-fastest layout would put element (d, h) at d*16 + h and needs 818// a real transpose - a reshape of the same flat buffer compares equal and would make the check vacuous. 819for (int h = 0 ;h < PLE_N_HEADS ;++ h )read_row (rows16 [h ],out2560 + (size_t )h * PLE_HEAD_DIM ); 820} 821 822}// namespace strata::kernels