okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
67148809b
main
1// tests/quant/quant_parity.cpp - the layer against its ORACLE: ggml-cpu's own dot products and activation quantizers, bit for bit. 2// 3// ggml-cpu is linked into this program only. The flavour of the linked ggml-cpu decides which contract is checked (isa.hpp): 4// a default / STRATA_PORTABLE build -> Arith::Avx2 (ggml's __AVX2__ branches) 5// -DSTRATA_ISA_FLOOR=avx -> Arith::Avx (its __AVX__ branches) 6// -DSTRATA_ISA_FLOOR=none -> Arith::Generic (its _generic C code) 7// Every kernel of that contract the CPU can run is compared with ggml's, on rows made by ggml's own quantizers from random floats 8// (so scales, mins and sign patterns are those of real models), at 1..8 blocks, and the activation quantizers on random rows and on rows 9// built to be exact ties (where half-to-even and half-away-from-zero differ). 10// 11// TWO LEGS (OWN-2A-ORACLE, 11-10). ggml-cpu is C that the compiler may contract into FMAs (-ffp-contract=fast, GCC's default for gnu11), and newer 12// GCCs fuse where GCC 13 did not: ggml's own results move with the compiler that builds this test (measured on one Broadwell box: GCC 14.3 moves 55 13// IQ4_NL rows, GCC 15.2 those and 183 Q2_0 rows, by 1-4 ulp), while the layer's results stay the same bytes under GCC 13.3, 14.3 and 15.2. So: 14// leg 1, the gate: every group (flavour, section, type, n) of our results against tests/quant/golden_x86.txt, the digests of the reference that 15// GCC 13.3's ggml-cpu computes for the same inputs (its header says how it was made). Any difference fails, whatever the compiler. 16// leg 2, information: our results row by row against the ggml-cpu linked here, as before. Its summary names the compiler and the groups where 17// that ggml differs from the golden reference. QUANT_PARITY_LIVE_STRICT=1 in the environment makes its differences fail too (the old 18// meaning of this test: right only where the local compiler builds ggml as GCC 13 does). 19// Where no golden exists (arm64: the Neon contract; a run with --rows other than 24) leg 2 is the gate, as before. 20// 21// A failing group, debugged without a GCC 13 box at hand: the FAIL line names its key, e.g. "avx2 dot iq4_nl 96". Run 22// quant_parity --dump-group "avx2 dot iq4_nl 96" > here.txt 23// on the failing build and the same on a GCC 13 build of the same tree (or ask for its file): every row of the group, ours per kernel and ggml's, as 24// output bits (hex bytes), with the row's input digest. `diff` of the two files shows which rows moved and on which side. 25// 26// usage: quant_parity [--rows N] [--type NAME] [--verbose] [--golden FILE] [--dump-group KEY] [--write-golden FILE] [--regen-check] 27// --write-golden FILE write this flavour's golden lines (the reference digests of the linked ggml) to FILE; tests/quant/make_golden.sh uses it 28// --regen-check GCC 13.x on x86 only (exit 77 = skipped elsewhere): the linked ggml regenerates this flavour's stored lines byte for byte 29// exit 0 = every comparison of the gate leg bit-identical 30#include <cmath> 31#include <cstdint> 32#include <cstdio> 33#include <cstdlib> 34#include <cstring> 35#include <fstream> 36#include <map> 37#include <sstream> 38#include <string> 39#include <vector> 40 41#include "ggml-cpu.h" 42#include "ggml.h" 43#include "strata/quant/act.hpp" 44#include "strata/quant/dequant.hpp" 45#include "strata/quant/dot.hpp" 46#include "strata/quant/isa.hpp" 47#include "strata/quant/types.hpp" 48#include "internal.hpp" // src/quant: the fp16 helpers (test only) 49 50#ifndef STRATA_QUANT_GOLDEN_FILE 51#define STRATA_QUANT_GOLDEN_FILE "" 52#endif 53 54namespace sq= strata::quant; 55 56namespace { 57 58struct Rng { 59uint64_t s ; 60explicit Rng (uint64_t seed ) :s (seed * 0x9E3779B97F4A7C15ull + 99 ) {} 61uint32_t next () { 62s ^=s >>12 ; 63s ^=s <<25 ; 64s ^=s >>27 ; 65return (uint32_t ) ((s * 0x2545F4914F6CDD1Dull ) >>32 ); 66 } 67float uni () {return (float )next () /4294967296.0f * 2.f - 1.f ; } 68// every draw in its own statement: the operands of one expression have no evaluation order in C++, and GCC and MSVC pick different ones 69float gauss () { 70const float a = uni (); 71const float b = uni (); 72const float c = uni (); 73const float d = uni (); 74return (a + b + c + d )* 0.5f ; 75 } 76}; 77 78// The golden digest: FNV-1a with 64-bit state (offset basis 0xcbf29ce484222325, prime 0x100000001b3), over the bytes in memory order, continued 79// across the rows of a group. Fixed here on purpose (never std::hash or a library's hash): the golden file is only meaningful while this stays. 80constexpr uint64_t kFnvBasis = 0xcbf29ce484222325ull ; 81uint64_t golden_fnv1a64 (const void * p ,size_t n ,uint64_t h = kFnvBasis ) { 82const unsigned char * b = (const unsigned char * )p ; 83for (size_t i = 0 ;i < n ;++ i ) { 84h ^=b [i ]; 85h *=0x100000001b3ull ; 86 } 87return h ; 88} 89// the published FNV-1a 64 test vectors 90bool digest_selftest () { 91return golden_fnv1a64 ("" ,0 )== 0xcbf29ce484222325ull && golden_fnv1a64 ("a" ,1 )== 0xaf63dc4c8601ec8cull && 92golden_fnv1a64 ("foobar" ,6 )== 0x85944171f73967e8ull ; 93} 94 95std::string compiler_name () { 96#if defined(__clang__ ) 97return std::string ("clang " )+ __clang_version__ ; 98#elif defined(__GNUC__ ) 99return std::string ("GCC " )+ __VERSION__ ; 100#elif defined(_MSC_FULL_VER ) 101return "MSVC " + std::to_string (_MSC_FULL_VER ); 102#else 103return "unknown compiler" ; 104#endif 105} 106 107// Toolchain families of the golden file. "gcc" lines are made by GCC 13.x on x86 and hold for every toolchain; "msvc" lines, made by MSVC 19.4x, stand 108// beside them only for the groups where MSVC's arithmetic differs (MSVC does not contract the intrinsics' add-of-mul into FMA where GCC does). 109// The family a build reads its own lines from, and whether --regen-check can regenerate them here: 110#if defined(_MSC_VER )&& !defined(__clang__ ) 111const char * const kFamily = "msvc" ; 112#if _MSC_VER >=1940 && _MSC_VER < 1950 && (defined(_M_X64 )|| defined(_M_IX86 )) 113constexpr bool kRegenHere = true; 114#else 115constexpr bool kRegenHere = false; 116#endif 117#else 118const char * const kFamily = "gcc" ; 119#if defined(__GNUC__ )&& !defined(__clang__ )&& __GNUC__ == 13 && (defined(__x86_64__ )|| defined(__i386__ )) 120constexpr bool kRegenHere = true; 121#else 122constexpr bool kRegenHere = false; 123#endif 124#endif 125constexpr int kGoldenRows = 24 ;// the golden file holds the default --rows 126 127sq::Arith oracle_arith () { 128#if defined(__aarch64__ ) 129return sq::Arith ::Neon ; 130#else 131if (ggml_cpu_has_avx2 ()&& ggml_cpu_has_fma ())return sq::Arith ::Avx2 ; 132if (ggml_cpu_has_avx ())return sq::Arith ::Avx ; 133return sq::Arith ::Generic ; 134#endif 135} 136 137int g_fail = 0 ,g_checked = 0 ,g_live_diff = 0 ,g_group_checks = 0 ;// rows compared (x kernels), live rows that differ, golden group checks 138bool g_info_only = false;// the oracle is a flavour the layer does not claim (arm64 with SVE): count the differences, do not fail 139bool g_verbose = false; 140bool g_golden_leg = false;// leg 1 runs (a golden section for this flavour, default --rows) 141bool g_live_strict = false;// leg 2's differences fail (no golden here, or QUANT_PARITY_LIVE_STRICT=1) 142std::string g_flavour ;// arith_name of the contract checked 143std::string g_dump_key ;// --dump-group 144 145void fail (const char * what ,const std::string & detail ) { 146++ g_fail ; 147if (g_fail <=40 ) std::printf ("FAIL %s: %s\n" ,what ,detail .c_str ()); 148} 149 150// leg 2: a row where the linked ggml and ours differ 151void live_diff (const char * what ,const std::string & detail ) { 152++ g_live_diff ; 153if (g_live_strict )fail (what ,detail ); 154else if (g_live_diff <=10 ) std::printf ("live: %s: %s\n" ,what ,detail .c_str ()); 155} 156 157std::string hex_bytes (const void * p ,size_t n ) { 158static const char * d = "0123456789abcdef" ; 159 std::string s ; 160const unsigned char * b = (const unsigned char * )p ; 161for (size_t i = 0 ;i < n ;++ i ) { 162s += d [b [i ] >>4 ]; 163s += d [b [i ]& 15 ]; 164 } 165return s ; 166} 167 168std::string hex64 (uint64_t v ) { 169char b [20 ]; 170 std::snprintf (b ,sizeof b ,"%016llx" , (unsigned long long )v ); 171return b ; 172} 173 174// ---- golden file (tests/quant/golden_x86.txt): lines "<family> <flavour> <section> <name> <n> <rows> <input digest> <reference digest>"; 175// "%note <family> <flavour> <section> <name> <why>" lines say why a family has its own lines; '#' lines are comments (the header) 176struct GoldenLine { 177int rows ; 178uint64_t in ,out ; 179 std::string text ;// the line without its family, as --write-golden writes it 180}; 181std::map < std::string ,GoldenLine > g_golden ;// this flavour's gcc lines, by key "<flavour> <section> <name> <n>" 182std::map < std::string ,GoldenLine > g_golden_own ;// this flavour's lines of this build's family when it is not gcc (the per-toolchain lines) 183std::vector < std::string > g_golden_gcc_order ;// the gcc keys in stored order (--regen-check under GCC 13) 184std::vector < std::string > g_notes ;// "%note" lines of this family and flavour 185 186bool load_golden (const std::string & path ,const std::string & flavour ) { 187 std::ifstream f (path ); 188if (!f )return false; 189 std::string line ; 190while (std::getline (f ,line )) { 191if (!line .empty ()&& line .back ()== '\r' )line .pop_back (); 192if (line .empty ()|| line [0 ]== '#' )continue ; 193 std::istringstream ss (line ); 194 std::string fam ,fl ,sec ,name ,n ,in ,out ; 195if (line [0 ]== '%' ) { 196 std::string tag ; 197ss >>tag >>fam >>fl ; 198if (fam == kFamily && fl == flavour )g_notes .push_back (line .substr (6 )); 199continue ; 200 } 201int rows = 0 ; 202if (!(ss >>fam >>fl >>sec >>name >>n >>rows >>in >>out )) { 203 std::printf ("quant_parity: malformed golden line: %s\n" ,line .c_str ()); 204 std::exit (2 ); 205 } 206if (fl != flavour )continue ; 207const std::string key = fl + " " + sec + " " + name + " " + n ; 208GoldenLine gl = {rows , std::strtoull (in .c_str (),nullptr ,16 ), std::strtoull (out .c_str (),nullptr ,16 ),line .substr (fam .size ()+ 1 )}; 209if (fam == "gcc" ) { 210g_golden [key ]= gl ; 211g_golden_gcc_order .push_back (key ); 212 }else if (fam == kFamily ) { 213g_golden_own [key ]= gl ; 214 } 215 } 216return true; 217} 218 219// the line this build is held to: its family's own line where one exists, else the gcc line 220const GoldenLine * golden_for (const std::string & key ) { 221auto own = g_golden_own .find (key ); 222if (own != g_golden_own .end ())return & own -> second ; 223auto it = g_golden .find (key ); 224return it == g_golden .end () ?nullptr :& it -> second ; 225} 226 227// one group of comparisons: the inputs and the reference (the linked ggml) are digested once, each kernel's results against them 228struct Group { 229 std::string key ,name ; 230int rows = 0 ; 231uint64_t in = kFnvBasis ,ref = kFnvBasis ; 232}; 233std::vector < Group > g_groups ;// visiting order = the order of the golden lines 234std::map < std::string ,int > g_groups_by_key ; 235std::vector < std::string > g_ref_moved ;// leg 2: groups where the linked ggml differs from golden 236 237Group & open_group (const char * section ,const char * name ,int n ) { 238const std::string key = g_flavour + " " + section + " " + name + " " + std::to_string (n ); 239g_groups .push_back (Group ()); 240Group & g = g_groups .back (); 241g .key = key ; 242g .name = name ; 243g_groups_by_key [key ]= (int )g_groups .size ()- 1 ; 244return g ; 245} 246 247// close a group: the reference against golden (leg 2's summary), and every kernel's digest against golden (leg 1) 248void close_group (Group & g ,const std::vector < std::pair < const char * ,uint64_t >>& ours ) { 249if (!g_golden_leg )return ; 250const GoldenLine * gp = golden_for (g .key ); 251if (gp == nullptr ) { 252fail (g .name .c_str (),"group \"" + g .key + "\" has no golden line (a new case: regenerate tests/quant/golden_x86.txt, tests/quant/make_golden.sh)" ); 253return ; 254 } 255const GoldenLine & gl = * gp ; 256if (gl .in != g .in || gl .rows != g .rows ) { 257fail (g .name .c_str (),"group \"" + g .key + "\": the INPUTS differ from the golden file's (" + std::to_string (g .rows )+ " rows, digest " + hex64 (g .in )+ 258"; golden " + std::to_string (gl .rows )+ " rows, " + hex64 (gl .in )+ "): ggml's quantizers that make the test rows moved here" ); 259return ; 260 } 261if (gl .out != g .ref )g_ref_moved .push_back (g .key ); 262for (const auto & k :ours ) { 263++ g_group_checks ; 264if (k .second != gl .out ) 265fail (g .name .c_str (), std::string ("kernel " )+ k .first + ": group \"" + g .key + "\" differs from the golden reference (ours " + hex64 (k .second )+ 266", golden " + hex64 (gl .out )+ "); rows: --dump-group \"" + g .key + "\"" ); 267 } 268} 269 270void dump_row (const Group & g ,const char * who ,int idx ,uint64_t in ,const void * out ,size_t n ) { 271if (g .key == g_dump_key ) std::printf ("ROW %s %s %d %s %s\n" ,g .key .c_str (),who ,idx ,hex64 (in ).c_str (),hex_bytes (out ,n ).c_str ()); 272} 273 274// weights of `type`, `nrows` rows of n elements, quantized by ggml from gaussian floats of scale `amp` 275std::vector < uint8_t > make_rows (ggml_type type ,int n ,int nrows ,Rng & r ,float amp ) { 276ggml_quantize_init (type ); 277 std::vector < float > f ((size_t )n * nrows ),im ((size_t )n ,1.0f ); 278for (float & v :f )v = r .gauss ()* amp ; 279 std::vector < uint8_t > out (ggml_row_size (type ,n )* nrows ); 280const size_t got = ggml_quantize_chunk (type ,f .data (),out .data (),0 ,nrows ,n ,ggml_quantize_requires_imatrix (type ) ?im .data () :nullptr ); 281if (got != out .size ()) { 282 std::printf ("quantize_chunk(%s) returned %zu, expected %zu\n" ,ggml_type_name (type ),got ,out .size ()); 283 std::exit (2 ); 284 } 285return out ; 286} 287 288bool bits_equal (float a ,float b ) {return std::memcmp (& a ,& b ,4 )== 0 ; } 289 290uint32_t float_bits (float f ) { 291uint32_t u ; 292 std::memcpy (& u ,& f ,4 ); 293return u ; 294} 295 296void test_dot (sq::Type st ,int rows ) { 297const ggml_type gt = (ggml_type ) (int )st ; 298const sq::TypeInfo * ti = sq::type_info (st ); 299const ggml_type_traits_cpu * tr = ggml_get_type_traits_cpu (gt ); 300if (ti == nullptr || tr == nullptr || tr -> vec_dot == nullptr )return ; 301const sq::Arith ar = oracle_arith (); 302// ggml's SSE4.2-only flavour (STRATA_ISA_FLOOR=none) has an SSSE3 branch for Q4_0 that is neither the generic C code nor AVX: not a contract of the layer 303if (ar == sq::Arith ::Generic && st == sq::Type ::Q4_0 ) { 304 std::printf (" dot q4_0 skipped: ggml's SSSE3 branch is not the Generic contract\n" ); 305return ; 306 } 307const sq::DotKernel * ks [16 ]; 308const int nk = sq::dot_kernels (st ,ar ,ks ,16 ); 309const ggml_type_traits_cpu * ta = ggml_get_type_traits_cpu (tr -> vec_dot_type ); 310if ((int )tr -> vec_dot_type != (int )ti -> act ) { 311fail (ti -> name ,"vec_dot_type differs from the layer's type table" ); 312return ; 313 } 314if ((int )ggml_blck_size (gt )!= ti -> blck || ggml_type_size (gt )!= ti -> bytes )fail (ti -> name ,"block geometry differs from ggml's" ); 315 std::vector < const sq::DotKernel *> run ; 316for (int ki = 0 ;ki < nk ;++ ki ) 317if (sq::isa_ok (ks [ki ]-> isa ))run .push_back (ks [ki ]); 318const int unit = ti -> blck > (int )ggml_blck_size (tr -> vec_dot_type ) ?ti -> blck : (int )ggml_blck_size (tr -> vec_dot_type ); 319Rng r (1234 + (uint64_t )st ); 320 std::vector < int > live_bad (run .size (),0 ); 321for (int nbk = 1 ;nbk <=8 ;++ nbk ) { 322const int n = unit * nbk ; 323const float amp = nbk %3 == 0 ?0.02f : (nbk %3 == 1 ?1.0f :40.0f ); 324const std::vector < uint8_t > w = make_rows (gt ,n ,rows ,r ,amp ); 325const size_t wrow = ggml_row_size (gt ,n ),arow = ggml_row_size (tr -> vec_dot_type ,n ); 326 std::vector < float > xf ((size_t )n ); 327 std::vector < uint8_t > act (arow * 3 ); 328for (int rep = 0 ;rep < 3 ;++ rep ) { 329for (float & v :xf )v = r .gauss ()* (rep == 0 ?1.f : (rep == 1 ?0.05f :7.f )); 330ta -> from_float (xf .data (),act .data ()+ arow * rep ,n ); 331 } 332Group & g = open_group ("dot" ,ti -> name ,n ); 333 std::vector < float > want ((size_t )3 * rows ); 334for (int rep = 0 ;rep < 3 ;++ rep ) 335for (int row = 0 ;row < rows ;++ row ) { 336const uint8_t * wr = w .data ()+ (size_t )row * wrow ; 337const uint8_t * ar_ = act .data ()+ arow * rep ; 338float & o = want [(size_t )rep * rows + row ]; 339tr -> vec_dot (n ,& o ,0 ,wr ,0 ,ar_ ,0 ,1 ); 340const uint64_t rin = golden_fnv1a64 (ar_ ,arow ,golden_fnv1a64 (wr ,wrow )); 341g .in = golden_fnv1a64 (ar_ ,arow ,golden_fnv1a64 (wr ,wrow ,g .in )); 342g .ref = golden_fnv1a64 (& o ,4 ,g .ref ); 343++ g .rows ; 344dump_row (g ,"ggml" ,rep * 1000 + row ,rin ,& o ,4 ); 345 } 346 std::vector < std::pair < const char * ,uint64_t >> ours ; 347for (size_t ki = 0 ;ki < run .size ();++ ki ) { 348const sq::DotKernel * k = run [ki ]; 349uint64_t h = kFnvBasis ; 350for (int rep = 0 ;rep < 3 ;++ rep ) 351for (int row = 0 ;row < rows ;++ row ) { 352const uint8_t * wr = w .data ()+ (size_t )row * wrow ; 353const uint8_t * ar_ = act .data ()+ arow * rep ; 354float got = 0.f ; 355k -> fn (n ,& got ,wr ,ar_ ); 356h = golden_fnv1a64 (& got ,4 ,h ); 357if (!g_dump_key .empty ())dump_row (g ,k -> name ,rep * 1000 + row ,golden_fnv1a64 (ar_ ,arow ,golden_fnv1a64 (wr ,wrow )),& got ,4 ); 358const float wv = want [(size_t )rep * rows + row ]; 359++ g_checked ; 360if (!bits_equal (wv ,got )&& live_bad [ki ]++ < 1 ) { 361char b [220 ]; 362 std::snprintf (b ,sizeof b ,"kernel %s n=%d row %d: ggml %.9g (%08x) ours %.9g (%08x)" ,k -> name ,n ,rep * 1000 + row ,wv , 363float_bits (wv ),got ,float_bits (got )); 364live_diff (ti -> name ,b ); 365 }else if (!bits_equal (wv ,got )) { 366live_diff (ti -> name , std::string ("kernel " )+ k -> name + " n=" + std::to_string (n )+ " row " + std::to_string (rep * 1000 + row )); 367 } 368 } 369ours .emplace_back (k -> name ,h ); 370 } 371close_group (g ,ours ); 372 } 373if (g_verbose ) 374for (const sq::DotKernel * k :run ) std::printf (" dot %-10s %-18s (%s/%s) done\n" ,ti -> name ,k -> name , sq::arith_name (k -> arith ), sq::isa_name (k -> isa )); 375if (run .empty ()&& g_verbose ) std::printf (" dot %-10s no kernel of contract %s runs here\n" ,ti -> name , sq::arith_name (ar )); 376if (run .empty ()&& nk == 0 )fail (ti -> name , std::string ("the layer has no kernel of contract " )+ sq::arith_name (ar )); 377} 378 379void test_act (sq::Type act ,int rows ) { 380const ggml_type gt = (ggml_type ) (int )act ; 381const ggml_type_traits_cpu * tr = ggml_get_type_traits_cpu (gt ); 382const sq::TypeInfo * ti = sq::type_info (act ); 383if (tr == nullptr || tr -> from_float == nullptr || ti == nullptr )return ; 384const sq::Arith ar = oracle_arith (); 385const sq::ActKernel * k = sq::act_kernel (act ,ar ); 386if (k == nullptr || k -> arith != ar ) { 387fail (ti -> name , std::string ("no activation quantizer of contract " )+ sq::arith_name (ar )); 388return ; 389 } 390Rng r (777 + (uint64_t )act ); 391for (int nbk = 1 ;nbk <=6 ;++ nbk ) { 392const int n = ti -> blck * nbk ; 393Group & g = open_group ("act" ,ti -> name ,n ); 394uint64_t h = kFnvBasis ; 395bool reported = false; 396 std::vector < float > x ((size_t )n ); 397 std::vector < uint8_t > a (ti -> bytes * nbk ),b (ti -> bytes * nbk ); 398for (int it = 0 ;it < rows * 4 ;++ it ) { 399for (float & v :x )v = r .gauss ()* (it %3 == 0 ?1.f : (it %3 == 1 ?1e-3f :300.f )); 400if (it %7 == 0 ) std::memset (x .data (),0 ,x .size ()* 4 );// an all-zero block 401if (it %11 == 0 )x [(size_t ) (r .next () %n )]= 0.f ; 402// ties: a block whose absolute maximum is 127 (id = 1) with half-integers elsewhere, and its negation 403if (it %5 == 0 ) { 404// one draw per statement (see Rng::gauss): two r.next() in one expression gave MSVC other inputs than GCC 405for (int j = 0 ;j < n ;++ j ) { 406const int q = (int ) (r .next () %255 )- 127 ; 407const float half = r .next ()& 1 ?0.f :0.5f ; 408x [(size_t )j ]= q * 0.5f + half ; 409 } 410for (int bI = 0 ;bI < nbk ;++ bI ) { 411const uint32_t at = r .next () %ti -> blck ; 412x [(size_t )bI * ti -> blck + at ]= r .next ()& 1 ?127.f :-127.f ; 413 } 414if (act == sq::Type ::Q8_K )for (int bI = 0 ;bI < nbk ;++ bI )x [(size_t )bI * ti -> blck + r .next () %ti -> blck ]= 127.f ; 415 } 416// pre-filled: Q8_K leaves an all-zero block's 16 block sums unwritten (ggml and the layer alike); without this they carry an earlier row's bytes 417 std::memset (a .data (),0 ,a .size ()); 418 std::memset (b .data (),0 ,b .size ()); 419tr -> from_float (x .data (),a .data (),n ); 420k -> fn (x .data (),b .data (),n ); 421const uint64_t rin = golden_fnv1a64 (x .data (),x .size ()* 4 ); 422g .in = golden_fnv1a64 (x .data (),x .size ()* 4 ,g .in ); 423g .ref = golden_fnv1a64 (a .data (),a .size (),g .ref ); 424h = golden_fnv1a64 (b .data (),b .size (),h ); 425++ g .rows ; 426dump_row (g ,"ggml" ,it ,rin ,a .data (),a .size ()); 427dump_row (g ,k -> name ,it ,rin ,b .data (),b .size ()); 428++ g_checked ; 429if (std::memcmp (a .data (),b .data (),a .size ())!= 0 && !reported ) { 430reported = true; 431size_t at = 0 ; 432while (a [at ]== b [at ])++ at ; 433char buf [160 ]; 434 std::snprintf (buf ,sizeof buf ,"kernel %s n=%d iteration %d: first differing byte %zu (ggml %02x ours %02x)" ,k -> name ,n ,it ,at ,a [at ],b [at ]); 435live_diff (ti -> name ,buf ); 436 } 437 } 438close_group (g , {{k -> name ,h }}); 439 } 440if (g_verbose ) std::printf (" act %-10s %-18s done\n" ,ti -> name ,k -> name ); 441} 442 443// to_float of every type the layer dequantizes, and the Q4_0 requantizer (--mtp-q4's output), bit for bit against ggml-base 444void test_dequant (int rows ) { 445static const sq::Type kTypes []= {sq::Type ::Q2_0 , sq::Type ::Q4_0 , sq::Type ::Q4_1 , sq::Type ::Q5_0 , sq::Type ::Q5_1 , sq::Type ::Q8_0 , sq::Type ::MXFP4 , 446 sq::Type ::NVFP4 , sq::Type ::Q2_K , sq::Type ::Q3_K , sq::Type ::Q4_K , sq::Type ::Q5_K , sq::Type ::Q6_K , sq::Type ::IQ2_XXS , 447 sq::Type ::IQ2_XS , sq::Type ::IQ2_S , sq::Type ::IQ3_XXS , sq::Type ::IQ3_S , sq::Type ::IQ1_S , sq::Type ::IQ1_M , 448 sq::Type ::IQ4_NL , sq::Type ::IQ4_XS }; 449for (sq::Type st :kTypes ) { 450const ggml_type gt = (ggml_type ) (int )st ; 451const ggml_type_traits * tr = ggml_get_type_traits (gt ); 452const sq::TypeInfo * ti = sq::type_info (st ); 453if (tr == nullptr || tr -> to_float == nullptr )continue ; 454if (!sq::can_dequant (st )) { 455fail (ti -> name ,"the layer cannot dequantize it" ); 456continue ; 457 } 458Rng r (321 + (uint64_t )st ); 459for (int nbk = 1 ;nbk <=4 ;++ nbk ) { 460const int n = ti -> blck * nbk ; 461const std::vector < uint8_t > w = make_rows (gt ,n ,rows ,r ,nbk %2 ?1.0f :30.0f ); 462Group & g = open_group ("deq" ,ti -> name ,n ); 463uint64_t h = kFnvBasis ; 464bool reported = false; 465 std::vector < float > a ((size_t )n ),b ((size_t )n ); 466for (int row = 0 ;row < rows ;++ row ) { 467const uint8_t * wr = w .data ()+ (size_t )row * ggml_row_size (gt ,n ); 468tr -> to_float (wr ,a .data (),n ); 469 std::memset (b .data (),0 ,b .size ()* 4 ); 470const bool ok = sq::dequant_row (st ,wr ,b .data (),n ); 471const uint64_t rin = golden_fnv1a64 (wr ,ggml_row_size (gt ,n )); 472g .in = golden_fnv1a64 (wr ,ggml_row_size (gt ,n ),g .in ); 473g .ref = golden_fnv1a64 (a .data (),a .size ()* 4 ,g .ref ); 474h = golden_fnv1a64 (b .data (),b .size ()* 4 ,h ); 475++ g .rows ; 476++ g_checked ; 477dump_row (g ,"ggml" ,row ,rin ,a .data (),a .size ()* 4 ); 478dump_row (g ,"dequant_row" ,row ,rin ,b .data (),b .size ()* 4 ); 479if (!ok ) { 480fail (ti -> name ,"dequant_row refused n=" + std::to_string (n )); 481break ; 482 } 483if (std::memcmp (a .data (),b .data (),a .size ()* 4 )!= 0 && !reported ) { 484reported = true; 485live_diff (ti -> name ,"dequant_row differs from ggml's to_float, n=" + std::to_string (n )+ " row " + std::to_string (row )); 486 } 487 } 488close_group (g , {{"dequant_row" ,h }}); 489 } 490 } 491// Q4_0 from floats: ggml_quantize_chunk(Q4_0, no imatrix) is quantize_row_q4_0_ref 492Rng r (99 ); 493for (int nbk = 1 ;nbk <=6 ;++ nbk ) { 494const int n = 32 * nbk ; 495Group & g = open_group ("rq4" ,"q4_0" ,n ); 496uint64_t h = kFnvBasis ; 497bool reported = false; 498 std::vector < float > f ((size_t )n ); 499 std::vector < uint8_t > a (18 * nbk ),b (18 * nbk ); 500for (int it = 0 ;it < rows * 4 ;++ it ) { 501for (float & v :f )v = r .gauss ()* (it %3 == 0 ?1.f : (it %3 == 1 ?1e-3f :200.f )); 502if (it %9 == 0 ) std::memset (f .data (),0 ,f .size ()* 4 ); 503ggml_quantize_chunk (GGML_TYPE_Q4_0 ,f .data (),a .data (),0 ,1 ,n ,nullptr ); 504 sq::quantize_q4_0_ref (f .data (),b .data (),n ); 505const uint64_t rin = golden_fnv1a64 (f .data (),f .size ()* 4 ); 506g .in = golden_fnv1a64 (f .data (),f .size ()* 4 ,g .in ); 507g .ref = golden_fnv1a64 (a .data (),a .size (),g .ref ); 508h = golden_fnv1a64 (b .data (),b .size (),h ); 509++ g .rows ; 510dump_row (g ,"ggml" ,it ,rin ,a .data (),a .size ()); 511dump_row (g ,"quantize_q4_0_ref" ,it ,rin ,b .data (),b .size ()); 512++ g_checked ; 513if (a != b && !reported ) { 514reported = true; 515live_diff ("q4_0" ,"quantize_q4_0_ref differs from ggml_quantize_chunk, n=" + std::to_string (n )+ " iteration " + std::to_string (it )); 516 } 517 } 518close_group (g , {{"quantize_q4_0_ref" ,h }}); 519 } 520} 521 522// Values within a few ulps of the rounding boundaries of the Q8_K quantizer (nearest_int adds the 2^23 + 2^22 magic number to iscale * x) and of the Q4_0 523// requantizer (x * id + 8.5, truncated). A compiler that contracts the multiply and the add into one FMA gives another result on exactly these inputs, and 524// ggml-base does so on arm64 under GCC (not on x86), so random data finds the mismatch only after millions of values: this finds it in a few thousand. 525void test_boundary (int rows ) { 526Rng r (4242 ); 527const sq::Arith ar = oracle_arith (); 528const sq::ActKernel * k8 = sq::act_kernel (sq::Type ::Q8_K ,ar ); 529const ggml_type_traits_cpu * t8 = ggml_get_type_traits_cpu (GGML_TYPE_Q8_K ); 530auto jitter = [& r ](float v ) { 531for (uint32_t t = r .next () %4 ;t > 0 ;-- t )v = std::nextafter (v ,r .next ()& 1 ?INFINITY :- INFINITY ); 532return v ; 533 }; 534if (k8 != nullptr && t8 != nullptr ) { 535Group & g = open_group ("bnd" ,"q8_K" ,256 ); 536uint64_t h = kFnvBasis ; 537bool reported = false; 538 std::vector < float > x (256 ); 539 std::vector < uint8_t > a (sq::kBlockQ8_K ),b (sq::kBlockQ8_K ); 540for (int it = 0 ;it < rows * 300 ;++ it ) { 541const float m = 0.5f + 0.5f * std::fabs (r .uni ()); 542const int e = (int ) (r .next () %14 )- 7 ; 543const float dd = std::ldexp (m ,e ); 544const float x0 = (r .next ()& 1 ?127.f :-127.f )* dd ; 545const float step = -1.f / (-127.f /x0 ); 546x [0 ]= x0 ; 547for (int j = 1 ;j < 256 ;++ j )x [(size_t )j ]= jitter (((int ) (r .next () %253 )- 126 + 0.5f )* step ); 548 std::memset (a .data (),0 ,a .size ()); 549 std::memset (b .data (),0 ,b .size ()); 550t8 -> from_float (x .data (),a .data (),256 ); 551k8 -> fn (x .data (),b .data (),256 ); 552const uint64_t rin = golden_fnv1a64 (x .data (),x .size ()* 4 ); 553g .in = golden_fnv1a64 (x .data (),x .size ()* 4 ,g .in ); 554g .ref = golden_fnv1a64 (a .data (),a .size (),g .ref ); 555h = golden_fnv1a64 (b .data (),b .size (),h ); 556++ g .rows ; 557dump_row (g ,"ggml" ,it ,rin ,a .data (),a .size ()); 558dump_row (g ,k8 -> name ,it ,rin ,b .data (),b .size ()); 559++ g_checked ; 560if (a != b && !reported ) { 561reported = true; 562live_diff ("q8_K" ,"boundary values: the quantizer differs from ggml's (a fused multiply-add on one side), iteration " + std::to_string (it )); 563 } 564 } 565close_group (g , {{k8 -> name ,h }}); 566 } 567Group & g = open_group ("bnd" ,"q4_0" ,32 ); 568uint64_t h = kFnvBasis ; 569bool reported = false; 570 std::vector < float > x (32 ); 571 std::vector < uint8_t > a (18 ),b (18 ); 572for (int it = 0 ;it < rows * 300 ;++ it ) { 573const float m = 0.5f + 0.5f * std::fabs (r .uni ()); 574const int e = (int ) (r .next () %14 )- 7 ; 575const float dd = std::ldexp (m ,e ); 576x [0 ]= -8.f * dd ; 577for (int j = 1 ;j < 32 ;++ j )x [(size_t )j ]= jitter (((int ) (r .next () %15 )+ 1 - 8.5f )* dd ); 578ggml_quantize_chunk (GGML_TYPE_Q4_0 ,x .data (),a .data (),0 ,1 ,32 ,nullptr ); 579 sq::quantize_q4_0_ref (x .data (),b .data (),32 ); 580const uint64_t rin = golden_fnv1a64 (x .data (),x .size ()* 4 ); 581g .in = golden_fnv1a64 (x .data (),x .size ()* 4 ,g .in ); 582g .ref = golden_fnv1a64 (a .data (),a .size (),g .ref ); 583h = golden_fnv1a64 (b .data (),b .size (),h ); 584++ g .rows ; 585dump_row (g ,"ggml" ,it ,rin ,a .data (),a .size ()); 586dump_row (g ,"quantize_q4_0_ref" ,it ,rin ,b .data (),b .size ()); 587++ g_checked ; 588if (a != b && !reported ) { 589reported = true; 590live_diff ("q4_0" ,"boundary values: quantize_q4_0_ref differs from ggml's (a fused multiply-add on one side), iteration " + std::to_string (it )); 591 } 592 } 593close_group (g , {{"quantize_q4_0_ref" ,h }}); 594} 595 596void test_fp16 () { 597// our software fp16 conversions against ggml's, every fp16 value and a spread of floats (one group, two rows: the two directions) 598Group & g = open_group ("fp16" ,"fp16" ,0 ); 599int bad = 0 ; 600uint64_t h = kFnvBasis ; 601for (uint32_t hv = 0 ;hv < 65536 ;++ hv ) { 602const uint16_t u = (uint16_t )hv ; 603const float a = ggml_fp16_to_fp32 ((ggml_fp16_t )u ); 604const float b = sq::fp16_to_fp32 (u ); 605g .in = golden_fnv1a64 (& u ,2 ,g .in ); 606g .ref = golden_fnv1a64 (& a ,4 ,g .ref ); 607h = golden_fnv1a64 (& b ,4 ,h ); 608if (std::isnan (a ) ? !std::isnan (b ) : !bits_equal (a ,b ))++ bad ; 609 } 610++ g .rows ; 611Rng r (5 ); 612for (int i = 0 ;i < 4000000 ;++ i ) { 613uint32_t w = r .next (); 614float f ; 615 std::memcpy (& f ,& w ,4 ); 616if (std::isnan (f ))continue ; 617const uint16_t a = ggml_fp32_to_fp16 (f ),b = sq::fp32_to_fp16 (f ); 618g .in = golden_fnv1a64 (& f ,4 ,g .in ); 619g .ref = golden_fnv1a64 (& a ,2 ,g .ref ); 620h = golden_fnv1a64 (& b ,2 ,h ); 621if (a != b )++ bad ; 622 } 623++ g .rows ; 624++ g_checked ; 625if (bad )live_diff ("fp16" , std::to_string (bad )+ " conversions differ from ggml's" ); 626close_group (g , {{"fp16" ,h }}); 627} 628 629std::string golden_lines_of_this_run () { 630 std::string s ; 631for (const Group & g :g_groups )s += g .key + " " + std::to_string (g .rows )+ " " + hex64 (g .in )+ " " + hex64 (g .ref )+ "\n" ; 632return s ; 633} 634 635}// namespace 636 637int main (int argc ,char ** argv ) { 638int rows = kGoldenRows ; 639const char * only = nullptr ; 640 std::string golden_path = STRATA_QUANT_GOLDEN_FILE ,write_golden ; 641bool regen_check = false; 642for (int i = 1 ;i < argc ;++ i ) { 643if (!std::strcmp (argv [i ],"--rows" )&& i + 1 < argc )rows = std::atoi (argv [++ i ]); 644else if (!std::strcmp (argv [i ],"--type" )&& i + 1 < argc )only = argv [++ i ]; 645else if (!std::strcmp (argv [i ],"--verbose" ))g_verbose = true; 646else if (!std::strcmp (argv [i ],"--golden" )&& i + 1 < argc )golden_path = argv [++ i ]; 647else if (!std::strcmp (argv [i ],"--dump-group" )&& i + 1 < argc )g_dump_key = argv [++ i ]; 648else if (!std::strcmp (argv [i ],"--write-golden" )&& i + 1 < argc )write_golden = argv [++ i ]; 649else if (!std::strcmp (argv [i ],"--regen-check" ))regen_check = true; 650else { 651 std::printf ("quant_parity: unknown argument %s\n" ,argv [i ]); 652return 2 ; 653 } 654 } 655if (!digest_selftest ()) { 656 std::printf ("quant_parity: FAIL: the golden digest (FNV-1a 64) does not give its test vectors\n" ); 657return 1 ; 658 } 659if (regen_check && !kRegenHere ) { 660 std::printf ("quant_parity --regen-check: SKIPPED: the golden lines are made by GCC 13.x (family gcc) and MSVC 19.4x (family msvc) on x86; this is %s\n" , 661compiler_name ().c_str ()); 662return 77 ; 663 } 664ggml_cpu_init (); 665const sq::Arith ar = oracle_arith (); 666g_flavour = sq::arith_name (ar ); 667 std::printf ("quant_parity: oracle flavour %s (ggml avx=%d avx2=%d fma=%d f16c=%d avx512=%d), layer best isa %s, default contract %s, compiler %s\n" , 668 sq::arith_name (ar ),ggml_cpu_has_avx (),ggml_cpu_has_avx2 (),ggml_cpu_has_fma (),ggml_cpu_has_f16c (),ggml_cpu_has_avx512 (), 669 sq::isa_name (sq::best_isa ()), sq::arith_name (sq::default_arith ()),compiler_name ().c_str ()); 670#if defined(__aarch64__ ) 671// The Neon contract is ggml-cpu's arm64 flavour with the dot product extension (the shipped STRATA_PORTABLE build and the Mac's native build). A ggml-cpu without it 672// (GCC's -mcpu=native on the Spark's mixed X925 + A725 cores resolves to plain armv8-a) runs other code, and one with SVE other branches of the Q4_0 / Q8_0 / 673// K-quant dots: those flavours are not the contract. The first is skipped, the second is run for information and its differences do not fail the test. 674if (!ggml_cpu_has_dotprod ()) { 675 std::printf ("quant_parity: SKIPPED, this ggml-cpu is built without the dot product extension (not the Neon contract)\n" ); 676return 0 ; 677 } 678if (ggml_cpu_has_sve ()) { 679g_info_only = true; 680 std::printf ("quant_parity: this ggml-cpu is built with SVE (not the Neon contract): differences are reported, not failed\n" ); 681 } 682#endif 683const bool have_golden = !golden_path .empty ()&& load_golden (golden_path ,g_flavour )&& !g_golden .empty (); 684g_golden_leg = have_golden && rows == kGoldenRows && write_golden .empty (); 685const char * strict_env = std::getenv ("QUANT_PARITY_LIVE_STRICT" ); 686g_live_strict = !g_golden_leg || (strict_env != nullptr && std::strcmp (strict_env ,"0" )!= 0 && * strict_env != '\0' ); 687if (regen_check && !have_golden ) { 688 std::printf ("quant_parity --regen-check: FAIL: no golden lines for flavour %s in %s\n" ,g_flavour .c_str (),golden_path .c_str ()); 689return 1 ; 690 } 691if (regen_check && rows != kGoldenRows ) { 692 std::printf ("quant_parity --regen-check: FAIL: the golden file holds --rows %d\n" ,kGoldenRows ); 693return 1 ; 694 } 695if (g_golden_leg ) { 696 std::printf ("quant_parity: leg 1 (gate): ours against the golden reference, %zu groups of flavour %s (%s); leg 2 (%s): ours against the ggml-cpu linked here\n" , 697g_golden .size (),g_flavour .c_str (),golden_path .c_str (),g_live_strict ?"FATAL, QUANT_PARITY_LIVE_STRICT" :"information" ); 698if (!g_golden_own .empty ()) { 699 std::printf ("quant_parity: toolchain family %s has its own golden lines for %zu groups of flavour %s:" ,kFamily ,g_golden_own .size (),g_flavour .c_str ()); 700for (const auto & kv :g_golden_own ) std::printf (" %s;" ,kv .first .c_str ()); 701 std::printf ("\n" ); 702for (const std::string & n :g_notes ) std::printf ("quant_parity: why: %s\n" ,n .c_str ()); 703 } 704 } 705else 706 std::printf ("quant_parity: no golden reference for flavour %s%s: the gate is ours against the ggml-cpu linked here\n" ,g_flavour .c_str (), 707have_golden ?" at this --rows" : (golden_path .empty () ?"" : (" in " + golden_path ).c_str ())); 708test_fp16 (); 709test_dequant (rows ); 710test_boundary (rows ); 711for (sq::Type a : {sq::Type ::Q8_0 , sq::Type ::Q8_1 , sq::Type ::Q8_K }) 712if (only == nullptr || !std::strcmp (only , sq::type_info (a )-> name ))test_act (a ,rows ); 713static const sq::Type kTypes []= {sq::Type ::Q2_0 , sq::Type ::Q4_0 , sq::Type ::Q4_1 , sq::Type ::Q5_0 , sq::Type ::Q5_1 , sq::Type ::Q8_0 , sq::Type ::IQ4_NL , 714 sq::Type ::MXFP4 , sq::Type ::NVFP4 , sq::Type ::Q2_K , sq::Type ::Q3_K , sq::Type ::Q4_K , sq::Type ::Q5_K , sq::Type ::Q6_K , 715 sq::Type ::IQ1_S , sq::Type ::IQ1_M , sq::Type ::IQ2_XXS , sq::Type ::IQ2_XS , sq::Type ::IQ2_S , sq::Type ::IQ3_XXS , 716 sq::Type ::IQ3_S , sq::Type ::IQ4_XS }; 717for (sq::Type t :kTypes ) 718if (only == nullptr || !std::strcmp (only , sq::type_info (t )-> name ))test_dot (t ,rows ); 719 720const std::string mine = golden_lines_of_this_run (); 721if (!write_golden .empty ()) { 722if (only != nullptr || rows != kGoldenRows ) { 723 std::printf ("quant_parity --write-golden: refused with --type or --rows (the golden file holds every group at --rows %d)\n" ,kGoldenRows ); 724return 2 ; 725 } 726FILE * f = std::fopen (write_golden .c_str (),"wb" ); 727const std::string head = "# made by " + compiler_name ()+ ", flavour " + g_flavour + ", " + std::to_string (g_groups .size ())+ " groups\n" ; 728if (f == nullptr || std::fwrite (head .data (),1 ,head .size (),f )!= head .size ()|| std::fwrite (mine .data (),1 ,mine .size (),f )!= mine .size ()|| 729 std::fclose (f )!= 0 ) { 730 std::printf ("quant_parity --write-golden: cannot write %s\n" ,write_golden .c_str ()); 731return 2 ; 732 } 733 std::printf ("quant_parity --write-golden: %zu groups of flavour %s written to %s (%s)\n" ,g_groups .size (),g_flavour .c_str (),write_golden .c_str (), 734compiler_name ().c_str ()); 735return 0 ; 736 } 737if (regen_check ) { 738if (only != nullptr ) { 739 std::printf ("quant_parity --regen-check: refused with --type\n" ); 740return 2 ; 741 } 742 std::string stored ; 743if (std::strcmp (kFamily ,"gcc" )== 0 ) { 744for (const std::string & k :g_golden_gcc_order )stored += g_golden [k ].text + "\n" ; 745 }else { 746// this family's own lines must regenerate, and every group without one must equal its gcc line (else MSVC differs in a new group: it needs a line) 747int own = 0 ; 748for (const Group & g :g_groups ) { 749const GoldenLine * gl = golden_for (g .key ); 750own += g_golden_own .count (g .key ) ?1 :0 ; 751stored += (gl ?gl -> text : std::string ("(no golden line for " )+ g .key + ")" )+ "\n" ; 752 } 753if (own != (int )g_golden_own .size ()) { 754 std::printf ("quant_parity --regen-check: FAIL: %zu %s lines of flavour %s stored, %d met\n" ,g_golden_own .size (),kFamily ,g_flavour .c_str (),own ); 755return 1 ; 756 } 757 } 758if (stored == mine ) { 759 std::printf ("quant_parity --regen-check: PASS: %s regenerates the stored lines of flavour %s byte for byte (family %s: %zu own lines; %zu groups)\n" , 760compiler_name ().c_str (),g_flavour .c_str (),kFamily , std::strcmp (kFamily ,"gcc" )== 0 ?g_golden .size () :g_golden_own .size (), 761g_groups .size ()); 762return 0 ; 763 } 764 std::istringstream a (stored ),b (mine ); 765 std::string la ,lb ; 766int ln = 0 ; 767while (true) { 768const bool ha = (bool ) std::getline (a ,la ),hb = (bool ) std::getline (b ,lb ); 769++ ln ; 770if (!ha && !hb )break ; 771if (!ha || !hb || la != lb ) { 772 std::printf ("quant_parity --regen-check: FAIL at flavour line %d:\n stored: %s\n regenerated: %s\n" ,ln ,ha ?la .c_str () :"(end)" , 773hb ?lb .c_str () :"(end)" ); 774break ; 775 } 776 } 777return 1 ; 778 } 779if (g_golden_leg && only == nullptr ) 780for (const auto & kv :g_golden )// every stored group of this flavour was met: a case that vanished does not pass silently 781if (g_groups_by_key .find (kv .first )== g_groups_by_key .end ())fail ("golden" ,"group \"" + kv .first + "\" of the golden file was not run" ); 782if (g_golden_leg ) { 783 std::printf ("quant_parity: leg 2 (%s): %d rows differ from the ggml-cpu linked here (%s); that ggml differs from the golden reference in %zu groups%s" , 784g_live_strict ?"FATAL" :"information" ,g_live_diff ,compiler_name ().c_str (),g_ref_moved .size (),g_ref_moved .empty () ?"\n" :":" ); 785for (size_t i = 0 ;i < g_ref_moved .size ();++ i ) std::printf ("%s %s" ,i ?"," :"" ,g_ref_moved [i ].c_str ()); 786if (!g_ref_moved .empty ()) std::printf ("\n" ); 787 } 788 std::printf ("quant_parity: %d comparisons, %d golden group checks, %d failures -> %s\n" ,g_checked ,g_group_checks ,g_fail ,g_fail ? (g_info_only ?"DIFFERENCES (information only)" :"FAIL" ) :"PASS" ); 789return (g_fail && !g_info_only ) ?1 :0 ; 790}