okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
bd0e878f4
main
1// src/ngram/ple_reader_test.cpp - plan v0.3 P2: the direct SSD row reader against ground truth. 2// 3// ple_reader_test --selftest [--dir D] synthetic table file; CPU and disk only, no model, no GPU 4// ple_reader_test --gguf SHARD2 [--rows N] the real table: Direct vs Mmap bytes for N random rows (+ the 5// 16 rows of every token in --tokens FILE), with read latencies 6// 7// Every row the synthetic table holds encodes its own index, so a wrong offset, a straddle mishandled or a 8// dedup slot mixed up shows as a mismatch rather than as plausible data. 9#include "strata/kernels/ngram.hpp" 10#include "strata/ngram/ple_reader.hpp" 11#include "strata/platform/direct_file.hpp" 12 13#include <atomic> 14#include <chrono> 15#include <cstdio> 16#include <cstdlib> 17#include <cstring> 18#include <filesystem> 19#include <fstream> 20#include <random> 21#include <sstream> 22#include <string> 23#include <thread> 24#include <set> 25#include <vector> 26 27namespace ng= strata::ngram; 28namespace k= strata::kernels; 29using strata::platform::now_us ; 30 31namespace { 32 33int g_fail = 0 ; 34#define CHECK (c , ...) \ 35 do { \ 36 if (!(c)) { \ 37 std::fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); \ 38 std::fprintf(stderr, __VA_ARGS__); \ 39 std::fprintf(stderr, "\n"); \ 40 ++g_fail; \ 41 } \ 42 } while (0) 43 44constexpr uint64_t HEADER = 192 ;// the real shard's data offset, so rows are misaligned the same way 45 46void expected_row (uint32_t row ,uint32_t rb ,uint8_t * out ) { 47for (uint32_t b = 0 ;b < rb ;++ b )out [b ]= (uint8_t ) ((row * 2654435761u + b * 97u ) >>7 ); 48 std::memcpy (out ,& row ,4 ); 49} 50 51bool make_table (const std::string & path ,uint32_t rows ,uint32_t rb ) { 52 std::ofstream f (path , std::ios::binary ); 53 std::vector < uint8_t > head (HEADER ,0xAB ); 54f .write ((const char * )head .data (), (std::streamsize )head .size ()); 55 std::vector < uint8_t > r (rb ); 56for (uint32_t i = 0 ;i < rows ;++ i ) { 57expected_row (i ,rb ,r .data ()); 58f .write ((const char * )r .data (),rb ); 59 } 60return (bool )f ; 61} 62 63bool check_rows (ng::PleReader & rd ,const std::vector < uint32_t >& rows ,uint32_t n_rows ,uint32_t rb ,const char * what ) { 64 std::vector < uint8_t > out (rows .size ()* rb ,0xCC ); 65 std::string err ; 66const auto t = rd .issue (rows .data (),rows .size (),out .data ()); 67if (!rd .collect (t ,err )) {CHECK (false,"%s: collect failed: %s" ,what ,err .c_str ());return false; } 68 std::vector < uint8_t > want (rb ); 69for (size_t i = 0 ;i < rows .size ();++ i ) { 70if (rows [i ] >=n_rows ) std::memset (want .data (),0 ,rb ); 71else expected_row (rows [i ],rb ,want .data ()); 72if (std::memcmp (want .data (),& out [i * rb ],rb )!= 0 ) { 73CHECK (false,"%s: row %u (index %zu) differs" ,what ,rows [i ],i ); 74return false; 75 } 76 } 77return true; 78} 79 80/// issue() folds the rows of one ticket that share a 4 KiB page into one read (PR #4910: a small stack buffer for up to 64 81/// misses, a reusable vector above that, sorted by offset and merged in one pass). The bytes are checked as always; here the 82/// counters too: `requests` grows by the rows asked for, and `dedup_rows` by (rows read - distinct pages), worked out from the 83/// row numbers alone. Needs a reader without a row cache (a cached row is not a miss). 84bool check_coalescing (ng::PleReader & rd ,const std::vector < uint32_t >& rows ,uint32_t n_rows ,uint32_t rb ,const char * what ) { 85const ng::ReaderStats before = rd .snapshot (); 86if (!check_rows (rd ,rows ,n_rows ,rb ,what ))return false; 87const ng::ReaderStats after = rd .snapshot (); 88 std::set < uint64_t > pages ; 89size_t misses = 0 ; 90for (uint32_t r :rows ) 91if (r < n_rows ) {++ misses ;pages .insert ((HEADER + (uint64_t )r * rb ) /4096 * 4096 ); } 92CHECK (after .requests - before .requests == rows .size (),"%s: requests grew by %llu, not %zu" ,what , 93 (unsigned long long ) (after .requests - before .requests ),rows .size ()); 94CHECK (after .dedup_rows - before .dedup_rows == misses - pages .size (),"%s: dedup_rows grew by %llu, not %zu" ,what , 95 (unsigned long long ) (after .dedup_rows - before .dedup_rows ),misses - pages .size ()); 96return true; 97} 98 99/// THE BF16 TABLE, and the claim it rests on. A bfloat16 is literally the top half of a float32, so widening 100/// one is a shift: exact for every value, normal or not, with no rounding to hide behind. These patterns are 101/// the ones a lossy path would break on - the subnormals and the NaN/inf encodings a saturating cast to FP8 102/// would collapse - so a table that came back through the FP8 route would not reproduce all of them. 103void bf16_widening_is_exact () { 104const uint16_t bits []= {0x0000 ,0x8000 ,0x3f80 ,0xbf80 ,0x7f7f ,0xff7f ,// 0, -0, 1, -1, max, -max 1050x0001 ,0x8001 ,0x007f ,0x7f80 ,0xff80 ,// smallest subnormals, +-inf 1060x7fc0 ,0x7f81 ,0x4049 ,0xc249 ,0x3c75 };// NaN, signalling NaN, 3.14, -3.14 107for (uint16_t b :bits ) { 108uint8_t row [2 * k::PLE_HEAD_DIM ]; 109 std::memset (row ,0 ,sizeof row ); 110row [0 ]= (uint8_t )b ;// little-endian: the low byte first 111row [1 ]= (uint8_t ) (b >>8 ); 112float out [k::PLE_HEAD_DIM ]; 113 k::bf16_dequant_row (row ,out ); 114uint32_t want = (uint32_t )b <<16 ,got ; 115 std::memcpy (& got ,& out [0 ],sizeof got ); 116CHECK (got == want ,"bf16 0x%04x widened to 0x%08x, not 0x%08x" ,b ,got ,want ); 117bool tail_zero = true;// one element under test must not have shifted the rest 118for (int j = 1 ;j < k::PLE_HEAD_DIM ;++ j )tail_zero = tail_zero && out [j ]== 0.0f ; 119CHECK (tail_zero ,"bf16 0x%04x: the rest of the row is not zero" ,b ); 120 } 121} 122 123/// EVERY FORMAT OF THE TABLE, END TO END (table-driven: one entry in `k::ple_formats()` is one run here). A minimal 124/// PLE-only GGUF holds `rows` rows of that format's row size, each filled with bytes that encode the row, and both I/O 125/// modes must return exactly what the format's own dequantizer makes of those bytes - so the row width, the offset 126/// and the type lookup all have to be right for every format, not only for IQ4_NL. 127uint32_t gguf_type_id (const char * name ) { 128static const struct {const char * name ;uint32_t id ; }ids []= { 129 {"IQ4_NL" ,20 }, {"Q4_0" ,2 }, {"Q4_1" ,3 }, {"Q5_0" ,6 }, {"Q5_1" ,7 }, {"Q8_0" ,8 }, {"BF16" ,30 }, {"F8_E4M3" ,24 }, {"NVFP4" ,24 }}; 130for (const auto & e :ids ) 131if (std::strcmp (e .name ,name )== 0 )return e .id ; 132return 0xFFFFFFFFu ; 133} 134 135// `claimed_rows` is the row count the header states; `rows` rows are actually written (equal unless a test lies) 136std::string write_format_table (const std::string & dir ,const k::PleFormatInfo & f ,uint32_t rows ,uint64_t claimed_rows = 0 ) { 137const std::string path = dir + "/ple_format_selftest.gguf" ; 138 std::ofstream out (path , std::ios::binary ); 139if (!out ) { std::fprintf (stderr ,"cannot write %s\n" ,path .c_str ());return {}; } 140const auto le = [](auto value ,int bytes ) { 141 std::string s ((size_t )bytes ,'\0' ); 142for (int i = 0 ;i < bytes ;++ i )s [(size_t )i ]= (char ) ((value >> (8 * i ))& 0xff ); 143return s ; 144 }; 145const auto str = [& ](const char * s ) {return le ((uint64_t ) std::strlen (s ),8 )+ std::string (s ); }; 146const uint64_t n_kv = f .needs_scale ?3 :1 ; 147 std::string head = "GGUF" + le (3u ,4 )+ le (1ull ,8 )+ le (n_kv ,8 ); 148head += str ("general.architecture" )+ le (8u ,4 )+ str ("strata-ple" ); 149if (f .needs_scale ) { 150const float scale = 0.75f ; 151uint32_t sb ; 152 std::memcpy (& sb ,& scale ,4 ); 153head += str ("strata.ple.format" )+ le (8u ,4 )+ str (f .id == k::PleFormat ::NVFP4 ?"nvfp4x16" :"f8_e4m3" ); 154head += str ("strata.ple.scale" )+ le (6u ,4 )+ le (sb ,4 );// 6 = FLOAT32 155 } 156head += str ("per_layer_token_embd.weight" )+ le (2u ,4 ); 157head += le (f .id == k::PleFormat ::NVFP4 ? (uint64_t )f .row_bytes : (uint64_t ) k::PLE_HEAD_DIM ,8 )+ le (claimed_rows != 0 ?claimed_rows : (uint64_t )rows ,8 ); 158head += le (gguf_type_id (f .name ),4 )+ le (0ull ,8 ); 159while (head .size () %32 )head += '\0' ; 160out .write (head .data (), (std::streamsize )head .size ()); 161 std::vector < uint8_t > r (f .row_bytes ); 162for (uint32_t i = 0 ;i < rows ;++ i ) { 163expected_row (i ,f .row_bytes ,r .data ()); 164out .write ((const char * )r .data (), (std::streamsize )f .row_bytes ); 165 } 166out .close (); 167return out ?path : std::string (); 168} 169 170void format_round_trip (const std::string & dir ,const k::PleFormatInfo & f ,uint32_t rows ) { 171CHECK (gguf_type_id (f .name )!= 0xFFFFFFFFu ,"%s: no GGUF type id in this test" ,f .name ); 172CHECK (f .row_bytes > 0 && f .row_bytes <= (uint32_t ) k::PLE_ROW_BYTES_MAX ,"%s: row_bytes %u out of range" ,f .name ,f .row_bytes ); 173const std::string path = write_format_table (dir ,f ,rows ); 174if (path .empty ()) {CHECK (false,"%s: no table was written" ,f .name );return ; } 175 std::mt19937 rng (13 ); 176 std::vector < uint32_t > want (rows ); 177for (uint32_t i = 0 ;i < rows ;++ i )want [i ]= rng () %rows ; 178want [0 ]= 0 ; 179want [1 ]= rows - 1 ; 180for (k::PleIo mode : {k::PleIo ::Direct , k::PleIo ::Mmap }) { 181const char * name = mode == k::PleIo ::Direct ?"direct" :"mmap" ; 182 k::PleTable t ; 183 std::string err ; 184 k::PleIoOptions io ; 185io .mode = mode ; 186io .max_inflight = 8 ; 187io .cache_rows = 0 ; 188CHECK (t .open (path ,err ,io ),"%s: open in %s mode: %s" ,f .name ,name ,err .c_str ()); 189if (g_fail )break ; 190CHECK (std::strcmp (t .format (),f .name )== 0 ,"%s: format() says \"%s\"" ,f .name ,t .format ()); 191CHECK (t .rows ()== rows ,"%s: rows %llu, not %u" ,f .name , (unsigned long long )t .rows (),rows ); 192// The residency policy in generate.cpp sizes the table with table_bytes(); it must be the file's own 193// row count x row bytes in both modes, and 0 once the table is closed. 194CHECK (t .table_bytes ()== (uint64_t )rows * f .row_bytes ,"%s: %s: table_bytes %llu, not %u x %u" ,f .name ,name , 195 (unsigned long long )t .table_bytes (),rows ,f .row_bytes ); 196 std::vector < uint8_t > raw (f .row_bytes ); 197float got [k::PLE_HEAD_DIM ],ref [k::PLE_HEAD_DIM ]; 198for (uint32_t r :want ) { 199t .read_row (r ,got ); 200expected_row (r ,f .row_bytes ,raw .data ()); 201f .dequant (raw .data (),f .needs_scale ?0.75f :1.0f ,ref ); 202if (std::memcmp (got ,ref ,sizeof got )!= 0 ) { 203CHECK (false,"%s: %s: row %u differs from the format's own dequantizer" ,f .name ,name ,r ); 204break ; 205 } 206 } 207// the 16-row path a token takes, one batch 208float tok [16 * k::PLE_HEAD_DIM ]; 209uint32_t rows16 [16 ]; 210for (int h = 0 ;h < 16 ;++ h )rows16 [h ]= want [(size_t )h + 2 ]; 211t .gather (rows16 ,tok ); 212for (int h = 0 ;h < 16 ;++ h ) { 213expected_row (rows16 [h ],f .row_bytes ,raw .data ()); 214f .dequant (raw .data (),f .needs_scale ?0.75f :1.0f ,ref ); 215CHECK (std::memcmp (tok + (size_t )h * k::PLE_HEAD_DIM ,ref ,sizeof ref )== 0 ,"%s: %s: gather head %d differs" ,f .name ,name ,h ); 216 } 217// a prompt chunk: gather_batch over more rows than one prefetch window (4096), one of them past the table's end 218 { 219const size_t nt = 700 ,nr = nt * 16 ;// 11200 rows, three windows 220 std::vector < uint32_t > br (nr ); 221for (size_t i = 0 ;i < nr ;++ i )br [i ]= want [i %want .size ()]; 222if (mode == k::PleIo ::Mmap )br [5000 ]= rows + 7 ;// out of range (mapped): zeros, as read_row gives 223 std::vector < float > bo (nr * k::PLE_HEAD_DIM ); 224 std::string e2 ; 225CHECK (t .gather_batch (br .data (),nt ,bo .data (),e2 ),"%s: %s: gather_batch: %s" ,f .name ,name ,e2 .c_str ()); 226size_t bad = 0 ; 227for (size_t i = 0 ;i < nr && !g_fail ;++ i ) { 228if (br [i ] >=rows ) { 229for (int d = 0 ;d < k::PLE_HEAD_DIM ;++ d )bad += bo [i * k::PLE_HEAD_DIM + d ]!= 0.0f ; 230continue ; 231 } 232expected_row (br [i ],f .row_bytes ,raw .data ()); 233f .dequant (raw .data (),f .needs_scale ?0.75f :1.0f ,ref ); 234bad += std::memcmp (bo .data ()+ i * k::PLE_HEAD_DIM ,ref ,sizeof ref )!= 0 ; 235 } 236CHECK (bad == 0 ,"%s: %s: gather_batch differs in %zu rows" ,f .name ,name ,bad ); 237 } 238 } 239 std::filesystem::remove (path ); 240} 241 242/// A table whose header does not match the file is refused with a message, never read past its end (#865): one row 243/// short, one row long (a single-tensor shard must be filled exactly), and a row count that wraps the 64-bit size. 244void bad_sizes_are_refused (const std::string & dir ) { 245for (int i = 0 ;i < k::ple_format_count ();++ i ) { 246const k::PleFormatInfo & f = k::ple_formats ()[i ]; 247struct {const char * what ;uint32_t rows ;uint64_t claimed ; }cases []= { 248 {"claims one row more than the file holds" ,500 ,501 }, 249 {"claims one row less than the file holds" ,500 ,499 }, 250 {"claims a row count that wraps 2^64" ,8 , (uint64_t )0x4000000000000000ull /3 * 2 }, 251 }; 252for (const auto & c :cases ) { 253const std::string path = write_format_table (dir ,f ,c .rows ,c .claimed ); 254if (path .empty ()) {CHECK (false,"%s: no table was written" ,f .name );continue ; } 255for (k::PleIo mode : {k::PleIo ::Direct , k::PleIo ::Mmap }) { 256 k::PleTable t ; 257 std::string err ; 258 k::PleIoOptions io ; 259io .mode = mode ; 260io .cache_rows = 0 ; 261CHECK (!t .open (path ,err ,io ),"%s: a table that %s was accepted" ,f .name ,c .what ); 262CHECK (!err .empty (),"%s: refused without a message (%s)" ,f .name ,c .what ); 263CHECK (!t .is_open (),"%s: left open after refusing (%s)" ,f .name ,c .what ); 264 } 265 std::filesystem::remove (path ); 266 } 267 } 268} 269 270// #2622 (reported by @hotschmoe): gather_batch matched the prefetched tokens by position, so a prefetch of A..F 271// gathered as D,E,F,A,B,C (or A gathered as A,A,A) issued a second ticket for rows that were already in flight. 272// Every case: the bytes equal the mapped reader's, and the requested-row counter says how many rows were re-read. 273void prefetched_keys_are_reused (const std::string & dir ) { 274const k::PleFormatInfo * fmt = nullptr ; 275for (int i = 0 ;i < k::ple_format_count ();++ i ) 276if (std::string (k::ple_formats ()[i ].name )== "IQ4_NL" )fmt = & k::ple_formats ()[i ]; 277if (fmt == nullptr ) {CHECK (false,"no IQ4_NL format" );return ; } 278const std::string path = write_format_table (dir ,* fmt ,4096 ); 279if (path .empty ()) {CHECK (false,"cannot write the prefetch table" );return ; } 280struct Case {const char * name ; std::vector < int > pre ,want ;uint64_t extra_rows ; }; 281 std::vector < int > seventeen ; 282for (int i = 0 ;i < 17 ;++ i )seventeen .push_back (i ); 283const std::vector < Case > cases = { 284 {"ordered" , {0 ,1 }, {0 ,1 },0 }, 285 {"permutation" , {0 ,1 ,2 ,3 ,4 ,5 }, {3 ,4 ,5 ,0 ,1 ,2 },0 }, 286 {"subset" , {0 ,1 ,2 ,3 ,4 ,5 }, {4 ,1 },0 }, 287 {"duplicates" , {0 }, {0 ,0 ,0 },0 }, 288 {"duplicate prefetch" , {0 ,0 ,1 }, {0 ,1 },0 }, 289 {"missing key" , {0 ,1 }, {0 ,2 },32 }, 290 {"extra prefetch" , {0 ,1 ,2 }, {1 },0 }, 291 {"none" , {0 }, {},0 }, 292 {"over the window" , {0 ,1 },seventeen ,17u * k::PLE_N_HEADS }, 293 {"window overflow" ,seventeen , {16 },0 }, 294 }; 295const auto keys = [](const std::vector < int >& ids ) { 296 std::vector < uint32_t > r ; 297for (int id :ids )for (int h = 0 ;h < k::PLE_N_HEADS ;++ h )r .push_back ((uint32_t ) (id * 32 + h )); 298return r ; 299 }; 300const auto requests = [](const k::PleTable & t ) { 301unsigned long long n = 0 ; 302const std::string s = t .io_report (); 303return std::sscanf (s .c_str (),"ple io: %llu rows" ,& n )== 1 ? (uint64_t )n : ~0ull ; 304 }; 305const size_t tok = (size_t ) k::PLE_N_HEADS * k::PLE_HEAD_DIM ; 306 std::vector < std::vector < float >> refs (cases .size ()); 307 { 308 k::PleTable mapped ; 309 k::PleIoOptions mio ; 310mio .mode = k::PleIo ::Mmap ; 311 std::string err ; 312if (!mapped .open (path ,err ,mio )) {CHECK (false,"mapped open: %s" ,err .c_str ());return ; } 313for (size_t c = 0 ;c < cases .size ();++ c ) { 314const auto r = keys (cases [c ].want ); 315refs [c ].resize (cases [c ].want .size ()* tok ); 316CHECK (mapped .gather_batch (r .data (),cases [c ].want .size (),refs [c ].data (),err ),"mapped gather: %s" ,err .c_str ()); 317 } 318 } 319for (uint64_t cache : {uint64_t (0 ),uint64_t (256 )})for (bool worker : {false, true}) { 320for (size_t c = 0 ;c < cases .size ();++ c ) { 321 k::PleTable t ; 322 k::PleIoOptions io ; 323io .mode = k::PleIo ::Direct ; 324io .cache_rows = cache ; 325io .io_thread = worker ; 326io .max_inflight = 8 ; 327io .keepalive_ms = 0 ; 328 std::string err ; 329if (!t .open (path ,err ,io )) {CHECK (false,"direct open: %s" ,err .c_str ());return ; } 330const auto pr = keys (cases [c ].pre ),wr = keys (cases [c ].want ); 331for (size_t i = 0 ;i < cases [c ].pre .size ();++ i )t .prefetch_rows (pr .data ()+ i * k::PLE_N_HEADS ); 332const uint64_t rq = requests (t ),by = t .bytes_read (); 333const float sentinel = -12345.5f ; 334 std::vector < float > out (refs [c ].size ()+ 2 ,sentinel ); 335const bool ok = t .gather_batch (wr .data (),cases [c ].want .size (),out .data ()+ 1 ,err ); 336CHECK (ok ,"%s (cache %llu worker %d): %s" ,cases [c ].name , (unsigned long long )cache , (int )worker ,err .c_str ()); 337CHECK (requests (t )- rq == cases [c ].extra_rows ,"%s (cache %llu worker %d): %llu rows re-requested, want %llu" , 338cases [c ].name , (unsigned long long )cache , (int )worker , (unsigned long long ) (requests (t )- rq ), 339 (unsigned long long )cases [c ].extra_rows ); 340CHECK (t .bytes_read ()- by == cases [c ].want .size ()* k::PLE_N_HEADS * fmt -> row_bytes ,"%s: bytes_read" ,cases [c ].name ); 341CHECK (refs [c ].empty ()|| std::memcmp (out .data ()+ 1 ,refs [c ].data (),refs [c ].size ()* sizeof (float ))== 0 , 342"%s (cache %llu worker %d): bytes differ from the mapped reader" ,cases [c ].name , (unsigned long long )cache , (int )worker ); 343CHECK (out .front ()== sentinel && out .back ()== sentinel ,"%s: wrote outside the output" ,cases [c ].name ); 344 } 345 } 346if (g_fail == 0 ) std::printf ("ple prefetched-key reuse (reordered, duplicated, subset), Direct vs Mmap bytes: OK\n" ); 347} 348 349/// #3602: the table the way the engine uses it - one PleTable shared by the prompt path (big gather_batch calls on a 350/// thread of their own, as prefill's std::async does), the decode window (prefetch_rows for each token, then 351/// gather_batch of the window) and the single-token gather, all at once, with a row cache that evicts all the time 352/// and one in-flight slot. Every float must equal what the mapped reader returns for the same rows. 353void table_is_consistent_under_concurrent_use (const std::string & dir ) { 354const k::PleFormatInfo * fmt = nullptr ; 355for (int i = 0 ;i < k::ple_format_count ();++ i ) 356if (std::string (k::ple_formats ()[i ].name )== "IQ4_NL" )fmt = & k::ple_formats ()[i ]; 357if (fmt == nullptr ) {CHECK (false,"no IQ4_NL format" );return ; } 358const uint32_t rows = 30000 ; 359const std::string path = write_format_table (dir ,* fmt ,rows ); 360if (path .empty ()) {CHECK (false,"cannot write the concurrency table" );return ; } 361 k::PleTable mapped ; 362 { 363 k::PleIoOptions mio ; 364mio .mode = k::PleIo ::Mmap ; 365 std::string err ; 366if (!mapped .open (path ,err ,mio )) {CHECK (false,"mapped open: %s" ,err .c_str ());return ; } 367 } 368const size_t tok = (size_t ) k::PLE_N_HEADS * k::PLE_HEAD_DIM ; 369// rows that straddle a page: row r sits at (header + 90 r), the header is the GGUF's; just take every 7th and every 45th 370auto pick_rows = [& ](std::mt19937 & rng ,size_t n ) { 371 std::vector < uint32_t > r (n ); 372for (auto & x :r ) { 373switch (rng () %6 ) { 374case 0 :x = rows - 1 - rng () %8 ;break ; 375case 1 :x = rng () %8 ;break ; 376case 2 :x = (uint32_t ) (rng () % (rows /45 ))* 45u ;break ; 377case 3 :x = 100 + rng () %12 ;break ;// a hot neighbourhood 378case 4 :x = rows + rng () %3 ;break ;// out of range: zeros in both readers 379default :x = rng () %rows ; 380 } 381 } 382return r ; 383 }; 384for (uint64_t cache : {uint64_t (0 ),uint64_t (16 ),uint64_t (4096 )}) 385for (uint32_t inflight : {1u ,3u ,64u }) { 386 k::PleTable t ; 387 k::PleIoOptions io ; 388io .mode = k::PleIo ::Direct ; 389io .cache_rows = cache ; 390io .max_inflight = inflight ; 391io .io_thread = true; 392io .keepalive_ms = inflight == 3 ?1.0 :0 ; 393 std::string err ; 394if (!t .open (path ,err ,io )) {CHECK (false,"direct open: %s" ,err .c_str ());return ; } 395 std::atomic < int > bad {0 }; 396 std::printf (" table under concurrent use: cache %llu rows, inflight %u\n" , (unsigned long long )cache ,inflight ); 397auto same = [& ](const std::vector < uint32_t >& r ,size_t n_tokens ,const float * got ,const char * what ) { 398 std::vector < float > ref (n_tokens * tok ); 399 std::string e ; 400if (!mapped .gather_batch (r .data (),n_tokens ,ref .data (),e )) {++ bad ;CHECK (false,"mapped reference: %s" ,e .c_str ());return ; } 401// (equal as numbers: a row past the table's end is zero bytes in both readers, but the direct one decodes the 402// zero bytes, which can give -0.0 where the mapped one writes +0.0; the table's bytes are random, so some values are NaN: 403// those are compared by their bits) 404size_t at = 0 ; 405while (at < ref .size ()&& (ref [at ]== got [at ]|| std::memcmp (& ref [at ],& got [at ],sizeof (float ))== 0 ))++ at ; 406if (at < ref .size ()) { 407++ bad ; 408CHECK (false,"%s (cache %llu, inflight %u): value %zu of %zu differs from the mapped reader (row %u of %u in range: mapped %g, direct %g)" , 409what , (unsigned long long )cache ,inflight ,at ,ref .size (),r [at / k::PLE_HEAD_DIM ],rows , 410 (double )ref [at ], (double )got [at ]); 411 } 412 }; 413 std::thread prompt ([& ] {try {// prefill: chunks of tokens, gathered on a thread 414 std::mt19937 rng (5 ); 415for (int i = 0 ;i < 12 && bad == 0 ;++ i ) { 416static const size_t sizes [4 ]= {17 ,300 ,700 ,64 }; 417const size_t nt = sizes [rng () %4 ]; 418const auto r = pick_rows (rng ,nt * k::PLE_N_HEADS ); 419 std::vector < float > out (nt * tok ,-7.0f ); 420 std::string e ; 421if (!t .gather_batch (r .data (),nt ,out .data (),e )) {++ bad ;CHECK (false,"prompt gather_batch: %s" ,e .c_str ());return ; } 422same (r ,nt ,out .data (),"prompt gather_batch" ); 423 } 424 }catch (const std::exception & e ) {++ bad ;CHECK (false,"prompt thread: exception %s" ,e .what ()); } }); 425 std::thread decode ([& ] {try {// verify windows: prefetch each token's rows, then gather the window 426 std::mt19937 rng (6 ); 427for (int i = 0 ;i < 300 && bad == 0 ;++ i ) { 428const size_t T = 1 + rng () %8 ; 429const auto r = pick_rows (rng ,T * k::PLE_N_HEADS ); 430for (size_t j = 0 ;j < T ;++ j )t .prefetch_rows (r .data ()+ j * k::PLE_N_HEADS ); 431if (rng () %4 == 0 ) {// a prefetch nobody asks for (a draft that was dropped) 432const auto extra = pick_rows (rng , k::PLE_N_HEADS ); 433t .prefetch_rows (extra .data ()); 434 } 435 std::vector < float > out (T * tok ,-7.0f ); 436 std::string e ; 437if (!t .gather_batch (r .data (),T ,out .data (),e )) {++ bad ;CHECK (false,"window gather_batch: %s" ,e .c_str ());return ; } 438same (r ,T ,out .data (),"window gather_batch" ); 439 } 440 }catch (const std::exception & e ) {++ bad ;CHECK (false,"decode thread: exception %s" ,e .what ()); } }); 441 std::thread single ([& ] {try {// the single-token gather 442 std::mt19937 rng (7 ); 443for (int i = 0 ;i < 300 && bad == 0 ;++ i ) { 444const auto r = pick_rows (rng , k::PLE_N_HEADS ); 445 std::vector < float > out (tok ,-7.0f ); 446t .gather (r .data (),out .data ()); 447same (r ,1 ,out .data (),"gather" ); 448 } 449 }catch (const std::exception & e ) {++ bad ;CHECK (false,"single thread: exception %s" ,e .what ()); } }); 450prompt .join (); 451decode .join (); 452single .join (); 453t .close (); 454 } 455mapped .close ();// (Windows cannot delete a file that is still mapped, and remove() throws) 456 std::error_code rm_ec ; 457 std::filesystem::remove (path ,rm_ec ); 458if (g_fail == 0 ) std::printf ("ple table shared by a prompt thread, a decode window and a single gather, 9 reader configurations, vs the mapped reader: OK\n" ); 459} 460 461void all_formats_round_trip (const std::string & dir ) { 462bf16_widening_is_exact ();// BF16's own claim: a shift, exact for every pattern 463bad_sizes_are_refused (dir ); 464prefetched_keys_are_reused (dir ); 465table_is_consistent_under_concurrent_use (dir ); 466CHECK (k::ple_format_count ()> 0 ,"no formats" ); 467for (int i = 0 ;i < k::ple_format_count ();++ i ) { 468const k::PleFormatInfo & f = k::ple_formats ()[i ]; 469CHECK ((int )f .id == i ,"%s: the table is not in PleFormat order" ,f .name ); 470// NVFP4 and F8_E4M3 are both I8 bytes: the type finds the FP8 entry, `strata.ple.format` picks NVFP4 in PleTable::open 471const k::PleFormatInfo * want = f .id == k::PleFormat ::NVFP4 ?& k::ple_format_info (k::PleFormat ::F8_E4M3 ) :& f ; 472CHECK (k::ple_format_for_type (f .gguf_type )== want ,"%s: type lookup" ,f .name ); 473format_round_trip (dir ,f ,2000 ); 474 } 475CHECK (k::ple_format_for_type ("Q6_K" )== nullptr ,"Q6_K must not be a PLE format" ); 476if (g_fail == 0 ) { 477 std::printf ("ple formats, both readers vs their dequantizers:" ); 478for (int i = 0 ;i < k::ple_format_count ();++ i ) std::printf (" %s" , k::ple_formats ()[i ].name ); 479 std::printf (": OK\n" ); 480 } 481} 482 483// row_bytes: ng::ROW_BYTES (90, IQ4_NL) is the production default; 110 (#296, OrcaRouter's Q5_0 PLE rows) is 484// run too, through the exact same generic row_bytes path -- nothing here is IQ4_NL-specific, so a second row 485// size run here is the correctness evidence for lifting ngram.cpp's "Q5_0 PLE requires --ple-io mmap" refusal. 486int selftest (const std::string & dir ,uint32_t rb ) { 487const uint32_t N = 500000 ;// 45 MB: large enough for thousands of distinct pages 488const std::string path = dir + "/ple_reader_selftest_" + std::to_string (rb )+ ".bin" ; 489if (!make_table (path ,N ,rb )) { std::fprintf (stderr ,"cannot write %s\n" ,path .c_str ());return 2 ; } 490 std::mt19937 rng (7 ); 491for (bool thr : {false, true}) 492for (uint64_t cache : {0ull ,4096ull }) { 493for (uint32_t inflight : {1u ,8u ,64u }) { 494 ng::PleReader rd ; 495 std::string err ; 496CHECK (rd .open (path ,HEADER ,N ,inflight ,cache ,err ,thr ,rb ),"open: %s" ,err .c_str ()); 497// decode-shaped tickets: 16 random rows 498for (int t = 0 ;t < 200 ;++ t ) { 499 std::vector < uint32_t > rows (16 ); 500for (auto & r :rows )r = rng () %N ; 501check_rows (rd ,rows ,N ,rb ,"decode" ); 502 } 503// rows that straddle a 4 KiB boundary: byte offset of row r is HEADER + rb * r 504 std::vector < uint32_t > straddle ; 505for (uint32_t r = 0 ;r < N && straddle .size ()< 64 ;++ r ) { 506const uint64_t a = HEADER + (uint64_t )r * rb ; 507if (a /4096 != (a + rb - 1 ) /4096 )straddle .push_back (r ); 508 } 509check_rows (rd ,straddle ,N ,rb ,"straddle" ); 510// duplicates, neighbours on one page, the first and last rows, and out-of-range rows 511check_rows (rd , {5 ,5 ,6 ,7 ,5 ,0 ,N - 1 ,N ,0xFFFFFFFFu ,44 ,45 },N ,rb ,"dedup/edges" ); 512if (cache == 0 ) { 513// batch sizes around the small-buffer bound (64), empty, one, and well above it; each shape twice, big and 514// small alternating so the reusable overflow vector is reused at a smaller size too 515for (size_t n : {(size_t )0 , (size_t )1 , (size_t )2 , (size_t )15 , (size_t )16 , (size_t )63 , (size_t )64 , 516 (size_t )65 , (size_t )66 , (size_t )127 , (size_t )128 , (size_t )129 , (size_t )1000 , (size_t )4096 , 517 (size_t )65 , (size_t )1 , (size_t )300 }) { 518 std::vector < uint32_t > rows (n ); 519for (auto & r :rows )r = rng () %N ; 520check_coalescing (rd ,rows ,N ,rb ,"random" ); 521for (auto & r :rows )r = 1000 + rng () %200 ;// ~200 rows of a few dozen pages: many shared 522check_coalescing (rd ,rows ,N ,rb ,"clustered" ); 523for (auto & r :rows )r = 77 ;// one row n times 524check_coalescing (rd ,rows ,N ,rb ,"one row" ); 525for (size_t i = 0 ;i < n ;++ i )rows [i ]= (uint32_t ) (n - 1 - i )* 3 ;// descending: the sort reorders them 526check_coalescing (rd ,rows ,N ,rb ,"descending" ); 527for (size_t i = 0 ;i < n ;++ i )rows [i ]= (i %5 == 0 ) ?N + (uint32_t )i : (uint32_t ) (i /2 )* 7 ;// out of range among misses 528check_coalescing (rd ,rows ,N ,rb ,"out of range mix" ); 529 } 530 std::vector < uint32_t > straddle_dup ;// rows that cross a page, each twice, interleaved 531for (uint32_t r = 0 ;r < N && straddle_dup .size ()< 140 ;++ r ) { 532const uint64_t at = HEADER + (uint64_t )r * rb ; 533if (at /4096 != (at + rb - 1 ) /4096 ) {straddle_dup .push_back (r );straddle_dup .push_back (r ); } 534 } 535check_coalescing (rd ,straddle_dup ,N ,rb ,"straddle twice" ); 536 } 537// a prefill-shaped ticket much larger than the in-flight window 538 std::vector < uint32_t > bulk (20000 ); 539for (auto & r :bulk )r = rng () %N ; 540check_rows (rd ,bulk ,N ,rb ,"bulk" ); 541// two tickets in flight at once, collected in reverse order 542 std::vector < uint32_t > a (16 ),b (16 ); 543for (auto & r :a )r = rng () %N ; 544for (auto & r :b )r = rng () %N ; 545 std::vector < uint8_t > oa (16 * rb ),ob (16 * rb ); 546const auto ta = rd .issue (a .data (),16 ,oa .data ()); 547const auto tb = rd .issue (b .data (),16 ,ob .data ()); 548CHECK (rd .collect (tb ,err )&& rd .collect (ta ,err ),"two tickets: %s" ,err .c_str ()); 549 std::vector < uint8_t > want (rb ); 550for (int i = 0 ;i < 16 ;++ i ) { 551expected_row (a [i ],rb ,want .data ()); 552CHECK (!std::memcmp (want .data (),& oa [i * rb ],rb ),"ticket a row %d" ,i ); 553expected_row (b [i ],rb ,want .data ()); 554CHECK (!std::memcmp (want .data (),& ob [i * rb ],rb ),"ticket b row %d" ,i ); 555 } 556if (cache > 0 )CHECK (rd .stats ().cache_hits > 0 ,"the row cache never hit" ); 557CHECK (rd .cache_size () <=rd .cache_capacity (),"row cache exceeded its bound" ); 558 } 559 } 560// fault injection: a 3 ms delay must be observed, and must not change the bytes 561for (bool thr : {false, true}) { 562 ng::PleReader rd ; 563 std::string err ; 564CHECK (rd .open (path ,HEADER ,N ,16 ,0 ,err ,thr ,rb ),"open: %s" ,err .c_str ()); 565rd .set_injected_delay_us (3000 ); 566 std::vector < uint32_t > rows (16 ); 567for (auto & r :rows )r = rng () %N ; 568const double t0 = now_us (); 569check_rows (rd ,rows ,N ,rb ,"delayed" ); 570CHECK (now_us ()- t0 >=3000 ,"injected delay not observed (%.0f us)" ,now_us ()- t0 ); 571CHECK (rd .stats ().late_injected > 0 ,"no read was held back" ); 572 } 573// keep-alive: while rows are asked for, a page goes out after `period` without a read; it stops once the 574// window after the last issue has passed, starts again with the next issue (even one the row cache serves), 575// and never shows up as a row read or changes a row 576 { 577 ng::PleReader rd ; 578 std::string err ; 579CHECK (rd .open (path ,HEADER ,N ,16 ,4096 ,err , true,rb ),"open: %s" ,err .c_str ()); 580rd .set_keepalive (20.0 ,0.5 ); 581 std::vector < uint32_t > rows (16 ); 582for (auto & r :rows )r = rng () %N ; 583check_rows (rd ,rows ,N ,rb ,"keep-alive, first ticket" ); 584const uint64_t reads0 = rd .snapshot ().reads ; 585const auto nap = [](int ms ) { std::this_thread::sleep_for (std::chrono::milliseconds (ms )); }; 586nap (300 ); 587const uint64_t k1 = rd .snapshot ().keepalive_reads ; 588CHECK (k1 >=8 && k1 <=20 ,"keep-alive: %llu reads in 300 ms at a 20 ms period" , (unsigned long long )k1 ); 589CHECK (rd .snapshot ().reads == reads0 ,"keep-alive reads were counted as row reads" ); 590nap (600 );// the 0.5 s window has passed 591const uint64_t k2 = rd .snapshot ().keepalive_reads ; 592nap (300 ); 593const uint64_t k3 = rd .snapshot ().keepalive_reads ; 594CHECK (k3 == k2 ,"keep-alive went on after the window (%llu -> %llu)" , (unsigned long long )k2 , 595 (unsigned long long )k3 ); 596CHECK (k2 <=k1 + 20 ,"keep-alive: %llu reads by the end of a 0.5 s window" , (unsigned long long )k2 ); 597check_rows (rd ,rows ,N ,rb ,"keep-alive, cached ticket" );// the row cache serves all 16: no row read 598CHECK (rd .snapshot ().reads == reads0 ,"cached rows were read again" ); 599nap (200 ); 600CHECK (rd .snapshot ().keepalive_reads >=k3 + 5 ,"the keep-alive did not start again (%llu -> %llu)" , 601 (unsigned long long )k3 , (unsigned long long )rd .snapshot ().keepalive_reads ); 602 std::vector < uint32_t > more (2000 ); 603for (auto & r :more )r = rng () %N ; 604check_rows (rd ,more ,N ,rb ,"keep-alive, rows afterwards" ); 605rd .set_keepalive (0 ,0.5 );// off 606const uint64_t k4 = rd .snapshot ().keepalive_reads ; 607nap (200 ); 608CHECK (rd .snapshot ().keepalive_reads <=k4 + 1 ,"keep-alive went on after it was turned off" ); 609rd .reset_stats (); 610CHECK (rd .snapshot ().keepalive_reads == 0 && rd .snapshot ().keepalive_us_max == 0 ,"reset_stats kept keep-alive counts" ); 611 } 612 {// the caller's thread does the reads: no worker, so no keep-alive 613 ng::PleReader rd ; 614 std::string err ; 615CHECK (rd .open (path ,HEADER ,N ,16 ,0 ,err , false,rb ),"open: %s" ,err .c_str ()); 616rd .set_keepalive (20.0 ,1.0 ); 617 std::vector < uint32_t > rows (16 ); 618for (auto & r :rows )r = rng () %N ; 619check_rows (rd ,rows ,N ,rb ,"keep-alive, caller thread" ); 620 std::this_thread::sleep_for (std::chrono::milliseconds (150 )); 621CHECK (rd .snapshot ().keepalive_reads == 0 ,"keep-alive without the worker thread" ); 622 } 623 std::filesystem::remove (path ); 624 std::printf ("ple_reader selftest (row_bytes=%u): %s\n" ,rb ,g_fail ?"FAILED" :"OK" ); 625return g_fail ?1 :0 ; 626} 627 628int real (const std::string & gguf ,int n_random ,const std::string & tokens_path ,uint32_t inflight ,bool direct_first , 629bool direct_only ,bool sync_submit ) { 630 k::PleTable mm ,direct ; 631 std::string err ; 632 k::PleIoOptions mo ; 633mo .mode = k::PleIo ::Mmap ; 634 k::PleIoOptions dopt ; 635dopt .cache_rows = 0 ;// measure the SSD, not the cache 636dopt .max_inflight = inflight ; 637dopt .io_thread = !sync_submit ; 638// `--direct-only` measures the direct path with NO mapping of the file alive anywhere in the process: a 639// live section on the same file forces the file system to keep cached and non-cached views coherent. 640if (!direct_only && !mm .open (gguf ,err ,mo )) { std::fprintf (stderr ,"mmap open: %s\n" ,err .c_str ());return 2 ; } 641if (!direct .open (gguf ,err ,dopt )) { std::fprintf (stderr ,"direct open: %s\n" ,err .c_str ());return 2 ; } 642 std::vector < std::vector < uint32_t >> tickets ; 643 std::mt19937_64 rng (11 ); 644for (int t = 0 ;t < n_random /16 ;++ t ) { 645 std::vector < uint32_t > r (16 ); 646for (auto & x :r )x = (uint32_t ) (rng () %direct .rows ()); 647tickets .push_back (r ); 648 } 649if (!tokens_path .empty ()) { 650 std::ifstream f (tokens_path ); 651 std::string text ((std::istreambuf_iterator < char > (f )), std::istreambuf_iterator < char > ()); 652for (char & c :text )if (c == ',' )c = ' ' ; 653 std::istringstream in (text ); 654 std::vector < int32_t > ids ; 655for (int32_t v ;in >>v ;)ids .push_back (v ); 656const k::PleConsts C = k::ple_artifact_consts (); 657for (size_t i = 0 ;i < ids .size ();++ i ) { 658const int32_t prev [2 ]= {i >=2 ?ids [i - 2 ] : k::TOKEN_NULL ,i >=1 ?ids [i - 1 ] : k::TOKEN_NULL }; 659 std::vector < uint32_t > r (16 ); 660 k::ngram_rows (& ids [i ],prev ,1 ,C ,r .data ()); 661tickets .push_back (r ); 662 } 663 } 664 std::vector < float > a (k::NG_N_EMBD ),b (k::NG_N_EMBD ); 665double t_mm = 0 ,t_dir = 0 ,t_issue = 0 ; 666for (const auto & r :tickets ) { 667for (int pass = 0 ;pass < 2 ;++ pass ) { 668const bool do_direct = (pass == 0 )== direct_first ; 669const double t0 = now_us (); 670if (!do_direct ) { 671if (direct_only )continue ; 672mm .gather (r .data (),a .data ()); 673t_mm += now_us ()- t0 ; 674 }else { 675const double ti = now_us (); 676const bool issued = direct .issue (r .data ()); 677t_issue += now_us ()- ti ; 678if (!issued || !direct .collect (b .data (),err )) { 679 std::fprintf (stderr ,"direct: %s\n" ,err .c_str ()); 680return 1 ; 681 } 682t_dir += now_us ()- t0 ; 683 } 684 } 685if (!direct_only ) 686CHECK (!std::memcmp (a .data (),b .data (),a .size ()* sizeof (float )),"token rows differ between mmap and direct" ); 687 } 688 std::printf ("tokens %zu: mmap %.1f us/token, direct %.1f us/token (issue on this thread %.1f us)\n%s\n" , 689tickets .size (),t_mm / (double )tickets .size (),t_dir / (double )tickets .size (), 690t_issue / (double )tickets .size (),direct .io_report ().c_str ()); 691 std::printf ("ple_reader real-table check: %s\n" ,g_fail ?"FAILED" :"OK (bit-identical)" ); 692return g_fail ?1 :0 ; 693} 694 695}// namespace 696 697int main (int argc ,char ** argv ) { 698 std::setvbuf (stdout ,nullptr ,_IONBF ,0 );// (progress lines survive a crash) 699 std::string gguf ,dir = std::filesystem::temp_directory_path ().string (),tokens ; 700int rows = 20000 ; 701uint32_t inflight = 64 ; 702bool direct_first = false; 703bool direct_only = false; 704bool sync_submit = false; 705bool self = false; 706 std::string make_path ,make_fmt ,ram_path ;// --make-table PATH FORMAT (uses --rows), --ram-time PATH 707for (int i = 1 ;i < argc ;++ i ) { 708const std::string a = argv [i ]; 709if (a == "--selftest" )self = true; 710else if (a == "--make-table" && i + 2 < argc ) {make_path = argv [i + 1 ];make_fmt = argv [i + 2 ];i += 2 ; } 711else if (a == "--ram-time" && i + 1 < argc )ram_path = argv [++ i ]; 712else if (a == "--dir" && i + 1 < argc )dir = argv [++ i ]; 713else if (a == "--gguf" && i + 1 < argc )gguf = argv [++ i ]; 714else if (a == "--rows" && i + 1 < argc )rows = std::atoi (argv [++ i ]); 715else if (a == "--tokens" && i + 1 < argc )tokens = argv [++ i ]; 716else if (a == "--inflight" && i + 1 < argc )inflight = (uint32_t ) std::atoi (argv [++ i ]); 717else if (a == "--direct-first" )direct_first = true; 718else if (a == "--direct-only" )direct_only = true; 719else if (a == "--sync" )sync_submit = true; 720else { std::fprintf (stderr ,"usage: ple_reader_test --selftest [--dir D] | --gguf SHARD2 [--rows N] [--tokens F]\n" );return 2 ; } 721 } 722if (self ) { 723// ng::ROW_BYTES (90, IQ4_NL, production default) and 110 (#296, OrcaRouter's Q5_0 PLE rows) through the 724// same generic row_bytes path -- see the comment on selftest(). 725all_formats_round_trip (dir );// every format of k::ple_formats(), both readers, vs its dequantizer 726if (g_fail != 0 )return 1 ; 727const int r90 = selftest (dir , ng::ROW_BYTES ); 728const int r110 = selftest (dir ,110 ); 729return r90 != 0 ?r90 :r110 ; 730 } 731if (!make_path .empty ()) {// a big synthetic table, for timing --ple-io ram's fault-in 732for (int i = 0 ;i < k::ple_format_count ();++ i ) { 733const k::PleFormatInfo & f = k::ple_formats ()[i ]; 734if (make_fmt != f .name )continue ; 735const std::string tmp = write_format_table (std::filesystem::path (make_path ).parent_path ().string (),f , (uint32_t )rows ); 736if (tmp .empty ())return 1 ; 737 std::filesystem::rename (tmp ,make_path ); 738 std::printf ("wrote %s: %s, %d rows, %.2f GiB\n" ,make_path .c_str (),f .name ,rows , 739 (double )rows * f .row_bytes / (1024.0 * 1024.0 * 1024.0 )); 740return 0 ; 741 } 742 std::fprintf (stderr ,"unknown format %s\n" ,make_fmt .c_str ()); 743return 2 ; 744 } 745if (!ram_path .empty ()) {// open mapped and locked (--ple-io ram): the seconds it takes 746 k::PleTable t ; 747 k::PleIoOptions io ; 748io .mode = k::PleIo ::Mmap ; 749io .lock = true; 750 std::string err ; 751const double t0 = now_us (); 752const bool ok = t .open (ram_path ,err ,io ); 753 std::printf ("ram open: %s, format %s, locked %d, %.2f s\n" ,ok ?"ok" :err .c_str (),ok ?t .format () :"-" ,ok && t .locked (), 754 (now_us ()- t0 ) /1e6 ); 755return ok ?0 :1 ; 756 } 757if (!gguf .empty ())return real (gguf ,rows ,tokens ,inflight ,direct_first ,direct_only ,sync_submit ); 758 std::fprintf (stderr ,"nothing to do\n" ); 759return 2 ; 760}