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