okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
832b2e4f3
main
1// src/kernels/ple_parity.cpp - P2.S4's test: the n-gram hash, the IQ4_NL table read, and the PLE block. 2// 3// THREE PARTS, THREE DIFFERENT ORACLES, and none of them is this project's own code: 4// 5// A. THE HASH against `ref/ngram.py::ngram_rows`, via `ple_oracle_vectors.inc` (generated). The properties 6// are asserted OBSERVABLE first - XOR vs sum, `%` vs `&`, the cut DIRECTION, the NULL sentinel - because 7// each rival reading produces a perfectly valid index in range. 8// B. THE TABLE against numpy reading the ORIGINAL GGUF at the offset the validated `gguf_reader` reports. 9// C. THE BLOCK against ggml's own graph, captured in `bench/micro/ple_in.bin` / `ple_out.bin` by 10// `ple_layer_xcheck.cpp`. That file records EVERY intermediate (key, value, gate, gated, normalized, 11// conv_out, result), so a mismatch can be attributed to a stage instead of guessed at - and the weights 12// in it were checked to be the artifact's real ones before this test was written. 13#include "strata/kernels/ple.hpp" 14#include "strata/kernels/ngram.hpp" 15#include "strata/kernels/f16_bits.hpp" 16#include "strata/kernels/native_mmvq.hpp" 17#include "ple_oracle_vectors.inc" 18 19#include <cuda_runtime.h> 20 21#include <algorithm> 22#include <cmath> 23#include <cstdio> 24#include <cstdlib> 25#include <cstring> 26#include <string> 27#include <stdexcept> 28#include <vector> 29 30namespace k= strata::kernels; 31namespace o= strata::kernels::ple_oracle; 32 33namespace { 34 35void ck (cudaError_t e ,const char * what ) { 36if (e != cudaSuccess ) { 37 std::fprintf (stderr ,"%s: %s\n" ,what ,cudaGetErrorString (e )); 38 std::exit (1 ); 39 } 40} 41 42/// TOLERANCE CHECKS MUST BE NaN-SAFE, and `x <= t` is not. 43/// 44/// `x <= t` AND `x > t` are BOTH false for NaN, so a check written either way can silently pass - round 197 45/// found `shared_expert_parity` printing a perfect score for an entirely-NaN fixture because the accumulator 46/// was `if (rel > worst) worst = rel;` and NaN is never greater. Every comparison in this file goes through 47/// `le`/`gt`, which require the value to be FINITE first, and every compared pair is counted for non-finite 48/// entries and the count printed. A NaN fixture is then a loud failure rather than a green line. 49bool le (double x ,double t ) {return std::isfinite (x )&& x <=t ; } 50bool gt (double x ,double t ) {return std::isfinite (x )&& x > t ; } 51 52/// How many entries of `a` are not finite. Printed next to every comparison. 53long long nonfinite (const float * a ,size_t n ) { 54long long k = 0 ; 55for (size_t i = 0 ;i < n ;++ i ) 56if (!std::isfinite (a [i ]))++ k ; 57return k ; 58} 59 60/// Normalised L1 with the reference magnitude returned. For the STAGE comparisons a plain |ref| denominator 61/// is right: these are dense vectors of O(1) values with no cancellation between them. 62/// 63/// Returns NaN if EITHER side has a non-finite entry, so a caller that forgets `le`/`gt` still cannot read a 64/// finite-looking number out of a broken fixture. 65double rel_l1 (const float * a ,const float * b ,size_t n ,double * mag_out = nullptr , 66long long * nf_out = nullptr ) { 67double d = 0 ,m = 0 ; 68long long nf = 0 ; 69for (size_t i = 0 ;i < n ;++ i ) { 70if (!std::isfinite (a [i ])|| !std::isfinite (b [i ])) {++ nf ;continue ; } 71d += std::fabs ((double )a [i ]- (double )b [i ]); 72m += std::fabs ((double )a [i ]); 73 } 74if (mag_out )* mag_out = m / (double ) (n ?n :1 ); 75if (nf_out )* nf_out = nf ; 76if (nf )return std::nan ("" ); 77return d / (m > 1e-30 ?m :1e-30 ); 78} 79 80/// The file's size, WITHOUT reading it. 81/// 82/// The first version of this test called `read_file(gguf)` - which reads the WHOLE file into a vector - three 83/// times, on a 28.8 GB GGUF. That is 27 GB of RSS, three full passes over the file, and a 132-second ctest 84/// entry in a suite where every other test is under a second. A test that slow stops being run, which is how 85/// a gate stops being a gate. Everything below now reads only the bytes it actually compares. 86long long file_size (const char * path ) { 87 std::FILE * f = std::fopen (path ,"rb" ); 88if (!f )return -1 ; 89#if defined(_MSC_VER ) 90_fseeki64 (f ,0 ,SEEK_END ); 91const long long n = _ftelli64 (f ); 92#else 93 std::fseek (f ,0 ,SEEK_END ); 94const long long n = std::ftell (f ); 95#endif 96 std::fclose (f ); 97return n ; 98} 99 100/// `n` bytes at `off`, or an empty vector. 101std::vector < uint8_t > read_at (const char * path ,long long off ,size_t n ) { 102 std::vector < uint8_t > v (n ); 103 std::FILE * f = std::fopen (path ,"rb" ); 104if (!f )return {}; 105#if defined(_MSC_VER ) 106if (_fseeki64 (f ,off ,SEEK_SET )!= 0 ) { std::fclose (f );return {}; } 107#else 108if (std::fseek (f , (long )off ,SEEK_SET )!= 0 ) { std::fclose (f );return {}; } 109#endif 110const size_t got = std::fread (v .data (),1 ,n ,f ); 111 std::fclose (f ); 112if (got != n )return {}; 113return v ; 114} 115 116/// Only used for the pack, which is 5.4 GB rather than 28.8 GB - and even then the caller says which region. 117std::vector < uint8_t > read_path (const char * path ) { 118const long long n = file_size (path ); 119if (n <=0 )return {}; 120return read_at (path ,0 , (size_t )n ); 121} 122 123/// Dequantize one IQ4_NL row with an INTERLEAVED nibble order, to show the correct split-half order is 124/// observable. Deliberately shares nothing with the kernel's decoder. 125void deq_interleaved (const uint8_t * row ,float * out160 ) { 126for (int b = 0 ;b < k::PLE_HEAD_DIM /32 ;++ b ) { 127const uint8_t * blk = row + (size_t )b * 18 ; 128uint16_t db ; 129 std::memcpy (& db ,blk ,2 ); 130const float d = k::f32_from_f16 (db ); 131for (int j = 0 ;j < 16 ;++ j ) { 132out160 [b * 32 + 2 * j ]= d * (float ) k::iq4nl_code (blk [2 + j ]& 0x0F ); 133out160 [b * 32 + 2 * j + 1 ]= d * (float ) k::iq4nl_code (blk [2 + j ] >>4 ); 134 } 135 } 136} 137 138struct PleCapture { 139int n_embd = 0 ,hc = 0 ,nt = 0 ,kern = 0 ,dil = 0 ; 140float eps = 0.0f ; 141 std::vector < float > emb ,hidden ,w_key ,w_value ,w_nk ,w_nq ,w_nc ,w_conv ,hist ; 142// oracle outputs 143 std::vector < float > key ,value ,gate ,gated ,normalized ,conv_out ,result ; 144}; 145 146bool load_capture (const char * in_path ,const char * out_path ,PleCapture & c ) { 147 std::FILE * fi = std::fopen (in_path ,"rb" ); 148if (!fi )return false; 149int32_t h [5 ]= {0 }; 150if (std::fread (h ,4 ,5 ,fi )!= 5 ) { std::fclose (fi );return false; } 151c .n_embd = h [0 ];c .hc = h [1 ];c .nt = h [2 ];c .kern = h [3 ];c .dil = h [4 ]; 152if (std::fread (& c .eps ,4 ,1 ,fi )!= 1 ) { std::fclose (fi );return false; } 153// Validate before deriving sizes or allocating. This bounded diagnostic 154// format is for this model's geometry and at most 64 captured tokens. 155if (c .n_embd != k::NG_N_EMBD || c .hc != k::NG_HC || c .nt <=0 || c .nt > 64 || 156c .kern != k::PLE_CONV_KERNEL || c .dil != k::NGRAM_SIZE || c .eps != k::NG_RMS_EPS ) { 157 std::fclose (fi );return false; 158 } 159const long long nd = c .n_embd ,hcd = (long long )c .hc * c .n_embd ,nt = c .nt , 160hist = (long long ) (c .kern - 1 )* c .dil ; 161const long long in_bytes = 24 + 4 * (nt * nd + nt * hcd + hcd * nd + nd * nd + 1623 * hcd + hcd * c .kern + hist * hcd ); 163const long long out_bytes = 12 + 4 * nt * (5 * hcd + nd + c .hc ); 164if (file_size (in_path )!= in_bytes || file_size (out_path )!= out_bytes ) { 165 std::fclose (fi );return false; 166 } 167auto rd = [](std::FILE * file , std::vector < float >& v ,long long n ) { 168v .resize ((size_t )n ); 169return n == 0 || std::fread (v .data (),4 , (size_t )n ,file )== (size_t )n ; 170 }; 171bool ok = rd (fi ,c .emb ,nt * nd )&& rd (fi ,c .hidden ,nt * hcd )&& rd (fi ,c .w_key ,hcd * nd )&& 172rd (fi ,c .w_value ,nd * nd )&& rd (fi ,c .w_nk ,hcd )&& rd (fi ,c .w_nq ,hcd )&& rd (fi ,c .w_nc ,hcd )&& 173rd (fi ,c .w_conv ,hcd * c .kern )&& rd (fi ,c .hist ,hist * hcd ); 174 std::fclose (fi ); 175if (!ok )return false; 176 177 std::FILE * fo = std::fopen (out_path ,"rb" ); 178if (!fo )return false; 179int32_t oh [3 ]= {0 }; 180if (std::fread (oh ,4 ,3 ,fo )!= 3 ) { std::fclose (fo );return false; } 181if (oh [0 ]!= c .n_embd || oh [1 ]!= hcd || oh [2 ]!= c .nt ) { std::fclose (fo );return false; } 182ok = rd (fo ,c .key ,nt * hcd )&& rd (fo ,c .value ,nt * nd )&& rd (fo ,c .gate ,nt * c .hc )&& rd (fo ,c .gated ,nt * hcd )&& 183rd (fo ,c .normalized ,nt * hcd )&& rd (fo ,c .conv_out ,nt * hcd )&& rd (fo ,c .result ,nt * hcd ); 184 std::fclose (fo ); 185return ok ; 186} 187 188int history_advance_regression () { 189const size_t channels = (size_t ) k::NG_HC_DIM ,rows = (size_t ) k::NG_HIST ,guard = 16 ; 190const size_t count = channels * rows ; 191 std::vector < float > expected (count ),normalized (channels ),actual (count ); 192for (size_t c = 0 ;c < channels ;++ c ) 193for (size_t r = 0 ;r < rows ;++ r )expected [c * rows + r ]= - float (c * 16 + r + 1 ); 194float * history_storage = nullptr ,* norm_storage = nullptr ; 195ck (cudaMalloc (& history_storage , (count + 2 * guard )* sizeof (float )),"history regression allocation" ); 196ck (cudaMalloc (& norm_storage , (channels + 2 * guard )* sizeof (float )),"history norm allocation" ); 197ck (cudaMemset (history_storage ,0xa5 , (count + 2 * guard )* sizeof (float )),"history guard init" ); 198ck (cudaMemset (norm_storage ,0xa5 , (channels + 2 * guard )* sizeof (float )),"history norm guard init" ); 199float * history = history_storage + guard ; 200float * norm = norm_storage + guard ; 201ck (cudaMemcpy (history ,expected .data (),count * sizeof (float ),cudaMemcpyHostToDevice ),"history initial values" ); 202// the guard memsets and this upload run on the legacy stream, which the non-blocking `stream` does not wait for 203ck (cudaDeviceSynchronize (),"history setup" ); 204cudaStream_t stream ; 205cudaGraph_t graph ; 206cudaGraphExec_t executable ; 207ck (cudaStreamCreateWithFlags (& stream ,cudaStreamNonBlocking ),"history regression stream" ); 208ck (cudaStreamBeginCapture (stream ,cudaStreamCaptureModeThreadLocal ),"history regression capture" ); 209 k::ple_history_advance (history ,norm ,stream ); 210ck (cudaStreamEndCapture (stream ,& graph ),"history regression capture end" ); 211ck (cudaGraphInstantiate (& executable ,graph ,nullptr ,nullptr ,0 ),"history regression instantiate" ); 212int bad = 0 ; 213for (int token = 0 ;token < 12 ;++ token ) { 214for (size_t c = 0 ;c < channels ;++ c ) { 215normalized [c ]= float ((token + 1 )* 1000000 + c );// distinct exactly represented integers 216for (size_t r = 0 ;r + 1 < rows ;++ r )expected [c * rows + r ]= expected [c * rows + r + 1 ]; 217expected [c * rows + rows - 1 ]= normalized [c ]; 218 } 219ck (cudaMemcpyAsync (norm ,normalized .data (),channels * sizeof (float ),cudaMemcpyHostToDevice ,stream ),"history new normalized row" ); 220ck (cudaGraphLaunch (executable ,stream ),"history captured advance" ); 221ck (cudaStreamSynchronize (stream ),"history captured advance sync" ); 222ck (cudaMemcpy (actual .data (),history ,count * sizeof (float ),cudaMemcpyDeviceToHost ),"history readback" ); 223if (std::memcmp (actual .data (),expected .data (),count * sizeof (float ))!= 0 ) { 224 std::printf (" history advance mismatch after token %d\n" ,token ); 225++ bad ; 226 } 227 } 228bool overlap_refused = false,null_refused = false; 229try { k::ple_history_advance (history ,history + 1 ,stream ); } 230catch (const std::invalid_argument & ) {overlap_refused = true; } 231try { k::ple_history_advance (history ,nullptr ,stream ); } 232catch (const std::invalid_argument & ) {null_refused = true; } 233if (!overlap_refused || !null_refused )++ bad ; 234auto guard_ok = [& ](float * storage ,size_t payload ) { 235uint8_t before [64 ],after [64 ]; 236ck (cudaMemcpy (before ,storage ,sizeof (before ),cudaMemcpyDeviceToHost ),"history prefix guard" ); 237ck (cudaMemcpy (after ,storage + guard + payload ,sizeof (after ),cudaMemcpyDeviceToHost ),"history suffix guard" ); 238return std::all_of (before ,before + 64 , [](uint8_t b ) {return b == 0xa5 ; })&& 239 std::all_of (after ,after + 64 , [](uint8_t b ) {return b == 0xa5 ; }); 240 }; 241if (!guard_ok (history_storage ,count )|| !guard_ok (norm_storage ,channels ))++ bad ; 242 std::printf (" PLE history 12 captured steps, row-fastest state and guards: %s\n" ,bad == 0 ?"pass" :"FAIL" ); 243ck (cudaGraphExecDestroy (executable ),"history graph exec destroy" ); 244ck (cudaGraphDestroy (graph ),"history graph destroy" ); 245ck (cudaStreamDestroy (stream ),"history stream destroy" ); 246cudaFree (history_storage );cudaFree (norm_storage ); 247return bad ; 248} 249 250}// namespace 251 252int main (int argc ,char ** argv ) { 253bool selftest = false; 254bool check_fixtures = false; 255 std::string pack = "pack/full" ; 256// --gguf, else $STRATA_PLE_GGUF, else the development layout (run from the engine root) 257 std::string gguf = std::getenv ("STRATA_PLE_GGUF" ) ? std::getenv ("STRATA_PLE_GGUF" ) 258 :"../../Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" ; 259 std::string in_bin = "bench/micro/ple_in.bin" ,out_bin = "bench/micro/ple_out.bin" ; 260for (int i = 1 ;i < argc ;++ i ) { 261const std::string a = argv [i ]; 262if (a == "--selftest" )selftest = true; 263else if (a == "--check-fixtures" )check_fixtures = true; 264else if (a == "--pack" && i + 1 < argc )pack = argv [++ i ]; 265else if (a == "--gguf" && i + 1 < argc )gguf = argv [++ i ]; 266else if (a == "--in" && i + 1 < argc )in_bin = argv [++ i ]; 267else if (a == "--out" && i + 1 < argc )out_bin = argv [++ i ]; 268else { std::fprintf (stderr ,"usage: ple_parity [--selftest] [--check-fixtures] [--pack D] [--gguf F] [--in F] [--out F]\n" ); 269return 2 ; } 270 } 271if (selftest && check_fixtures ) { 272 std::fprintf (stderr ,"ple_parity: --check-fixtures is CPU-only; use it separately from --selftest\n" ); 273return 2 ; 274 } 275// Required self-test fixtures are checked before the first CUDA call, so 276// missing files cannot become an apparent pass or a misleading GPU error. 277 k::PleTable table ; 278 std::string err ; 279PleCapture cap ; 280bool preflight_done = false; 281if (selftest || check_fixtures ) { 282if (!table .open (gguf ,err )|| table .rows ()!= o::kTableRows || 283file_size (gguf .c_str ())!= (long long ) o::kTableDataStart + (long long ) o::kTableRows * k::PLE_ROW_BYTES ) { 284 std::fprintf (stderr ,"ple_parity: required PLE table is missing or incompatible: %s (%s)\n" ,gguf .c_str (),err .c_str ()); 285return 2 ; 286 } 287const uint64_t pack_needed = std::max ({o::kKeyCodesOffset + o::kKeyCodesBytes , 288 o::kKeyScalesOffset + o::kKeyScalesBytes , o::kValueOffset + o::kValueBytes }); 289const long long pack_size = file_size ((pack + "/dense.bin" ).c_str ()); 290if (pack_size < 0 || (uint64_t )pack_size < pack_needed ) { 291 std::fprintf (stderr ,"ple_parity: required dense pack is missing or truncated: %s/dense.bin\n" ,pack .c_str ()); 292return 2 ; 293 } 294if (!load_capture (in_bin .c_str (),out_bin .c_str (),cap )) { 295 std::fprintf (stderr ,"ple_parity: required block fixtures are missing, truncated or incompatible: %s / %s\n" ,in_bin .c_str (),out_bin .c_str ()); 296return 2 ; 297 } 298preflight_done = true; 299if (check_fixtures ) { 300 std::puts ("PASS required PLE fixture structure on CPU; no GPU numerical checks were run" ); 301return 0 ; 302 } 303if (!k::ple_block_available ()) { 304 std::fprintf (stderr ,"ple_parity: --selftest requires a CUDA device for block checks\n" ); 305return 2 ; 306 } 307 } 308int bad = history_advance_regression (); 309const k::PleConsts C = k::ple_artifact_consts (); 310 311// ============================ A. THE HASH ============================ 312 std::printf ("A. the n-gram hash, against ref/ngram.py with the artifact's own constants\n" ); 313 314// ---- the constants must be internally consistent BEFORE they are used: `head_offsets` is its own array 315// in the metadata, so deriving it from `vocab_sizes` would hide a disagreement between them. 316 { 317uint64_t run = 0 ; 318bool ok = true; 319for (int h = 0 ;h < k::PLE_N_HEADS ;++ h ) { 320if (C .offset [h ]!= run )ok = false; 321run += C .vocab [h ]; 322 } 323const uint64_t total = run ; 324const bool fits = total <= k::PLE_TABLE_ROWS ; 325 std::printf (" %-46s %s (sum %llu <= %llu rows; %llu spare)\n" , 326"head_offsets == the running sum of vocab_sizes" ,ok && fits ?"yes" :"*** NO ***" , 327 (unsigned long long )total , (unsigned long long ) k::PLE_TABLE_ROWS , 328 (unsigned long long ) (k::PLE_TABLE_ROWS - total )); 329if (!ok || !fits )++ bad ; 330 } 331 332for (int ci = 0 ;ci < o::kHashCaseCount ;++ ci ) { 333const o::HashCase & hc = o::kHashCases [ci ]; 334 std::vector < uint32_t > got ((size_t )hc .n_tokens * k::PLE_N_HEADS ); 335 k::ngram_rows (hc .tokens ,hc .prev ,hc .n_tokens ,C ,got .data ()); 336long long diff = 0 ; 337for (size_t i = 0 ;i < got .size ();++ i ) 338if (got [i ]!= hc .rows [i ])++ diff ; 339 std::printf (" %-46s %s (%lld of %zu differ)\n" ,hc .name ,diff ?"*** WRONG ***" :"matches" ,diff , 340got .size ()); 341if (diff ) { 342for (int t = 0 ;t < hc .n_tokens && diff ;++ t ) { 343for (int h = 0 ;h < k::PLE_N_HEADS ;++ h ) { 344const uint32_t g = got [(size_t )t * 16 + h ],w = hc .rows [(size_t )t * 16 + h ]; 345if (g != w ) { 346 std::printf (" first: t=%d h=%d got %u want %u\n" ,t ,h ,g ,w ); 347t = hc .n_tokens ; 348break ; 349 } 350 } 351 } 352++ bad ; 353 } 354 } 355 356// ---- the rival readings, each computed and required to DIFFER from the oracle ------------------- 357// 358// Every one of these produces a 16-element vector of valid indices. That is the whole reason the hash is 359// transcribed property by property: no range check, no shape check and no summing test can see any of 360// them, only an oracle can - and only a DELIBERATELY-WRONG fixture can show that the oracle comparison 361// has the power to catch them. 362 { 363const o::HashCase & hc = o::kHashCases [0 ];// the window-direction case, 4 tokens 364const int T = hc .n_tokens ,np = k::NGRAM_SIZE - 1 ,n_heads = k::PLE_N_HEADS ; 365 std::vector < uint32_t > xor_v ((size_t )T * n_heads ),sum_v ((size_t )T * n_heads ), 366mask_v ((size_t )T * n_heads ),back_v ((size_t )T * n_heads ),zero_v ((size_t )T * n_heads ); 367for (int i = 0 ;i < T ;++ i ) { 368int64_t ctx [k::NGRAM_SIZE ]; 369ctx [0 ]= hc .tokens [i ]; 370for (int s = 1 ;s < k::NGRAM_SIZE ;++ s )ctx [s ]= hc .prev [i * np + (np - s )]; 371for (int n = 2 ;n <= k::NGRAM_SIZE ;++ n ) { 372// (1) SUM instead of XOR 373uint64_t sum = 0 ; 374for (int j = 0 ;j < n ;++ j )sum += (uint64_t )ctx [j ]* C .mult [j ]; 375// (2) mask instead of modulo: the vocab sizes are NOT powers of two 376uint64_t xr = k::ngram_mixed (ctx ,C .mult ,n ); 377// (4) token 0 treated as "missing" the way -1 is 378int64_t ctx0 [k::NGRAM_SIZE ]; 379for (int j = 0 ;j < k::NGRAM_SIZE ;++ j ) 380ctx0 [j ]= (ctx [j ]== k::TOKEN_NULL || ctx [j ]== 0 ) ? k::PLE_EOS_TOKEN_ID :ctx [j ]; 381uint64_t xr0 = k::ngram_mixed (ctx0 ,C .mult ,n ); 382// (3) the window read NEWEST-first instead of oldest-first: prev index (s-1) 383int64_t ctxb [k::NGRAM_SIZE ]; 384ctxb [0 ]= hc .tokens [i ]; 385for (int s = 1 ;s < k::NGRAM_SIZE ;++ s )ctxb [s ]= hc .prev [i * np + (s - 1 )]; 386uint64_t xrb = k::ngram_mixed (ctxb ,C .mult ,n ); 387const int base = (n - 2 )* k::HEADS_PER_NGRAM ; 388for (int g = 0 ;g < k::HEADS_PER_NGRAM ;++ g ) { 389const int h = base + g ; 390xor_v [(size_t )i * n_heads + h ]= (uint32_t ) (xr %C .vocab [h ]+ C .offset [h ]); 391sum_v [(size_t )i * n_heads + h ]= (uint32_t ) (sum %C .vocab [h ]+ C .offset [h ]); 392mask_v [(size_t )i * n_heads + h ]= 393 (uint32_t ) ((xr & (C .vocab [h ]- 1 ))+ C .offset [h ]); 394back_v [(size_t )i * n_heads + h ]= (uint32_t ) (xrb %C .vocab [h ]+ C .offset [h ]); 395zero_v [(size_t )i * n_heads + h ]= (uint32_t ) (xr0 %C .vocab [h ]+ C .offset [h ]); 396 } 397 } 398 } 399struct Rival {const char * name ;const std::vector < uint32_t >* v ; }; 400const Rival rivals []= {{"XOR vs SUM" ,& sum_v }, 401 {"% vs & (vocab sizes are not powers of two)" ,& mask_v }, 402 {"window read newest-first, not oldest-first" ,& back_v }, 403 {"token id 0 treated as the NULL sentinel" ,& zero_v }}; 404for (const Rival & r :rivals ) { 405// A rival is observable if it disagrees with the ORACLE, which is what the test above compares. 406long long d = 0 ; 407for (size_t i = 0 ;i < r .v -> size ();++ i ) 408if ((* r .v )[i ]!= hc .rows [i ])++ d ; 409const bool visible = d > 0 ; 410 std::printf (" %-46s %s (%lld of %zu rows differ from the oracle)\n" ,r .name , 411visible ?"yes" :"*** NO - the fixture cannot see this ***" ,d ,r .v -> size ()); 412if (!visible )++ bad ; 413 } 414 (void )xor_v ; 415 } 416 417// ---- the EOS cut DIRECTION, which needs a case where the two directions disagree ---------------- 418 { 419const o::HashCase & hc = o::kHashCases [1 ];// [[N,N],[7,EOS],[EOS,7]] 420const int T = hc .n_tokens ,np = k::NGRAM_SIZE - 1 ,n_heads = k::PLE_N_HEADS ; 421 std::vector < uint32_t > fwd ((size_t )T * n_heads ),bwd ((size_t )T * n_heads ); 422for (int i = 0 ;i < T ;++ i ) { 423int64_t f [k::NGRAM_SIZE ],b [k::NGRAM_SIZE ]; 424f [0 ]= b [0 ]= hc .tokens [i ]; 425bool cf = false,cb = false; 426for (int s = 1 ;s < k::NGRAM_SIZE ;++ s ) { 427const int32_t fv = hc .prev [i * np + (np - s )]; 428cf = cf || fv < 0 || fv == k::PLE_EOS_TOKEN_ID ; 429f [s ]= cf ? k::PLE_EOS_TOKEN_ID :fv ; 430// the BACKWARD reading: only the position that IS EOS becomes EOS 431const int32_t bv = hc .prev [i * np + (np - s )]; 432b [s ]= (bv < 0 || bv == k::PLE_EOS_TOKEN_ID ) ? k::PLE_EOS_TOKEN_ID :bv ; 433 (void )cb ; 434 } 435for (int n = 2 ;n <= k::NGRAM_SIZE ;++ n ) { 436const uint64_t mf = k::ngram_mixed (f ,C .mult ,n ),mb = k::ngram_mixed (b ,C .mult ,n ); 437const int base = (n - 2 )* k::HEADS_PER_NGRAM ; 438for (int g = 0 ;g < k::HEADS_PER_NGRAM ;++ g ) { 439const int h = base + g ; 440fwd [(size_t )i * n_heads + h ]= (uint32_t ) (mf %C .vocab [h ]+ C .offset [h ]); 441bwd [(size_t )i * n_heads + h ]= (uint32_t ) (mb %C .vocab [h ]+ C .offset [h ]); 442 } 443 } 444 } 445long long d = 0 ; 446for (size_t i = 0 ;i < fwd .size ();++ i ) 447if (fwd [i ]!= bwd [i ])++ d ; 448 std::printf (" %-46s %s (%lld of %zu rows differ)\n" , 449"cut propagates FORWARD vs only at the EOS position" , 450d > 0 ?"yes" :"*** NO ***" ,d ,fwd .size ()); 451if (!d )++ bad ; 452 } 453 454// ============================ B. THE TABLE ============================ 455 std::printf ("\nB. the IQ4_NL table, against numpy reading the original GGUF\n" ); 456if (!preflight_done && !table .open (gguf ,err )) { 457 std::printf (" cannot open the PLE table: %s\n" ,err .c_str ()); 458 std::printf ("\nple_parity: %d failures, TABLE AND BLOCK SKIPPED; partial diagnostic only\n" ,bad ); 459return selftest || bad ?1 :0 ; 460 } 461 std::printf (" %-46s %llu (expected %llu)\n" ,"rows" , (unsigned long long )table .rows (), 462 (unsigned long long ) o::kTableRows ); 463if (table .rows ()!= o::kTableRows )++ bad ; 464 465// The size identity is what makes the data offset FALSIFIABLE: the tensor must exactly fill the file from 466// data_start. Deriving the row count from the file size instead gives 320001538 rows and data_start 12, 467// which is self-consistent and wrong. 468 { 469const long long sz = file_size (gguf .c_str ()); 470const long long need = (long long ) o::kTableDataStart + (long long )table .rows ()* k::PLE_ROW_BYTES ; 471const bool ok = sz == need ; 472 std::printf (" %-46s %s (%lld vs %lld; data_start %llu)\n" , 473"data_start + rows*90 == file size" ,ok ?"yes" :"*** NO ***" ,sz ,need , 474 (unsigned long long ) o::kTableDataStart ); 475if (!ok )++ bad ; 476 } 477 478// Read the raw bytes through the mapped table by comparing against numpy's decode of the SAME offsets. 479// 90 BYTES AT A TIME, not the whole file - see `file_size`'s note. 480 { 481int probe_bad = 0 ; 482for (int p = 0 ;p < o::kProbeCount ;++ p ) { 483const uint32_t row = o::kProbeRows [p ]; 484 std::vector < float > got (k::PLE_HEAD_DIM ); 485table .read_row (row ,got .data ()); 486const std::vector < uint8_t > raw = 487read_at (gguf .c_str (), (long long ) o::kTableDataStart + (long long )row * k::PLE_ROW_BYTES , 488 (size_t ) k::PLE_ROW_BYTES ); 489if (raw .size ()!= (size_t ) k::PLE_ROW_BYTES ) { std::printf (" short read at row %u\n" ,row );++ probe_bad ;continue ; } 490 std::vector < float > ref (k::PLE_HEAD_DIM ); 491 k::iq4nl_dequant_row (raw .data (),ref .data ()); 492// the sampled values from the generator (numpy), which is the oracle proper. 493// NOT `fmax`: it DISCARDS NaN, so a NaN element would leave these at 0 and the row would report 494// a perfect match. A plain comparison propagates the NaN into `ok`. 495double head = 0 ,tail = 0 ,sum = 0 ; 496for (int i = 0 ;i < 8 ;++ i ) { 497const double dh = std::fabs ((double )got [i ]- (double ) o::kProbeHead [p ][i ]); 498const double dt = std::fabs ((double )got [k::PLE_HEAD_DIM - 8 + i ]- 499 (double ) o::kProbeTail [p ][i ]); 500if (p == 0 && i == 0 ) {head = dh ;tail = dt ; } 501else {head = (dh > head ) ?dh :head ;tail = (dt > tail ) ?dt :tail ; } 502 } 503for (int i = 0 ;i < k::PLE_HEAD_DIM ;++ i )sum += std::fabs ((double )got [i ]); 504const long long nfg = nonfinite (got .data (), k::PLE_HEAD_DIM ); 505const bool ok = le (head ,0.0 )&& le (tail ,0.0 )&& le (std::fabs (sum - o::kProbeSum [p ]),1e-9 )&& 506nfg == 0 ; 507 std::printf (" %-46s %s (row %u: head %.3e tail %.3e sum d %.3e, non-finite %lld)\n" , 508p == 0 ?"row matches numpy's decode of the same bytes" :" (same, another row)" , 509ok ?"yes" :"*** NO ***" ,row ,head ,tail , std::fabs (sum - o::kProbeSum [p ]),nfg ); 510if (!ok )++ probe_bad ; 511// and the two decoders must agree with each other bit for bit 512for (int i = 0 ;i < k::PLE_HEAD_DIM ;++ i ) 513if (got [i ]!= ref [i ]) { std::printf (" byte-level decode differs at %d\n" ,i );++ probe_bad ;break ; } 514 } 515bad += probe_bad ; 516 } 517 518// ---- the split-half nibble order must be observable --------------------------------------------- 519 { 520const std::vector < uint8_t > raw = 521read_at (gguf .c_str (), (long long ) o::kTableDataStart + 522 (long long ) o::kProbeRows [0 ]* k::PLE_ROW_BYTES , 523 (size_t ) k::PLE_ROW_BYTES ); 524 std::vector < float > want (k::PLE_HEAD_DIM ),inter (k::PLE_HEAD_DIM ); 525 k::iq4nl_dequant_row (raw .data (),want .data ()); 526deq_interleaved (raw .data (),inter .data ()); 527const double rel = rel_l1 (want .data (),inter .data (), k::PLE_HEAD_DIM ); 528const bool visible = gt (rel ,0.05 ); 529 std::printf (" %-46s %s (%.2f%% apart; generator says %.4f)\n" , 530"split-half vs INTERLEAVED nibbles observable" , 531visible ?"yes" :"*** NO ***" ,rel * 100 , (double ) o::kInterleavedSeparation ); 532if (!visible )++ bad ; 533 } 534 535// ---- and reading at file offset 0 instead of data_start must be observable ---------------------- 536 { 537const std::vector < uint8_t > at_ds = read_at (gguf .c_str (), (long long ) o::kTableDataStart , 538 (size_t ) k::PLE_ROW_BYTES ); 539const std::vector < uint8_t > at_0 = read_at (gguf .c_str (),0 , (size_t ) k::PLE_ROW_BYTES ); 540 std::vector < float > ok_v (k::PLE_HEAD_DIM ),at0 (k::PLE_HEAD_DIM ); 541 k::iq4nl_dequant_row (at_ds .data (),ok_v .data ()); 542 k::iq4nl_dequant_row (at_0 .data (),at0 .data ()); 543const double rel = rel_l1 (ok_v .data (),at0 .data (), k::PLE_HEAD_DIM ); 544const bool visible = gt (rel ,0.05 ); 545 std::printf (" %-46s %s (%.2f%% apart)\n" , 546"data_start 192 vs file offset 0 observable" ,visible ?"yes" :"*** NO ***" ,rel * 100 ); 547if (!visible )++ bad ; 548 } 549 550// ---- head-slowest flatten ---------------------------------------------------------------------- 551 { 552const uint32_t rows16 [16 ]= {0 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 ,12 ,13 ,14 ,15 }; 553 std::vector < float > emb (k::NG_N_EMBD ),one (k::PLE_HEAD_DIM ); 554table .gather (rows16 ,emb .data ()); 555bool blockwise = true; 556for (int h = 0 ;h < k::PLE_N_HEADS && blockwise ;++ h ) { 557table .read_row ((uint32_t )h ,one .data ()); 558for (int d = 0 ;d < k::PLE_HEAD_DIM ;++ d ) 559if (emb [h * k::PLE_HEAD_DIM + d ]!= one [d ]) {blockwise = false;break ; } 560 } 561// the rival: head-fastest, element (d,h) at d*16+h - a real transpose, not a reshape 562 std::vector < float > fast (k::NG_N_EMBD ); 563for (int d = 0 ;d < k::PLE_HEAD_DIM ;++ d ) 564for (int h = 0 ;h < k::PLE_N_HEADS ;++ h )fast [d * k::PLE_N_HEADS + h ]= emb [h * k::PLE_HEAD_DIM + d ]; 565long long diff = 0 ; 566for (int i = 0 ;i < k::NG_N_EMBD ;++ i ) 567if (fast [i ]!= emb [i ])++ diff ; 568 std::printf (" %-46s %s (head h occupies [h*160,(h+1)*160))\n" ,"gather is head-slowest" , 569blockwise ?"yes" :"*** NO ***" ); 570 std::printf (" %-46s %s (%lld of %d elements differ)\n" ,"head-fastest would differ" , 571diff > 0 ?"yes" :"*** NO ***" ,diff , k::NG_N_EMBD ); 572if (!blockwise || !diff )++ bad ; 573 } 574 575// ============================ C. THE BLOCK ============================ 576 std::printf ("\nC. the PLE block, against ggml's own graph (ple_in.bin / ple_out.bin)\n" ); 577if (!preflight_done && !load_capture (in_bin .c_str (),out_bin .c_str (),cap )) { 578 std::printf (" cannot load %s / %s\n" ,in_bin .c_str (),out_bin .c_str ()); 579 std::printf ("\nple_parity: %d failures, BLOCK SKIPPED; partial diagnostic only\n" ,bad ); 580return selftest || bad ?1 :0 ; 581 } 582 std::printf (" capture: n_embd %d, hc %d, nt %d, kern %d, dil %d, eps %g\n" ,cap .n_embd ,cap .hc ,cap .nt , 583cap .kern ,cap .dil , (double )cap .eps ); 584if (cap .n_embd != k::NG_N_EMBD || cap .hc != k::NG_HC || cap .kern != k::PLE_CONV_KERNEL || 585cap .dil != k::NGRAM_SIZE ) { 586 std::printf (" *** the capture's geometry is not the artifact's ***\n" ); 587return 1 ; 588 } 589 590if (!k::ple_block_available ()) { 591 std::printf (" no CUDA device; the block SKIPPED, not passed.\n" ); 592 std::printf ("\nple_parity: %d failures, BLOCK SKIPPED\n" ,bad ); 593return selftest || bad ?1 :0 ; 594 } 595 596// ---- the two quantized weights, from the PACK, not from the capture. 597// The capture holds `w_key` already dequantized to f32; the kernel needs the CODES AND SCALES, and 598// re-quantizing the f32 would be a different tensor. Reading the pack is right and it was checked: 599// the pack's decode of row 0 reproduces the capture's w_key row 0 exactly (see the round entry). 600// Only the two regions are read, not all 5.4 GB of `dense.bin`. 601 std::vector < uint8_t > key_codes = 602read_at ((pack + "/dense.bin" ).c_str (), (long long ) o::kKeyCodesOffset , (size_t ) o::kKeyCodesBytes ); 603const std::vector < uint8_t > raw_scales = 604read_at ((pack + "/dense.bin" ).c_str (), (long long ) o::kKeyScalesOffset , (size_t ) o::kKeyScalesBytes ); 605const std::vector < uint8_t > raw_value = 606read_at ((pack + "/dense.bin" ).c_str (), (long long ) o::kValueOffset , (size_t ) o::kValueBytes ); 607if (key_codes .empty ()|| raw_scales .empty ()|| raw_value .empty ()) { 608 std::printf (" cannot read the ple_key/ple_value regions from %s/dense.bin\n" ,pack .c_str ()); 609return 2 ; 610 } 611// fp16 -> f32 for the scales, which is what every S-form kernel in this project expects 612const size_t n_scales = raw_scales .size () /2 ; 613 std::vector < float > key_scales (n_scales ); 614for (size_t i = 0 ;i < n_scales ;++ i ) { 615uint16_t h ; 616 std::memcpy (& h ,raw_scales .data ()+ i * 2 ,2 ); 617key_scales [i ]= k::f32_from_f16 (h ); 618 } 619// ple_value is BF16 promoted to 32 bits in the pack; take the high half, which is exact 620 std::vector < uint16_t > value_bf16 (raw_value .size () /4 ); 621for (size_t i = 0 ;i < value_bf16 .size ();++ i ) { 622uint32_t u ; 623 std::memcpy (& u ,raw_value .data ()+ i * 4 ,4 ); 624value_bf16 [i ]= (uint16_t ) (u >>16 ); 625 } 626// ple_conv1d is F16 in the pack; the capture holds it as f32 in ggml order, and the kernel wants F16 627 std::vector < uint16_t > conv1d_f16 (cap .w_conv .size ()); 628for (size_t i = 0 ;i < conv1d_f16 .size ();++ i )conv1d_f16 [i ]= k::f16_from_f32 (cap .w_conv [i ]); 629 630// ---- the check that the two sources describe the SAME weights --------------------------------- 631 { 632// dequantize key row 0 with the canonical rule and compare to the capture's w_key row 0. 633// NOT `fmax`, for the reason above: it discards NaN, so a NaN would leave `worst` at 0 and report a 634// perfect match. 635double worst = 0 ; 636bool first = true; 637long long nf = 0 ; 638for (int d = 0 ;d < k::NG_N_EMBD ;++ d ) { 639const uint8_t byte = key_codes [d /4 ]; 640const int code = (byte >> ((d %4 )* 2 ))& 3 ; 641const float v = (float ) (code + (-1 ))* key_scales [d /64 ]; 642if (!std::isfinite (v )|| !std::isfinite (cap .w_key [d ])) {++ nf ;continue ; } 643const double diff = std::fabs ((double )v - (double )cap .w_key [d ]); 644if (first ) {worst = diff ;first = false; } 645else worst = (diff > worst ) ?diff :worst ; 646 } 647 std::printf (" %-46s %s (worst |d| %.3e, non-finite %lld)\n" , 648"pack ple_key row 0 == the capture's w_key row 0" , 649 (le (worst ,0.0 )&& nf == 0 ) ?"yes" :"*** NO ***" ,worst ,nf ); 650if (!le (worst ,0.0 )|| nf )++ bad ; 651 } 652 653// ---- run the block for both tokens of the capture --------------------------------------------- 654const size_t hcd = (size_t ) k::NG_HC_DIM ,nd = (size_t ) k::NG_N_EMBD ; 655 std::vector < float > dev_key (hcd ),dev_value (nd ),dev_gate (k::NG_HC ),dev_gated (hcd ),dev_norm (hcd ), 656dev_conv (hcd ),dev_res (hcd ); 657float * d_emb = nullptr ,* d_hid = nullptr ,* d_hist = nullptr ,* d_nk = nullptr ,* d_nq = nullptr , 658* d_nc = nullptr ,* d_ck = nullptr ,* d_cv = nullptr ,* d_cn = nullptr ,* d_cr = nullptr ; 659uint8_t * d_kc = nullptr ; 660uint16_t * d_vb = nullptr ,* d_c1 = nullptr ; 661float * d_g = nullptr ,* d_v = nullptr ,* d_gd = nullptr ,* d_nm = nullptr ,* d_co = nullptr ; 662ck (cudaMalloc (& d_emb ,nd * 4 ),"emb" ); 663ck (cudaMalloc (& d_hid ,hcd * 4 ),"hid" ); 664ck (cudaMalloc (& d_hist , (size_t ) k::NG_HIST * hcd * 4 ),"hist" ); 665ck (cudaMalloc (& d_nk ,hcd * 4 ),"nk" ); 666ck (cudaMalloc (& d_nq ,hcd * 4 ),"nq" ); 667ck (cudaMalloc (& d_nc ,hcd * 4 ),"nc" ); 668ck (cudaMalloc (& d_kc ,key_codes .size ()),"kc" ); 669ck (cudaMalloc (& d_vb ,value_bf16 .size ()* 2 ),"vb" ); 670ck (cudaMalloc (& d_c1 ,conv1d_f16 .size ()* 2 ),"c1" ); 671ck (cudaMalloc (& d_g , k::NG_HC * 4 ),"g" ); 672ck (cudaMalloc (& d_v ,nd * 4 ),"v" ); 673ck (cudaMalloc (& d_gd ,hcd * 4 ),"gd" ); 674ck (cudaMalloc (& d_nm ,hcd * 4 ),"nm" ); 675ck (cudaMalloc (& d_co ,hcd * 4 ),"co" ); 676ck (cudaMalloc (& d_ck ,hcd * 4 ),"ck" ); 677ck (cudaMalloc (& d_cv ,nd * 4 ),"cv" ); 678ck (cudaMalloc (& d_cn ,hcd * 4 ),"cn" ); 679ck (cudaMalloc (& d_cr ,hcd * 4 ),"cr" ); 680ck (cudaMemcpy (d_nk ,cap .w_nk .data (),hcd * 4 ,cudaMemcpyHostToDevice ),"cnk" ); 681ck (cudaMemcpy (d_nq ,cap .w_nq .data (),hcd * 4 ,cudaMemcpyHostToDevice ),"cnq" ); 682ck (cudaMemcpy (d_nc ,cap .w_nc .data (),hcd * 4 ,cudaMemcpyHostToDevice ),"cnc" ); 683ck (cudaMemcpy (d_kc ,key_codes .data (),key_codes .size (),cudaMemcpyHostToDevice ),"ckc" ); 684ck (cudaMemcpy (d_vb ,value_bf16 .data (),value_bf16 .size ()* 2 ,cudaMemcpyHostToDevice ),"cvb" ); 685ck (cudaMemcpy (d_c1 ,conv1d_f16 .data (),conv1d_f16 .size ()* 2 ,cudaMemcpyHostToDevice ),"cc1" ); 686 687 k::PleWeights w {}; 688w .key_codes = d_kc ; 689w .key_scales = key_scales .data ();// uploaded per call below so the pointer is a device one 690w .value_bf16 = d_vb ; 691w .norm_key = d_nk ; 692w .norm_query = d_nq ; 693w .norm_conv = d_nc ; 694w .conv1d_f16 = d_c1 ; 695float * d_ks = nullptr ; 696ck (cudaMalloc (& d_ks ,key_scales .size ()* 4 ),"ks" ); 697ck (cudaMemcpy (d_ks ,key_scales .data (),key_scales .size ()* 4 ,cudaMemcpyHostToDevice ),"cks" ); 698w .key_scales = d_ks ; 699 700// Per-stage comparison. Each stage the oracle records is a separate line, so a mismatch says WHICH part 701// of the block is wrong rather than only that the sum is. The oracle writes each array token-major, so 702// every slice is an explicit (offset, count) pair - deriving the offset from the stage's NAME, which the 703// first version of this did, is a fixture that breaks the moment a name changes. 704struct Stage {const char * name ;const std::vector < float >* got ;const std::vector < float >* all ; 705size_t offset ;size_t n ; }; 706double worst_all = 0 ; 707 708// THE CONV HISTORY ADVANCES BETWEEN TOKENS, and getting this wrong is why token 1 compared badly at 709// first. The capture is a TWO-TOKEN ubatch: ggml pads `[hist(9) | normalized(0..nt-1)]` ONCE and the conv 710// reads rows `t+0, t+3, t+6, t+9` for output position t. So token 1's window is rows 1,4,7 of the SAME 711// history plus row 10 - which is token 1's own normalized - i.e. the state slides by one NORMALIZED row 712// per token. Feeding both tokens the original history compares my block's t=0 against ggml's t=1, and 713// both my kernel and my host reference made the same mistake, so they agreed with each other and only the 714// oracle could see it. 715// 716// ggml layout for the state is `ne=(hist, hc_dim)`: flat = row + NG_HIST*channel. 717 std::vector < float > hist_state = cap .hist ; 718for (int t = 0 ;t < cap .nt ;++ t ) { 719ck (cudaMemcpy (d_emb ,cap .emb .data ()+ (size_t )t * nd ,nd * 4 ,cudaMemcpyHostToDevice ),"cemb" ); 720ck (cudaMemcpy (d_hid ,cap .hidden .data ()+ (size_t )t * hcd ,hcd * 4 ,cudaMemcpyHostToDevice ),"chid" ); 721ck (cudaMemcpy (d_hist ,hist_state .data (), (size_t ) k::NG_HIST * hcd * 4 ,cudaMemcpyHostToDevice ), 722"chist" ); 723 k::PleOut out {}; 724out .key = d_ck ;out .value = d_cv ;out .gate = d_g ;out .gated = d_gd ; 725out .normalized = d_nm ;out .conv = d_co ;out .result = d_cr ; 726// the workspace is the caller's, and the sync the block used to do is now the caller's too 727void * ple_ws = nullptr ; 728ck (cudaMalloc (& ple_ws , k::ple_block_scratch_bytes ()),"ple_block scratch" ); 729if (t == 0 ) { 730const size_t bytes = (size_t ) k::ple_block_scratch_bytes (); 731ck (cudaMemset (ple_ws ,0xa5 ,bytes ),"PLE prelaunch guard sentinel" ); 732const struct AliasCase {float * k ::PleOut ::* field ;size_t offset ; }cases []= { 733 {& k::PleOut ::key ,0 }, {& k::PleOut ::value ,hcd }, {& k::PleOut ::gate ,hcd + nd }, 734 {& k::PleOut ::gated ,hcd + nd + (size_t ) k::NG_HC }, 735 {& k::PleOut ::normalized ,2 * hcd + nd + (size_t ) k::NG_HC }, 736 {& k::PleOut ::conv ,3 * hcd + nd + (size_t ) k::NG_HC }, {& k::PleOut ::result ,0 } 737 }; 738int refused = 0 ; 739for (const auto & item :cases ) { 740 k::PleOut invalid = out ; 741invalid .*( item . field ) = static_cast < float *> ( ple_ws ) + item . offset ; 742try { k::ple_block( d_emb , d_hid , d_hist , w , invalid , ple_ws , nullptr ); } 743catch ( const std:: invalid_argument & ) { ++ refused ; } 744} 745ck(cudaDeviceSynchronize(), "PLE guard no-launch sync" ); 746std:: vector < uint8_t > sentinel( bytes ); 747ck(cudaMemcpy( sentinel .data(), ple_ws , bytes , cudaMemcpyDeviceToHost ), "PLE guard sentinel readback" ); 748const bool unchanged = std::all_of( sentinel .begin(), sentinel .end(), []( uint8_t b ) { return b == 0xa5 ; }); 749const bool rejected = refused == 7 && unchanged ; 750std::printf( " PLE old caller output offsets rejected before launch: %s (%d/7, scratch %s)\n" , 751rejected ? "pass" : "FAIL" , refused , unchanged ? "unchanged" : "CORRUPTED" ); 752if (! rejected ) ++ bad ; 753} 754k::ple_block( d_emb , d_hid , d_hist , w , out , ple_ws , nullptr ); 755ck(cudaDeviceSynchronize(), "ple_block sync" ); 756ck(cudaMemcpy( dev_key .data(), d_ck , hcd * 4 , cudaMemcpyDeviceToHost ), "rck" ); 757ck(cudaMemcpy( dev_value .data(), d_cv , nd * 4 , cudaMemcpyDeviceToHost ), "rcv" ); 758ck(cudaMemcpy( dev_gate .data(), d_g , k:: NG_HC * 4 , cudaMemcpyDeviceToHost ), "rg" ); 759ck(cudaMemcpy( dev_gated .data(), d_gd , hcd * 4 , cudaMemcpyDeviceToHost ), "rgd" ); 760ck(cudaMemcpy( dev_norm .data(), d_nm , hcd * 4 , cudaMemcpyDeviceToHost ), "rnm" ); 761ck(cudaMemcpy( dev_conv .data(), d_co , hcd * 4 , cudaMemcpyDeviceToHost ), "rco" ); 762ck(cudaMemcpy( dev_res .data(), d_cr , hcd * 4 , cudaMemcpyDeviceToHost ), "rcr" ); 763 764const size_t ok_ = ( size_t ) t * hcd , ov = ( size_t ) t * nd , og = ( size_t ) t * ( size_t ) k:: NG_HC ; 765const Stage stages [] = { 766{ "key (grouped_norm of ple_key @ emb)" , & dev_key , & cap . key , ok_ , hcd }, 767{ "value (ple_value @ emb, BF16)" , & dev_value , & cap . value , ov , nd }, 768{ "gate (signed sqrt, sigmoid)" , & dev_gate , & cap . gate , og , ( size_t ) k:: NG_HC }, 769{ "gated (value broadcast * gate)" , & dev_gated , & cap . gated , ok_ , hcd }, 770{ "normalized (grouped_norm(gated, ple_norm_conv))" , & dev_norm , & cap . normalized , ok_ , hcd }, 771{ "conv_out (dilated conv, then SiLU)" , & dev_conv , & cap . conv_out , ok_ , hcd }, 772{ "result (hidden + gated + conv)" , & dev_res , & cap . result , ok_ , hcd }, 773}; 774for ( const Stage & s : stages ) { 775std:: vector < float > want ( s . all -> begin() + ( long long ) s . offset , 776s . all -> begin() + ( long long ) ( s . offset + s . n )); 777double mag = 0 ; 778long long nf = 0 ; 779const double rel = rel_l1( want .data(), s . got -> data(), s . n , & mag , & nf ); 780// NaN-SAFE: `rel > worst_all` is false for NaN, so `fmax` here would silently report a perfect 781// score for a fixture full of NaNs - round 197's exact failure. 782worst_all = ( rel > worst_all ) ? rel : worst_all ; 783if ( nf ) worst_all = std::nan( "" ); 784const bool last = (std::strncmp( s . name , "result" , 6 ) == 0 ); 785std::printf( " token %d %-46s rel %.3e (mean |ref| %.4f, non-finite %lld)%s\n" , t , s . name , rel , 786mag , nf , last && !le( rel , 1e-2 ) ? " *** over 1e-2 ***" : "" ); 787// TOLERANCE, and what sets it: this comparison is the GPU against a capture whose weights are 788// F32, so ggml performed NO activation conversion while the kernel applies the CONTRACT (Q8_0 789// for the Q2_0 weight, BF16 for the BF16 one). The contract's per-element cost is 2^-9 = 1.95e-3 790// for BF16 and ~0.4% for Q8_0, so the OUTPUT difference is ~2e-3 wherever there is no 791// cancellation and larger where there is - `conv_out` cancels by ~77x and is the one stage that 792// exceeds it. `result` is the quantity that matters and 1e-2 is five times the contract's own 793// per-element size, so it is a bound on "the contract and nothing else", not a judgement call. 794// The HOST reference below uses the capture's own F32 weights and is asserted at 1e-4, which is 795// what proves the difference here IS the contract. 796if ( last && !le( rel , 1e-2 )) ++ bad ; 797} 798 799if ( t == 0 ) { 800// Deliberate BF16 halfway values make the value projection's activation precision visible. 801// The scalar reference uses the actual packed BF16 weight bits and unrounded F32 inputs. 802std:: vector < float > witness( nd ), reference_value( nd ), native_value( nd ), native_result( hcd ), replay( hcd ); 803for ( size_t i = 0 ; i < nd ; ++ i ) witness [ i ] = i % 7 == 0 ? 1.00390625f : -0.501953125f ; 804for ( size_t row = 0 ; row < nd ; ++ row ) { 805double sum = 0.0 ; 806for ( size_t col = 0 ; col < nd ; ++ col ) { 807const uint32_t bits = uint32_t ( value_bf16 [ row * nd + col ]) << 16 ; 808float weight ; 809std::memcpy( & weight , & bits , sizeof ( weight )); 810sum += double ( weight ) * witness [ col ]; 811} 812reference_value [ row ] = float ( sum ); 813} 814ck(cudaMemcpy( d_emb , witness .data(), nd * sizeof ( float ), cudaMemcpyHostToDevice ), "native PLE witness" ); 815k::ple_block( d_emb , d_hid , d_hist , w , out , ple_ws , nullptr ); 816ck(cudaDeviceSynchronize(), "legacy PLE witness sync" ); 817std:: vector < float > legacy_value( nd ); 818ck(cudaMemcpy( legacy_value .data(), d_cv , nd * sizeof ( float ), cudaMemcpyDeviceToHost ), "legacy PLE witness value" ); 819cudaStream_t stream ; 820ck(cudaStreamCreateWithFlags( & stream , cudaStreamNonBlocking ), "native PLE stream" ); 821k::ple_set_native_bf16(true); 822k::ple_block( d_emb , d_hid , d_hist , w , out , ple_ws , stream ); 823ck(cudaStreamSynchronize( stream ), "native PLE sync" ); 824ck(cudaMemcpy( native_value .data(), d_cv , nd * sizeof ( float ), cudaMemcpyDeviceToHost ), "native PLE value" ); 825ck(cudaMemcpy( native_result .data(), d_cr , hcd * sizeof ( float ), cudaMemcpyDeviceToHost ), "native PLE result" ); 826long long nf = 0 ; 827const double rel = rel_l1( reference_value .data(), native_value .data(), nd , nullptr , & nf ); 828const double separation = rel_l1( native_value .data(), legacy_value .data(), nd ); 829const bool correct = le( rel , 2e-6 ) && nf == 0 && gt( separation , 1e-5 ); 830std::printf( " native PLE value: %s (ref rel %.3e, BF16 separation %.3e)\n" , 831correct ? "pass" : "FAIL" , rel , separation ); 832if (! correct ) ++ bad ; 833cudaGraph_t graph ; 834cudaGraphExec_t executable ; 835ck(cudaStreamBeginCapture( stream , cudaStreamCaptureModeThreadLocal ), "native PLE capture" ); 836k::ple_block( d_emb , d_hid , d_hist , w , out , ple_ws , stream ); 837ck(cudaStreamEndCapture( stream , & graph ), "native PLE capture end" ); 838ck(cudaGraphInstantiate( & executable , graph , nullptr , nullptr , 0 ), "native PLE instantiate" ); 839k::ple_set_native_bf16(false); 840ck(cudaGraphLaunch( executable , stream ), "native PLE replay" ); 841ck(cudaStreamSynchronize( stream ), "native PLE replay sync" ); 842ck(cudaMemcpy( replay .data(), d_cr , hcd * sizeof ( float ), cudaMemcpyDeviceToHost ), "native PLE replay result" ); 843const bool captured = std::memcmp( native_result .data(), replay .data(), hcd * sizeof ( float )) == 0 ; 844std::printf( " native PLE captured selection: %s\n" , captured ? "byte-identical" : "FAIL" ); 845if (! captured ) ++ bad ; 846ck(cudaGraphExecDestroy( executable ), "native PLE graph exec destroy" ); 847ck(cudaGraphDestroy( graph ), "native PLE graph destroy" ); 848ck(cudaStreamDestroy( stream ), "native PLE stream destroy" ); 849ck(cudaMemcpy( d_emb , cap . emb .data(), nd * sizeof ( float ), cudaMemcpyHostToDevice ), "restore PLE embedding" ); 850k::ple_block( d_emb , d_hid , d_hist , w , out , ple_ws , nullptr ); 851ck(cudaDeviceSynchronize(), "restored PLE sync" ); 852ck(cudaMemcpy( replay .data(), d_cr , hcd * sizeof ( float ), cudaMemcpyDeviceToHost ), "restored PLE result" ); 853const bool restored = std::memcmp( dev_res .data(), replay .data(), hcd * sizeof ( float )) == 0 ; 854std::printf( " restored PLE default: %s\n" , restored ? "byte-identical" : "FAIL" ); 855if (! restored ) ++ bad ; 856} 857 858if ( t == 0 ) { 859// This checks native-projection wiring and graph lifetime, independently 860// of the legacy CPU/F32 structural capture. Actual Q2_0 arithmetic is 861// checked separately by native_mmvq_parity against the pinned CUDA DLL. 862const size_t blocks = n_scales , native_bytes = blocks * 18 , guard = 64 ; 863const size_t qbytes = k::native_q8_1_bytes(k:: NG_N_EMBD ); 864std:: vector < uint8_t > native_key( native_bytes ); 865for ( size_t b = 0 ; b < blocks ; ++ b ) { 866std::memcpy( native_key .data() + b * 18 , raw_scales .data() + b * 2 , 2 ); 867std::memcpy( native_key .data() + b * 18 + 2 , key_codes .data() + b * 16 , 16 ); 868} 869void * native_storage = nullptr , * q_storage = nullptr ; 870float * raw_projection = nullptr ; 871ck(cudaMalloc( & native_storage , native_bytes + 2 * guard ), "native PLE weights" ); 872ck(cudaMalloc( & q_storage , qbytes + 2 * guard ), "native PLE q8 scratch" ); 873ck(cudaMalloc( & raw_projection , hcd * 4 ), "native PLE raw projection" ); 874ck(cudaMemset( native_storage , 0xa5 , native_bytes + 2 * guard ), "native PLE weight guards" ); 875ck(cudaMemset( q_storage , 0xa5 , qbytes + 2 * guard ), "native PLE q8 guards" ); 876void * native_data = static_cast < uint8_t *> ( native_storage ) + guard ; 877void * native_q = static_cast < uint8_t *> ( q_storage ) + guard ; 878ck(cudaMemcpy( native_data , native_key .data(), native_bytes , cudaMemcpyHostToDevice ), "native PLE weights upload" ); 879k:: PleWeights nw = w ; 880nw . key_native_data = native_data ; nw . key_native_type = 42 ; nw . key_native_q8_1 = native_q ; 881cudaStream_t stream ; 882ck(cudaStreamCreateWithFlags( & stream , cudaStreamNonBlocking ), "native PLE key stream" ); 883const size_t workspace_bytes = ( size_t ) k::ple_block_scratch_bytes(); 884ck(cudaMemset( ple_ws , 0xa5 , workspace_bytes ), "native PLE no-launch sentinel" ); 885// the guards, the weight upload and the sentinel run on the legacy stream, which the non-blocking 886// `stream` does not wait for 887ck(cudaDeviceSynchronize(), "native PLE key setup" ); 888int refused = 0 ; 889for ( int c = 0 ; c < 9 ; ++ c ) { 890auto invalid = nw ; 891if ( c == 0 ) invalid . key_native_type = 11 ; 892if ( c == 1 ) invalid . key_native_q8_1 = nullptr ; 893if ( c == 3 ) invalid . key_native_q8_1 = ple_ws ; 894if ( c == 4 ) invalid . key_native_q8_1 = d_emb ; 895if ( c == 5 ) invalid . key_native_q8_1 = out . key ; 896if ( c == 6 ) invalid . key_native_q8_1 = static_cast < uint8_t *> ( native_q ) + 1 ; 897if ( c == 7 ) invalid . key_native_data = static_cast < uint8_t *> ( native_data ) + 1 ; 898if ( c == 8 ) invalid . key_native_q8_1 = native_data ; 899try { k::ple_block( d_emb , d_hid , d_hist , invalid , out , ple_ws , c == 2 ? nullptr : stream ); } 900catch ( const std:: invalid_argument & ) { ++ refused ; } 901} 902ck(cudaStreamSynchronize( stream ), "native PLE refusal sync" ); 903std:: vector < uint8_t > sentinel( workspace_bytes ); 904ck(cudaMemcpy( sentinel .data(), ple_ws , workspace_bytes , cudaMemcpyDeviceToHost ), "native PLE refusal sentinel" ); 905const bool untouched = std::all_of( sentinel .begin(), sentinel .end(), []( uint8_t x ) { return x == 0xa5 ; }); 906std::printf( " native PLE key prelaunch guards: %s (%d/9, workspace %s)\n" , 907refused == 9 && untouched ? "pass" : "FAIL" , refused , untouched ? "unchanged" : "changed" ); 908if ( refused != 9 || ! untouched ) ++ bad ; 909cudaGraph_t graph = nullptr ; cudaGraphExec_t executable = nullptr ; 910std:: vector < float > projected( hcd ), normalized( hcd ), actual_key( hcd ), actual_result( hcd ), replay( hcd ); 911for ( int p = 0 ; p < std::min( cap . nt , 2 ); ++ p ) { 912ck(cudaMemcpy( d_emb , cap . emb .data() + ( size_t ) p * nd , nd * 4 , cudaMemcpyHostToDevice ), "native PLE key input" ); 913ck(cudaDeviceSynchronize(), "native PLE key input sync" ); 914k::native_q2_0_f32( native_data , d_emb , native_q , raw_projection , k:: NG_N_EMBD , k:: NG_HC_DIM , 1 , stream ); 915ck(cudaStreamSynchronize( stream ), "native PLE raw key sync" ); 916ck(cudaMemcpy( projected .data(), raw_projection , hcd * 4 , cudaMemcpyDeviceToHost ), "native PLE raw key read" ); 917for ( int c = 0 ; c < k:: NG_HC ; ++ c ) { 918double sum = 0 ; 919for ( size_t j = 0 ; j < nd ; ++ j ) { const float v = projected [( size_t ) c * nd + j ]; sum += double ( v * v ); } 920const float scale = 1.0f / std::sqrt( float ( sum / double ( nd )) + k:: NG_RMS_EPS ); 921for ( size_t j = 0 ; j < nd ; ++ j ) { const size_t i = ( size_t ) c * nd + j ; normalized [ i ] = projected [ i ] * scale * cap . w_nk [ i ]; } 922} 923k::ple_block( d_emb , d_hid , d_hist , nw , out , ple_ws , stream ); 924ck(cudaStreamSynchronize( stream ), "native PLE key direct sync" ); 925ck(cudaMemcpy( actual_key .data(), d_ck , hcd * 4 , cudaMemcpyDeviceToHost ), "native PLE key read" ); 926ck(cudaMemcpy( actual_result .data(), d_cr , hcd * 4 , cudaMemcpyDeviceToHost ), "native PLE result read" ); 927const double rel = rel_l1( normalized .data(), actual_key .data(), hcd ); 928const bool wired = le( rel , 2e-6 ) && nonfinite( actual_result .data(), hcd ) == 0 ; 929std::printf( " native PLE key projection->existing norm input %d: %s (rel %.3e)\n" , p , wired ? "pass" : "FAIL" , rel ); 930if (! wired ) ++ bad ; 931if ( p == 0 ) { 932ck(cudaStreamBeginCapture( stream , cudaStreamCaptureModeThreadLocal ), "native PLE key capture" ); 933k::ple_block( d_emb , d_hid , d_hist , nw , out , ple_ws , stream ); 934ck(cudaStreamEndCapture( stream , & graph ), "native PLE key capture end" ); 935ck(cudaGraphInstantiate( & executable , graph , nullptr , nullptr , 0 ), "native PLE key instantiate" ); 936} 937nw . key_native_data = nullptr ; // graph selection must survive descriptor changes 938for ( int repeat = 0 ; repeat < 2 ; ++ repeat ) { 939ck(cudaGraphLaunch( executable , stream ), "native PLE key replay" ); 940ck(cudaStreamSynchronize( stream ), "native PLE key replay sync" ); 941ck(cudaMemcpy( replay .data(), d_cr , hcd * 4 , cudaMemcpyDeviceToHost ), "native PLE key replay read" ); 942if (std::memcmp( actual_result .data(), replay .data(), hcd * 4 ) != 0 ) ++ bad ; 943} 944nw . key_native_data = native_data ; 945} 946ck(cudaGraphExecDestroy( executable ), "native PLE key executable destroy" ); 947ck(cudaGraphDestroy( graph ), "native PLE key graph destroy" ); 948for ( int b = 0 ; b < 2 ; ++ b ) { 949const void * storage = b == 0 ? native_storage : q_storage ; 950const size_t payload = b == 0 ? native_bytes : qbytes ; 951std:: vector < uint8_t > ends ( 2 * guard ); 952ck(cudaMemcpy( ends .data(), storage , guard , cudaMemcpyDeviceToHost ), "native PLE prefix guard" ); 953ck(cudaMemcpy( ends .data() + guard , static_cast < const uint8_t *> ( storage ) + guard + payload , guard , cudaMemcpyDeviceToHost ), "native PLE suffix guard" ); 954if (!std::all_of( ends .begin(), ends .end(), []( uint8_t x ) { return x == 0xa5 ; })) ++ bad ; 955} 956ck(cudaStreamDestroy( stream ), "native PLE key stream destroy" ); 957cudaFree( raw_projection ); cudaFree( q_storage ); cudaFree( native_storage ); 958ck(cudaMemcpy( d_emb , cap . emb .data(), nd * 4 , cudaMemcpyHostToDevice ), "native PLE restore input" ); 959k::ple_block( d_emb , d_hid , d_hist , w , out , ple_ws , nullptr ); 960ck(cudaDeviceSynchronize(), "native PLE default restore sync" ); 961ck(cudaMemcpy( replay .data(), d_cr , hcd * 4 , cudaMemcpyDeviceToHost ), "native PLE default restore read" ); 962const bool restored = std::memcmp( dev_res .data(), replay .data(), hcd * 4 ) == 0 ; 963std::printf( " native PLE key graph/repeat/buffer guards checked; restored default: %s\n" , restored ? "byte-identical" : "FAIL" ); 964if (! restored ) ++ bad ; 965} 966 967if ( t == 0 ) { 968// The engine only needs result and normalized. Export normalized after the complete private 969// workspace; result may overwrite hidden once its original values are no longer needed. 970const size_t workspace_bytes = ( size_t ) k::ple_block_scratch_bytes(); 971void * compact_workspace = nullptr ; 972ck(cudaMalloc( & compact_workspace , workspace_bytes + hcd * sizeof ( float )), "compact PLE workspace" ); 973k:: PleOut compact {}; 974compact . normalized = reinterpret_cast < float *> (static_cast < uint8_t *> ( compact_workspace ) + workspace_bytes ); 975compact . result = d_hid ; 976k::ple_block( d_emb , d_hid , d_hist , w , compact , compact_workspace , nullptr ); 977ck(cudaDeviceSynchronize(), "compact PLE sync" ); 978std:: vector < float > compact_norm( hcd ), compact_result( hcd ); 979ck(cudaMemcpy( compact_norm .data(), compact . normalized , hcd * sizeof ( float ), cudaMemcpyDeviceToHost ), "compact PLE normalized" ); 980ck(cudaMemcpy( compact_result .data(), d_hid , hcd * sizeof ( float ), cudaMemcpyDeviceToHost ), "compact PLE result" ); 981const bool equal = std::memcmp( compact_norm .data(), dev_norm .data(), hcd * sizeof ( float )) == 0 && 982std::memcmp( compact_result .data(), dev_res .data(), hcd * sizeof ( float )) == 0 ; 983std::printf( " PLE separate exports and in-place hidden result: %s\n" , equal ? "byte-identical" : "FAIL" ); 984if (! equal ) ++ bad ; 985ck(cudaMemcpy( d_hid , cap . hidden .data(), hcd * sizeof ( float ), cudaMemcpyHostToDevice ), "restore PLE hidden input" ); 986cudaFree( compact_workspace ); 987} 988 989// slide the conv state by one NORMALIZED row, which is what the next token's window needs 990for ( size_t c = 0 ; c < hcd ; ++ c ) 991for ( size_t r = 0 ; r + 1 < ( size_t ) k:: NG_HIST ; ++ r ) 992hist_state [ r + ( size_t ) k:: NG_HIST * c ] = hist_state [( r + 1 ) + ( size_t ) k:: NG_HIST * c ]; 993for ( size_t c = 0 ; c < hcd ; ++ c ) 994hist_state [(( size_t ) k:: NG_HIST - 1 ) + ( size_t ) k:: NG_HIST * c ] = dev_norm [ c ]; 995cudaFree( ple_ws ); 996} 997 998// ---- the trap that matters most: gated vs normalized as the conv input -------------------------- 999// `ref/ngram.py`'s docstring calls `terms` "the padded gated values"; the source pads `normalized`. 1000// Feeding the conv the gated values instead is a one-word change with every shape intact, so it is 1001// computed here and required to differ. 1002{ 1003const double rel_norm_gated = rel_l1( cap . gated .data(), cap . normalized .data(), hcd ); 1004std::printf( " %-52s %s (%.2f%% apart)\n" , "normalized vs gated as the conv input is observable" , 1005rel_norm_gated > 0.05 ? "yes" : "*** NO ***" , rel_norm_gated * 100 ); 1006if (!( rel_norm_gated > 0.05 )) ++ bad ; 1007} 1008 1009// ---- the conv TAP ORDER: tap 0 reads the furthest back, not the current row --------------------- 1010{ 1011// Recompute the conv on the host with the taps reversed, from the ORACLE's own `normalized`, and 1012// require the result to differ from the oracle's conv_out. 1013const size_t hcd2 = hcd ; 1014std:: vector < float > rev ( hcd2 , 0.0f ); 1015for ( size_t c = 0 ; c < hcd2 ; ++ c ) { 1016float acc = 0 ; 1017for ( int kk = 0 ; kk < k:: PLE_CONV_KERNEL ; ++ kk ) { 1018// THE RIVAL READING OF THE TAP CONVENTION. ggml's is `t - (K-1-k)*d`, i.e. tap 0 reads the 1019// FURTHEST back; the natural misreading is `t - k*d`, i.e. tap 0 reads the CURRENT row. 1020// 1021// The first version of this trap wrote `row = kk*dil` for the rival - which is ALGEBRAICALLY 1022// THE SAME as the correct `hist - (K-1-kk)*dil` whenever `hist == (K-1)*dil`, because 1023// `9-(3-kk)*3 == 3kk` identically. It reported "0.00% apart" and was measuring nothing. 1024// The rival has to REVERSE the row order: `(K-1-kk)*dil` gives 9,6,3,0 against the correct 1025// 0,3,6,9, so tap 0 pairs the kernel's first weight with the NEWEST row instead of the oldest. 1026const int row = (k:: PLE_CONV_KERNEL - 1 - kk ) * k:: NGRAM_SIZE ; 1027// ROW-FASTEST: the capture's history is ggml's `ne=(hist, hc_dim)`, flat = row + hist*channel 1028const float v = ( row == k:: NG_HIST ) ? cap . normalized [ c ] 1029: cap . hist [( size_t ) row + ( size_t ) k:: NG_HIST * c ]; 1030// GGML-NATIVE: `w_conv[k + kern*c]`, because the capture's tensor is ne=(kern, hc_dim) with 1031// ne0 = kern fast. `w_conv[kk*hc_dim + c]` is the TRANSPOSE and is what this reference had 1032// first - it reported 115% on conv_out while the GPU kernel, which carries the layout note, 1033// was within 4.6e-02. The oracle caught the reference, not the kernel, which is the whole 1034// reason for having one. 1035acc += cap . w_conv [( size_t ) kk + ( size_t ) k:: PLE_CONV_KERNEL * c ] * v ; 1036} 1037rev [ c ] = acc / ( 1.0f + std::exp( - acc )); 1038} 1039const double rel = rel_l1( cap . conv_out .data(), rev .data(), hcd2 ); 1040std::printf( " %-52s %s (%.2f%% apart)\n" , "reversed conv tap order is observable" , 1041gt( rel , 0.05 ) ? "yes" : "*** NO ***" , rel * 100 ); 1042if (!gt( rel , 0.05 )) ++ bad ; 1043} 1044 1045// ---- THE HOST f32 REFERENCE, which is what makes the gaps above ATTRIBUTABLE rather than mysterious. 1046// 1047// `ple_layer_xcheck.cpp` builds ggml's graph with the weights as **F32 tensors** (`ggml_new_tensor_2d(..., 1048// GGML_TYPE_F32, ...)`). `ggml_mul_mat` converts src1 to src0's `vec_dot_type`, so with an F32 weight 1049// ggml performs NO activation conversion at all - while the real `ple_key` is Q2_0 (contract Q8_0) and the 1050// real `ple_value` is BF16 (contract BF16). 1051// 1052// **The capture is therefore a valid oracle for the STRUCTURE and not for the ACTIVATION CONTRACT.** This 1053// reference reproduces it exactly, in f32, using the capture's own weights - which proves every LAYOUT in 1054// the block (the conv kernel's `k + kern*c`, the row-fastest history, per-stream grouped norms, the 1055// head-slowest gather) independently of the GPU. Whatever gap remains between the GPU and the capture is 1056// then exactly the contract, and nothing else. 1057// Hoisted out of the reference block below: the term-magnitude metric needs the state the LAST token 1058// used, and that block has already closed by the time it runs. 1059std:: vector < float > hist_last ; 1060{ 1061const size_t H = hcd , N = nd ; 1062std:: vector < float > k_ref( H ), q_ref( H ), v_ref( N ), gt_ref(k:: NG_HC ), gd_ref( H ), nm_ref( H ), cv_ref( H ), 1063rs_ref( H ); 1064auto gnorm = [ & ]( const float * x , const float * w , float * y , int n ) { 1065for ( int c = 0 ; c < k:: NG_HC ; ++ c ) { 1066double sum = 0.0 ; 1067for ( int d = 0 ; d < k:: NG_N_EMBD ; ++ d ) { 1068const float xv = x [ c * k:: NG_N_EMBD + d ]; 1069sum += ( double ) ( xv * xv ); // f32 product, widened - as ggml does 1070} 1071const float mean = ( float ) ( sum / k:: NG_N_EMBD ); 1072const float scale = 1.0f / std::sqrt( mean + cap . eps ); 1073for ( int d = 0 ; d < k:: NG_N_EMBD ; ++ d ) 1074y [ c * k:: NG_N_EMBD + d ] = x [ c * k:: NG_N_EMBD + d ] * scale * w [ c * k:: NG_N_EMBD + d ]; 1075} 1076( void ) n ; 1077}; 1078// The SAME history advance as the GPU loop, so the two are compared on identical inputs. 1079std:: vector < float > hist_ref = cap . hist ; 1080for ( int t = 0 ; t < cap . nt ; ++ t ) { 1081const float * emb = cap . emb .data() + ( size_t ) t * N ; 1082const float * hid = cap . hidden .data() + ( size_t ) t * H ; 1083// key = w_key @ emb, with the capture's F32 weight and NO activation conversion 1084for ( size_t o = 0 ; o < H ; ++ o ) { 1085double a = 0 ; 1086for ( size_t i = 0 ; i < N ; ++ i ) a += ( double ) cap . w_key [ o * N + i ] * ( double ) emb [ i ]; 1087k_ref [ o ] = ( float ) a ; 1088} 1089gnorm( k_ref .data(), cap . w_nk .data(), k_ref .data(), k:: NG_N_EMBD ); 1090gnorm( hid , cap . w_nq .data(), q_ref .data(), k:: NG_N_EMBD ); 1091for ( size_t o = 0 ; o < N ; ++ o ) { 1092double a = 0 ; 1093for ( size_t i = 0 ; i < N ; ++ i ) a += ( double ) cap . w_value [ o * N + i ] * ( double ) emb [ i ]; 1094v_ref [ o ] = ( float ) a ; 1095} 1096for ( int c = 0 ; c < k:: NG_HC ; ++ c ) { 1097double a = 0 ; 1098for ( int d = 0 ; d < k:: NG_N_EMBD ; ++ d ) 1099a += ( double ) k_ref [ c * k:: NG_N_EMBD + d ] * ( double ) q_ref [ c * k:: NG_N_EMBD + d ]; 1100const float s = ( float ) ( a / ( double ) 1.0 ) / std::sqrt(( float ) k:: NG_N_EMBD ); 1101const float mag = std::sqrt(std::fmax(std::fabs( s ), 1e-6f )); 1102const float sgn = ( s > 0 ) ? 1.0f : (( s < 0 ) ? -1.0f : 0.0f ); 1103gt_ref [ c ] = 1.0f / ( 1.0f + std::exp( - ( sgn * mag ))); 1104} 1105for ( size_t i = 0 ; i < H ; ++ i ) 1106gd_ref [ i ] = v_ref [ i % N ] * gt_ref [ i / N ]; 1107gnorm( gd_ref .data(), cap . w_nc .data(), nm_ref .data(), k:: NG_N_EMBD ); 1108for ( size_t c = 0 ; c < H ; ++ c ) { 1109float acc = 0 ; 1110for ( int kk = 0 ; kk < k:: PLE_CONV_KERNEL ; ++ kk ) { 1111const int row = k:: NG_HIST - (k:: PLE_CONV_KERNEL - 1 - kk ) * k:: NGRAM_SIZE ; 1112// capture history is ggml `ne=(hist, hc_dim)`: flat = row + hist*channel. `hist_ref` is 1113// the ADVANCED state, so this reference sees exactly what the GPU call saw. 1114const float vv = ( row == k:: NG_HIST ) ? nm_ref [ c ] 1115: hist_ref [( size_t ) row + ( size_t ) k:: NG_HIST * c ]; 1116acc += cap . w_conv [( size_t ) kk + ( size_t ) k:: PLE_CONV_KERNEL * c ] * vv ; 1117} 1118cv_ref [ c ] = acc / ( 1.0f + std::exp( - acc )); 1119} 1120for ( size_t i = 0 ; i < H ; ++ i ) rs_ref [ i ] = hid [ i ] + gd_ref [ i ] + cv_ref [ i ]; 1121 1122const size_t ok_ = ( size_t ) t * H , ov = ( size_t ) t * N , og = ( size_t ) t * ( size_t ) k:: NG_HC ; 1123struct HCmp { const char * name ; const std:: vector < float >* got ; const std:: vector < float >* all ; 1124size_t off ; size_t n ; }; 1125const HCmp cmps [] = { 1126{ "key" , & k_ref , & cap . key , ok_ , H }, { "value" , & v_ref , & cap . value , ov , N }, 1127{ "gate" , & gt_ref , & cap . gate , og , ( size_t ) k:: NG_HC }, 1128{ "gated" , & gd_ref , & cap . gated , ok_ , H }, { "normalized" , & nm_ref , & cap . normalized , ok_ , H }, 1129{ "conv_out" , & cv_ref , & cap . conv_out , ok_ , H }, 1130{ "result" , & rs_ref , & cap . result , ok_ , H }, 1131}; 1132for ( const HCmp & s : cmps ) { 1133std:: vector < float > want ( s . all -> begin() + ( long long ) s . off , 1134s . all -> begin() + ( long long ) ( s . off + s . n )); 1135long long nf = 0 ; 1136const double rel = rel_l1( want .data(), s . got -> data(), s . n , nullptr , & nf ); 1137const bool ok = le( rel , 1e-4 ) && nf == 0 ; 1138std::printf( " host f32 reference, token %d %-12s rel %.3e (non-finite %lld)%s\n" , t , s . name , 1139rel , nf , ok ? "" : " *** FAIL ***" ); 1140if (! ok ) ++ bad ; 1141} 1142 1143// save the state this token used, then slide it - identical to the GPU-side advance 1144if ( t == cap . nt - 1 ) hist_last = hist_ref ; 1145for ( size_t c = 0 ; c < hcd ; ++ c ) 1146for ( size_t r = 0 ; r + 1 < ( size_t ) k:: NG_HIST ; ++ r ) 1147hist_ref [ r + ( size_t ) k:: NG_HIST * c ] = hist_ref [( r + 1 ) + ( size_t ) k:: NG_HIST * c ]; 1148for ( size_t c = 0 ; c < hcd ; ++ c ) 1149hist_ref [(( size_t ) k:: NG_HIST - 1 ) + ( size_t ) k:: NG_HIST * c ] = nm_ref [ c ]; 1150} 1151// TOLERANCE: 1e-4. Both sides are f32 (or f64-accumulated) sums of 2560 products, so the only 1152// difference is summation ORDER, which is ~n*eps = 2560*6e-8 = 1.5e-4 worst case and far less in 1153// practice. A STRUCTURAL error - a transposed conv kernel, a channel-slow history, a head-fastest 1154// gather - is O(1), so the two are three orders apart and the bound is not a judgement call. 1155} 1156 1157// ---- `conv_out`'s error must be measured against the TERMS, not the result ---------------------- 1158// 1159// The dilated conv sums four terms and the sum CANCELS: `normalized` has mean |.| around 0.70 and the 1160// result's is around 0.009, a factor of ~77. Dividing by the result therefore reports the CONDITION 1161// NUMBER and not the arithmetic - the same metric mistake this project has made four times (rounds 169, 1162// 189, 194, 196), and it is what made `conv_out` look like the worst stage at 4.55e-02. 1163{ 1164// `dev_conv` holds the LAST token after the loop above, and the capture is token-major. 1165const float * oc = cap . conv_out .data() + ( size_t ) ( cap . nt - 1 ) * hcd ; 1166double num = 0 , terms = 0 , res = 0 ; 1167for ( size_t c = 0 ; c < hcd ; ++ c ) { 1168double t_sum = 0 ; 1169for ( int kk = 0 ; kk < k:: PLE_CONV_KERNEL ; ++ kk ) { 1170const int row = k:: NG_HIST - (k:: PLE_CONV_KERNEL - 1 - kk ) * k:: NGRAM_SIZE ; 1171const float v = ( row == k:: NG_HIST ) 1172? cap . normalized [( size_t ) ( cap . nt - 1 ) * hcd + c ] 1173: hist_last [( size_t ) row + ( size_t ) k:: NG_HIST * c ]; 1174t_sum += std::fabs(( double ) cap . w_conv [( size_t ) kk + ( size_t ) k:: PLE_CONV_KERNEL * c ] * 1175( double ) v ); 1176} 1177terms += t_sum ; 1178res += std::fabs(( double ) oc [ c ]); 1179num += std::fabs(( double ) oc [ c ] - ( double ) dev_conv [ c ]); 1180} 1181std::printf( "\n conv_out (token %d) against the TERM magnitude, not the result: rel %.3e" 1182" (|result|/|terms| = %.4f)\n" , 1183cap . nt - 1 , num / terms , res / terms ); 1184} 1185 1186std::printf( "\nple_parity: %d failures (worst stage rel %.3e)\n" , bad , worst_all ); 1187if ( bad ) return 1 ; 1188if ( selftest ) std::printf( "ple_parity OK\n" ); 1189return 0 ; 1190}