okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1// src/kernels/cpu/nvfp4_avx512_parity.cpp - the AVX-512 and AVX2 NVFP4 rows against ggml-cpu's own dot product. 2// 3// nvfp4_avx512_parity [pack/experts.bin] 4// 5// Parity: every row x every token of the multi-token kernel against ggml_vec_dot_nvfp4_q8_0 on the same Q8_0 6// activation. Both sum each 16-value sub-block exactly in integers; only the float additions are ordered differently, 7// so the check is a relative tolerance, not equality. Random blocks cover every code and a wide scale range; a real 8// expert (layer 0, expert 0 of a pack's experts.bin) covers the checkpoint's own distribution. 9// Also the down rows (n 640) and gate/up through silu with the blob tail's scales, 1..9 tokens (past one slice). 10// The AVX2 rows follow ggml's AVX2 path step for step, so for them every row must also be bit-equal (ggml-cpu built 11// with AVX2: STRATA_PORTABLE, or a native build). Each kernel is checked when this CPU runs it. 12// Speed: gate+up rows of one expert for 1..8 tokens, each way, as the CPU pool runs them. 13// 14// nvfp4_avx512_parity --bw THREADS TOKENS [ggml|avx2] 15// nvfp4_avx512_parity --expert pack/experts.bin [layer expert] 16// 17// --expert: one whole expert as decode runs it (Q8_0 input, gate/up + silu, Q8_0 of the hidden, down) against a 18// double-precision reference with the checkpoint's global scales, with s_down folded into up (the hidden becomes 19// ~1e-5 and its Q8_0 scale an FP16 subnormal) and with s_down applied to the output instead. 20// 21// DRAM rate: THREADS threads each run whole experts (gate/up through silu, then down) out of 4.2 GB of blobs - 22// 40x the L3 - for TOKENS tokens; GB/s of weights read. STRATA_NVFP4_PREFETCH sets the kernel's prefetch distance. 23#include "strata/kernels/cpu/expert_layout.hpp" 24#include "strata/kernels/cpu/nvfp4_avx2.hpp" 25#include "strata/kernels/cpu/nvfp4_avx512.hpp" 26 27#include "ggml.h" 28#include "ggml-cpu.h" 29 30#include <chrono> 31#include <cmath> 32#include <cstdio> 33#include <cstdlib> 34#include <cstring> 35#include <fstream> 36#include <random> 37#include <thread> 38#include <string> 39#include <vector> 40 41namespace { 42 43struct Kern { 44const char * name ; 45void (* gu )(const uint8_t * ,size_t ,size_t ,int ,const void * const * ,int ,float * const * ,int ,int ,float ,float ); 46void (* rows )(const uint8_t * ,size_t ,int ,const void * const * ,int ,float * const * ,int ,int ,float ); 47bool exact ;// bit-equal to ggml's AVX2 dot 48}; 49const Kern k512 {"avx512" , strata::kernels::cpu::nvfp4_512_gu_rows , strata::kernels::cpu::nvfp4_512_rows , false}; 50const Kern k256 {"avx2" , strata::kernels::cpu::nvfp4_256_gu_rows , strata::kernels::cpu::nvfp4_256_rows , true}; 51 52constexpr int N = 2560 ,ROWS = 1280 ,BLK = 36 ;// an expert's gate+up: 1280 rows of 2560 values 53constexpr int FF = 640 ;// its down: 2560 rows of 640 54constexpr size_t ROW_BYTES = (size_t )N /64 * BLK ,D_ROW = (size_t )FF /64 * BLK ; 55constexpr size_t BLOB = (size_t )ROWS * ROW_BYTES + (size_t )N * D_ROW + 16 ; 56 57double now_ms () { 58return std::chrono::duration < double , std::milli > (std::chrono::steady_clock::now ().time_since_epoch ()).count (); 59} 60 61struct Acts { 62 std::vector < std::vector < uint8_t >> q ; 63 std::vector < const void *> p ; 64Acts (int n ,int nt , std::mt19937 & rng ) :q (nt ),p (nt ) { 65const ggml_type_traits_cpu * ta = ggml_get_type_traits_cpu (GGML_TYPE_Q8_0 ); 66 std::normal_distribution < float > nd (0.f ,1.f ); 67 std::vector < float > x (n ); 68for (int t = 0 ;t < nt ;++ t ) { 69for (float & v :x )v = nd (rng )* (t + 1 );// several magnitudes 70q [t ].resize (ggml_row_size (GGML_TYPE_Q8_0 ,n )); 71ta -> from_float (x .data (),q [t ].data (),n ); 72p [t ]= q [t ].data (); 73 } 74 } 75}; 76 77float ref_dot (const uint8_t * row ,int n ,const void * a ) { 78float s = 0.f ; 79ggml_get_type_traits_cpu (GGML_TYPE_NVFP4 )-> vec_dot (n ,& s ,0 ,row ,0 ,a ,0 ,1 ); 80return s ; 81} 82 83int report (const std::vector < std::vector < float >>& mine ,const std::vector < std::vector < float >>& ref , 84int nt ,int rows ,double & worst ,int & differ ) { 85int bad = 0 ; 86for (int t = 0 ;t < nt ;++ t ) { 87double scale = 0 ; 88for (int r = 0 ;r < rows ;++ r )scale = std::fmax (scale , std::fabs (ref [t ][r ])); 89for (int r = 0 ;r < rows ;++ r ) { 90const double e = std::fabs ((double )mine [t ][r ]- ref [t ][r ]) / (scale > 0 ?scale :1 ); 91worst = std::fmax (worst ,e ); 92if (!(e <=1e-5 ))++ bad ; 93differ += std::memcmp (& mine [t ][r ],& ref [t ][r ],sizeof (float ))!= 0 ; 94 } 95 } 96return bad ; 97} 98 99// a kernel that claims bit equality fails on any differing row 100int verdict (const Kern & k ,const char * what ,double worst ,int rows ,int nt ,int bad ,int differ ) { 101 std::printf ("%-7s %-36s worst |mine - ggml| / max|ggml| = %.2e over %d rows x 1..%d tokens, %d beyond 1e-5, " 102"%d not bit-equal\n" ,k .name ,what ,worst ,rows ,nt ,bad ,differ ); 103#if defined(STRATA_TEST_GGML_WITHOUT_AVX2 ) 104// an older-CPU build (STRATA_ISA_FLOOR): ggml-cpu has no AVX2/FMA there, so its dot is not the AVX2 one these rows 105// follow; only the 1e-5 check counts 106if (k .exact ) 107 std::printf ("%-7s %-36s bit-equality not required (STRATA_ISA_FLOOR build: ggml-cpu without AVX2/FMA)\n" , 108k .name ,what ); 109return bad ; 110#else 111return bad + (k .exact ?differ :0 ); 112#endif 113} 114 115// plain rows: `rows` rows of `n` values, `row_bytes` apart 116int check_rows (const Kern & k ,const uint8_t * w ,int n ,size_t row_bytes ,int rows ,const char * what , 117 std::mt19937 & rng ) { 118constexpr int NT = 9 ;// past one slice: 9 = 5 + 4 119Acts a (n ,NT ,rng ); 120 std::vector < std::vector < float >> mine (NT , std::vector < float > (rows )),ref (NT , std::vector < float > (rows )); 121 std::vector < float *> op (NT ); 122for (int t = 0 ;t < NT ;++ t )op [t ]= mine [t ].data (); 123int bad = 0 ,differ = 0 ; 124double worst = 0 ; 125for (int nt = 1 ;nt <=NT ;++ nt ) { 126k .rows (w ,row_bytes ,n ,a .p .data (),nt ,op .data (),0 ,rows ,1.f ); 127for (int t = 0 ;t < nt ;++ t ) 128for (int r = 0 ;r < rows ;++ r )ref [t ][r ]= ref_dot (w + (size_t )r * row_bytes ,n ,a .p [t ]); 129bad += report (mine ,ref ,nt ,rows ,worst ,differ ); 130 } 131return verdict (k ,what ,worst ,rows ,NT ,bad ,differ ); 132} 133 134// gate/up with the blob tail's scales: silu(s_gate g) * (s_up u), as native_gu_rows' ggml path computes it 135int check_gu (const Kern & k ,const uint8_t * blob , std::mt19937 & rng ) { 136constexpr int NT = 9 ,F = ROWS /2 ; 137float tail [4 ]; 138 std::memcpy (tail ,blob + BLOB - 16 ,sizeof tail ); 139const float sg = tail [0 ],su = tail [1 ]; 140const size_t up_off = (size_t )F * ROW_BYTES ; 141Acts a (N ,NT ,rng ); 142 std::vector < std::vector < float >> mine (NT , std::vector < float > (F )),ref (NT , std::vector < float > (F )); 143 std::vector < float *> op (NT ); 144for (int t = 0 ;t < NT ;++ t )op [t ]= mine [t ].data (); 145int bad = 0 ,differ = 0 ; 146double worst = 0 ; 147for (int nt = 1 ;nt <=NT ;++ nt ) { 148k .gu (blob ,ROW_BYTES ,up_off ,N ,a .p .data (),nt ,op .data (),0 ,F ,sg ,su ); 149for (int t = 0 ;t < nt ;++ t ) 150for (int r = 0 ;r < F ;++ r ) { 151const float g = ref_dot (blob + (size_t )r * ROW_BYTES ,N ,a .p [t ])* sg ; 152const float u = ref_dot (blob + up_off + (size_t )r * ROW_BYTES ,N ,a .p [t ])* su ; 153ref [t ][r ]= (g / (1.f + std::exp (- g )))* u ; 154 } 155bad += report (mine ,ref ,nt ,F ,worst ,differ ); 156 } 157char what [96 ]; 158 std::snprintf (what ,sizeof what ,"expert 0: silu(gate) * up (s %.2g/%.2g)" ,sg ,su ); 159return verdict (k ,what ,worst ,F ,NT ,bad ,differ ); 160} 161 162void speed (const std::vector < uint8_t >& w , std::mt19937 & rng ,bool has512 ,bool has256 ) { 163const ggml_type_traits_cpu * tw = ggml_get_type_traits_cpu (GGML_TYPE_NVFP4 ); 164const ggml_type_traits_cpu * ta = ggml_get_type_traits_cpu (tw -> vec_dot_type ); 165const size_t act_bytes = ggml_row_size (tw -> vec_dot_type ,N ); 166 std::normal_distribution < float > nd (0.f ,1.f ); 167 std::vector < std::vector < uint8_t >> act (8 , std::vector < uint8_t > (act_bytes )); 168 std::vector < float > x (N ),sink (8 * ROWS ); 169const void * ap [8 ]; 170float * op [8 ]; 171for (int t = 0 ;t < 8 ;++ t ) { 172for (float & v :x )v = nd (rng ); 173ta -> from_float (x .data (),act [t ].data (),N ); 174ap [t ]= act [t ].data (); 175op [t ]= sink .data ()+ (size_t )t * ROWS ; 176 } 177 std::printf ("\n%-6s %10s %10s %8s %10s %8s (one expert's gate+up, %d rows; best of 20)\n" ,"tokens" , 178"ggml ms" ,"avx512 ms" ,"speedup" ,"avx2 ms" ,"speedup" ,ROWS ); 179for (int nt = 1 ;nt <=8 ;++ nt ) { 180double tg = 1e30 ,tm = 1e30 ,t2 = 1e30 ; 181for (int rep = 0 ;rep < 20 ;++ rep ) { 182double t0 = now_ms (); 183for (int t = 0 ;t < nt ;++ t ) 184for (int r = 0 ;r < ROWS ;++ r )tw -> vec_dot (N ,& op [t ][r ],0 ,w .data ()+ (size_t )r * ROW_BYTES ,0 ,ap [t ],0 ,1 ); 185tg = std::fmin (tg ,now_ms ()- t0 ); 186if (has512 ) { 187t0 = now_ms (); 188k512 .rows (w .data (),ROW_BYTES ,N ,ap ,nt ,op ,0 ,ROWS ,1.f ); 189tm = std::fmin (tm ,now_ms ()- t0 ); 190 } 191if (has256 ) { 192t0 = now_ms (); 193k256 .rows (w .data (),ROW_BYTES ,N ,ap ,nt ,op ,0 ,ROWS ,1.f ); 194t2 = std::fmin (t2 ,now_ms ()- t0 ); 195 } 196 } 197 std::printf ("%-6d %10.3f %10.3f %7.2fx %10.3f %7.2fx\n" ,nt ,tg ,has512 ?tm :0.0 ,has512 ?tg /tm :0.0 , 198has256 ?t2 :0.0 ,has256 ?tg /t2 :0.0 ); 199 } 200} 201 202int bandwidth (int threads ,int nt ,bool use_ggml ,const Kern & k ) { 203constexpr int E = 1536 ; 204 std::vector < uint8_t > blobs ((size_t )E * BLOB ); 205 { 206 std::vector < std::thread > fill ; 207for (int t = 0 ;t < 16 ;++ t ) 208fill .emplace_back ([& ,t ] { 209uint64_t x = 0x9E3779B97F4A7C15ull * (t + 1 ); 210const size_t n8 = blobs .size () /8 ,a = n8 * t /16 ,b = n8 * (t + 1 ) /16 ; 211for (size_t i = a ;i < b ;++ i ) { 212x ^=x <<13 ;x ^=x >>7 ;x ^=x <<17 ; 213uint64_t v = x & 0x3F3F3F3F3F3F3F3Full ;// scale bytes stay finite; codes are any nibble 214 std::memcpy (blobs .data ()+ 8 * i ,& v ,8 ); 215 } 216 }); 217for (auto & f :fill )f .join (); 218 } 219 std::mt19937 rng (7 ); 220Acts ax (N ,nt ,rng ),ah (FF ,nt ,rng ); 221const ggml_type_traits_cpu * tw = ggml_get_type_traits_cpu (GGML_TYPE_NVFP4 ); 222double best = 1e30 ; 223for (int pass = 0 ;pass < 3 ;++ pass ) { 224const double t0 = now_ms (); 225 std::vector < std::thread > pool ; 226for (int w = 0 ;w < threads ;++ w ) 227pool .emplace_back ([& ,w ] { 228 std::vector < float > ff ((size_t )nt * (ROWS /2 )),out ((size_t )nt * N ); 229 std::vector < float *> fp (nt ),op (nt ); 230for (int t = 0 ;t < nt ;++ t ) {fp [t ]= ff .data ()+ (size_t )t * (ROWS /2 );op [t ]= out .data ()+ (size_t )t * N ; } 231for (int e = w ;e < E ;e += threads ) { 232const uint8_t * b = blobs .data ()+ (size_t )e * BLOB ; 233const size_t up_off = (size_t ) (ROWS /2 )* ROW_BYTES ,d_off = (size_t )ROWS * ROW_BYTES ; 234if (!use_ggml ) { 235k .gu (b ,ROW_BYTES ,up_off ,N ,ax .p .data (),nt ,fp .data (),0 ,ROWS /2 ,1.f ,1.f ); 236k .rows (b + d_off ,D_ROW ,FF ,ah .p .data (),nt ,op .data (),0 ,N ,1.f ); 237 }else { 238for (int r = 0 ;r < ROWS /2 ;++ r ) 239for (int t = 0 ;t < nt ;++ t ) { 240float g = 0.f ,u = 0.f ; 241tw -> vec_dot (N ,& g ,0 ,b + (size_t )r * ROW_BYTES ,0 ,ax .p [t ],0 ,1 ); 242tw -> vec_dot (N ,& u ,0 ,b + up_off + (size_t )r * ROW_BYTES ,0 ,ax .p [t ],0 ,1 ); 243fp [t ][r ]= (g / (1.f + std::exp (- g )))* u ; 244 } 245for (int r = 0 ;r < N ;++ r ) 246for (int t = 0 ;t < nt ;++ t )tw -> vec_dot (FF ,& op [t ][r ],0 ,b + d_off + (size_t )r * D_ROW ,0 ,ah .p [t ],0 ,1 ); 247 } 248 } 249 }); 250for (auto & p :pool )p .join (); 251best = std::fmin (best ,now_ms ()- t0 ); 252 } 253const char * pf = std::getenv ("STRATA_NVFP4_PREFETCH" ); 254 std::printf ("%s threads %d tokens %d prefetch %s: %.1f ms for %d experts -> %.1f GB/s, %.1f us/expert/thread\n" , 255use_ggml ?"ggml " :k .name ,threads ,nt ,use_ggml ?"-" : (pf ?pf :"2048" ),best ,E , 256 (double )E * BLOB /best /1e6 ,best * 1000.0 * threads /E ); 257return 0 ; 258} 259 260int expert_e2e (const char * path ,int layer ,int e ) { 261constexpr size_t STRIDE = 2764816 ,LAYER = 512 * STRIDE ; 262 std::vector < uint8_t > b (BLOB ); 263 std::ifstream f (path , std::ios::binary ); 264f .seekg ((std::streamoff ) (layer * LAYER + (size_t )e * STRIDE )); 265if (!f .read ((char * )b .data (), (std::streamsize )b .size ())) { std::fprintf (stderr ,"cannot read %s\n" ,path );return 2 ; } 266float tail [4 ]; 267 std::memcpy (tail ,b .data ()+ BLOB - 16 ,sizeof tail ); 268const float sg = tail [0 ],s_up = tail [1 ],s_down = tail [2 ]; 269const int F = ROWS /2 ; 270const size_t up_off = (size_t )F * ROW_BYTES ,d_off = (size_t )ROWS * ROW_BYTES ; 271const ggml_type_traits * tt = ggml_get_type_traits (GGML_TYPE_NVFP4 ); 272 std::vector < float > wg ((size_t )F * N ),wu ((size_t )F * N ),wd ((size_t )N * FF ); 273tt -> to_float (b .data (),wg .data (), (int64_t )F * N ); 274tt -> to_float (b .data ()+ up_off ,wu .data (), (int64_t )F * N ); 275tt -> to_float (b .data ()+ d_off ,wd .data (), (int64_t )N * FF ); 276const ggml_type_traits_cpu * q8 = ggml_get_type_traits_cpu (GGML_TYPE_Q8_0 ); 277 std::mt19937 rng (9 ); 278 std::normal_distribution < float > nd (0.f ,1.f ); 279double e_fold = 0 ,e_out = 0 ,den = 0 ,hmax_fold = 0 ; 280for (int trial = 0 ;trial < 8 ;++ trial ) { 281 std::vector < float > x (N ); 282for (float & v :x )v = nd (rng ); 283 std::vector < double > h (F ),y (N ,0.0 ); 284for (int r = 0 ;r < F ;++ r ) { 285double g = 0 ,u = 0 ; 286for (int k = 0 ;k < N ;++ k ) {g += (double )wg [(size_t )r * N + k ]* x [k ];u += (double )wu [(size_t )r * N + k ]* x [k ]; } 287g *=sg ;u *=s_up ; 288h [r ]= g / (1 + std::exp (- g ))* u ; 289 } 290for (int r = 0 ;r < N ;++ r ) { 291double s = 0 ; 292for (int k = 0 ;k < F ;++ k )s += (double )wd [(size_t )r * FF + k ]* h [k ]; 293y [r ]= s * s_down ; 294 } 295 std::vector < uint8_t > xq (ggml_row_size (GGML_TYPE_Q8_0 ,N )),hq (ggml_row_size (GGML_TYPE_Q8_0 ,FF )); 296q8 -> from_float (x .data (),xq .data (),N ); 297const void * ap [1 ]= {xq .data ()}; 298 std::vector < float > ff (F ),out (N ); 299float * fp [1 ]= {ff .data ()}; 300float * op [1 ]= {out .data ()}; 301for (int mode = 0 ;mode < 2 ;++ mode ) {// 0: s_down folded into up; 1: s_down on the output 302const Kern & k = strata::kernels::cpu::cpu_avx512_ok () ?k512 :k256 ; 303k .gu (b .data (),ROW_BYTES ,up_off ,N ,ap ,1 ,fp ,0 ,F ,sg ,mode == 0 ?s_up * s_down :s_up ); 304if (mode == 0 )for (float v :ff )hmax_fold = std::fmax (hmax_fold , std::fabs (v )); 305q8 -> from_float (ff .data (),hq .data (),FF ); 306const void * hp [1 ]= {hq .data ()}; 307k .rows (b .data ()+ d_off ,D_ROW ,FF ,hp ,1 ,op ,0 ,N ,1.f ); 308double err = 0 ; 309for (int r = 0 ;r < N ;++ r ) { 310const double got = mode == 0 ?out [r ] : (double )out [r ]* s_down ; 311err += (got - y [r ])* (got - y [r ]); 312 } 313 (mode == 0 ?e_fold :e_out )+= err ; 314 } 315for (int r = 0 ;r < N ;++ r )den += y [r ]* y [r ]; 316 } 317 std::printf ("layer %d expert %d: s_gate %.3g s_up %.3g s_down %.3g; folded hidden max |h| %.3g (Q8_0 d %.3g, FP16 " 318"normal from 6.1e-05)\n" ,layer ,e ,sg ,s_up ,s_down ,hmax_fold ,hmax_fold /127 ); 319 std::printf (" s_down folded into up : expert output rel. error %.3f%%\n" ,100 * std::sqrt (e_fold /den )); 320 std::printf (" s_down on the output : expert output rel. error %.3f%%\n" ,100 * std::sqrt (e_out /den )); 321return 0 ; 322} 323 324}// namespace 325 326int main (int argc ,char ** argv ) { 327ggml_cpu_init (); 328if (argc >=3 && std::string (argv [1 ])== "--expert" ) 329return expert_e2e (argv [2 ],argc >=4 ? std::atoi (argv [3 ]) :0 ,argc >=5 ? std::atoi (argv [4 ]) :0 ); 330const bool has512 = strata::kernels::cpu::cpu_avx512_ok (),has256 = strata::kernels::cpu::cpu_avx2_ok (); 331if (argc >=4 && std::string (argv [1 ])== "--bw" ) { 332const std::string how = argc >=5 ?argv [4 ] :"" ; 333return bandwidth (std::atoi (argv [2 ]), std::atoi (argv [3 ]),how == "ggml" ,how == "avx2" || !has512 ?k256 :k512 ); 334 } 335 std::vector < const Kern *> ks ; 336if (has512 )ks .push_back (& k512 ); 337if (has256 )ks .push_back (& k256 ); 338 std::mt19937 rng (20260929 ); 339 std::vector < uint8_t > w (BLOB ); 340// random blocks: every code, scales 0x20..0x5f (sign bit clear, never 0x7F), as ModelOpt writes them 341 std::uniform_int_distribution < int > byte (0 ,255 ),sc (0x20 ,0x5f ); 342for (size_t b = 0 ;b + BLK <=BLOB - 16 ;b += BLK ) { 343for (int s = 0 ;s < 4 ;++ s )w [b + s ]= (uint8_t )sc (rng ); 344for (int q = 4 ;q < BLK ;++ q )w [b + q ]= (uint8_t )byte (rng ); 345 } 346int bad = 0 ; 347for (const Kern * k :ks ) { 348bad += check_rows (* k ,w .data (),N ,ROW_BYTES ,ROWS ,"random blocks, n 2560" ,rng ); 349bad += check_rows (* k ,w .data (),FF ,D_ROW ,N ,"random blocks, n 640" ,rng ); 350 } 351if (argc >=2 ) {// layer 0, expert 0 of the pack 352 std::ifstream f (argv [1 ], std::ios::binary ); 353if (!f .read ((char * )w .data (), (std::streamsize )w .size ())) { 354 std::fprintf (stderr ,"cannot read %zu bytes of %s\n" ,w .size (),argv [1 ]); 355return 2 ; 356 } 357for (const Kern * k :ks ) { 358bad += check_rows (* k ,w .data (),N ,ROW_BYTES ,ROWS ,"expert 0: gate+up rows" ,rng ); 359bad += check_rows (* k ,w .data ()+ (size_t )ROWS * ROW_BYTES ,FF ,D_ROW ,N ,"expert 0: down rows" ,rng ); 360bad += check_gu (* k ,w .data (),rng ); 361 } 362 } 363speed (w ,rng ,has512 ,has256 ); 364 std::printf ("\nRESULT: %s\n" ,bad ?"MISMATCH" :"parity OK" ); 365return bad ?1 :0 ; 366}