okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
885f91649
main
1// Strata. The DeepSeek-V4.1 CPU lane's ggml-type rows (src/dsv41/ds4_gg_cpu.cpp): ggml-cpu's row dot against Strata's AVX2 2// multi-token i-quant rows, on random blocks. 3// ds4_gg_bench [--type 16|17|18|29] [--threads N] [--mb M] [--nt 1..8] [--reps R] 4// --k256 / --k512: direct row exactness checks, without dispatcher fallback. 5// --expert --lane: one expert per call through the production pool, including serial h quantization. 6// Checks first (every row, every token): the two paths' results agree to a few float ulps (the integer sums are the same; 7// only the order of the float additions differs) and, with --exact, bit for bit. Then the time of a pass over M MB of 8// weights (default 3072, far past L3) on N threads, as GB/s of weights read, beside a plain streaming read of the same 9// bytes (the memory ceiling the rows are measured against). 10#include "ds4_gguf_cpu.hpp" 11#include "ds4_pool.hpp" 12 13#include "ggml-cpu.h" 14#include "strata/kernels/cpu/expert_layout.hpp" 15#include "strata/kernels/cpu/iq_avx512.hpp" 16#include "strata/kernels/cpu/iq_avx2.hpp" 17#include "ggml.h" 18 19#include <algorithm> 20#include <atomic> 21#include <chrono> 22#include <cmath> 23#include <functional> 24#include <memory> 25#include <cstdio> 26#include <cstdlib> 27#include <cstring> 28#include <string> 29#include <thread> 30#include <vector> 31 32using namespace strata::ds4::gguf ; 33using clk = std::chrono::steady_clock ; 34 35static double secs (clk::time_point a ) {return std::chrono::duration < double > (clk::now ()- a ).count (); } 36 37// ---- --expert: the engine's expert pipeline on random experts (gate+up+SwiGLU, quantize h, down) in jobs of 64 rows over N threads, for 38// ggml-cpu's dots (mode 0), the default rule (2) and the AVX2 rows always (1); GB/s of all three matrices' bytes, outputs compared bit for bit. 39static void fill_blocks (uint8_t * w ,size_t bytes ,int type ,uint64_t seed ) { 40uint64_t st = 0x9E3779B97F4A7C15ull ^ (seed * 0xD1B54A32D192ED03ull ); 41auto next = [& st ] {st ^=st <<13 ;st ^=st >>7 ;st ^=st <<17 ;return st ; }; 42for (size_t o = 0 ;o + 8 <=bytes ;o += 8 ) {const uint64_t v = next (); std::memcpy (w + o ,& v ,8 ); } 43const size_t bb = ggml_type_size ((ggml_type )type ); 44for (size_t o = 0 ;o + bb <=bytes ;o += bb ) { 45const ggml_fp16_t d = ggml_fp32_to_fp16 (0.002f + 0.001f * (float ) (next () %16 )); 46if (type == 29 ) { 47uint16_t sc [4 ]; 48 std::memcpy (sc ,w + o + 48 ,8 ); 49for (int k = 0 ;k < 4 ;++ k )sc [k ]= (uint16_t ) ((sc [k ]& 0x0fff ) | ((d >> (4 * k ))& 0xf ) <<12 ); 50 std::memcpy (w + o + 48 ,sc ,8 ); 51 }else { 52 std::memcpy (w + o ,& d ,sizeof d ); 53 } 54 } 55} 56 57static int run_expert (int tg ,int td ,int threads ,long mb ,int nt ,int reps ,bool lane ) { 58ggml_cpu_init (); 59const int E = 5120 ,FF = 2304 ; 60IqCpu f ; 61 std::string err ; 62if (!gg_cpu_fmt (tg ,td ,E ,FF ,f ,err )) { std::fprintf (stderr ,"gg_cpu_fmt: %s\n" ,err .c_str ());return 2 ; } 63const size_t gbytes = f .gu_row * FF ,dbytes = f .d_row * E ,ebytes = 2 * gbytes + dbytes ; 64const int ne = (int ) std::max (2L , (long ) ((size_t )mb * 1000000 /ebytes )); 65 std::vector < uint8_t > gw ((size_t )ne * gbytes ),uw ((size_t )ne * gbytes ),dw ((size_t )ne * dbytes ); 66for (int e = 0 ;e < ne ;++ e ) { 67fill_blocks (& gw [(size_t )e * gbytes ],gbytes ,tg ,3 * (uint64_t )e + 1 ); 68fill_blocks (& uw [(size_t )e * gbytes ],gbytes ,tg ,3 * (uint64_t )e + 2 ); 69fill_blocks (& dw [(size_t )e * dbytes ],dbytes ,td ,3 * (uint64_t )e + 3 ); 70 } 71uint64_t st = 12345 ; 72auto next = [& st ] {st ^=st <<13 ;st ^=st >>7 ;st ^=st <<17 ;return st ; }; 73 std::vector < std::vector < uint8_t >> act ((size_t )nt , std::vector < uint8_t > (f .act_bytes )); 74for (int t = 0 ;t < nt ;++ t ) { 75 std::vector < float > x ((size_t )E ); 76for (auto & v :x )v = ((float ) (next () %2001 )- 1000.0f )* 1e-3f ; 77gg_cpu_quant (f .gu_act ,x .data (),E ,act [(size_t )t ].data ()); 78 } 79 std::vector < float > h ((size_t )ne * nt * FF ),y ((size_t )ne * nt * E ); 80 std::vector < uint8_t > hq ((size_t )ne * nt * f .h_bytes ); 81const int RB = 64 ; 82 std::unique_ptr < strata::ds4::Pool > pool ; 83if (lane )pool = std::make_unique < strata::ds4::Pool > (std::max (0 ,threads - 1 )); 84 std::printf ("expert scheduling: %s\n" ,lane ?"one expert per call, production Pool" :"all experts batched, temporary threads" ); 85auto run_jobs = [& ](long njobs ,const std::function < void (long )>& fn ) { 86if (pool ) { 87pool -> run ((int )njobs , [& ](int j ) {fn (j ); }); 88return ; 89 } 90 std::atomic < long > cur {0 }; 91 std::vector < std::thread > th ; 92for (int k = 0 ;k < threads ;++ k ) 93th .emplace_back ([& ] {for (;;) {const long j = cur .fetch_add (1 );if (j >=njobs )break ;fn (j ); } }); 94for (auto & t :th )t .join (); 95 }; 96auto pass = [& ](int mode ) { 97gg_cpu_set_iq256 (mode ); 98double best = 1e30 ; 99for (int r = 0 ;r < reps + 1 ;++ r ) { 100const auto t0 = clk::now (); 101const long gb = (FF + RB - 1 ) /RB ,db = (E + RB - 1 ) /RB ; 102const int batch = lane ?1 :ne ; 103for (int first = 0 ;first < ne ;first += batch ) { 104const int count = std::min (batch ,ne - first ); 105run_jobs ((long )count * gb , [& ](long j ) { 106const int e = first + (int ) (j /gb ),r0 = (int ) (j %gb )* RB ,r1 = std::min (FF ,r0 + RB ); 107const void * ap [64 ]; 108float * hp [64 ]; 109for (int t = 0 ;t < nt ;++ t ) {ap [t ]= act [(size_t )t ].data ();hp [t ]= & h [((size_t )e * nt + t )* FF ]; } 110gg_cpu_gate_up (f ,& gw [(size_t )e * gbytes ],& uw [(size_t )e * gbytes ],ap ,nt ,hp ,r0 ,r1 ,10.0f ); 111 }); 112auto quant_h = [& ](long j ) { 113const size_t ix = (size_t )first * nt + j ; 114gg_cpu_quant (f .d_act ,& h [ix * FF ],FF ,& hq [ix * f .h_bytes ]); 115 }; 116if (lane )for (int t = 0 ;t < nt ;++ t )quant_h (t ); 117else run_jobs ((long )count * nt ,quant_h ); 118run_jobs ((long )count * db , [& ](long j ) { 119const int e = first + (int ) (j /db ),r0 = (int ) (j %db )* RB ,r1 = std::min (E ,r0 + RB ); 120const void * hp [64 ]; 121float * yp [64 ]; 122for (int t = 0 ;t < nt ;++ t ) {hp [t ]= & hq [((size_t )e * nt + t )* f .h_bytes ];yp [t ]= & y [((size_t )e * nt + t )* E ]; } 123gg_cpu_down (f ,& dw [(size_t )e * dbytes ],hp ,nt ,yp ,r0 ,r1 ); 124 }); 125 } 126if (r > 0 )best = std::min (best ,secs (t0 )); 127 } 128return best ; 129 }; 130const double gb = (double )ne * ebytes /1e9 ; 131 std::vector < float > y0 ; 132double t0s = 0 ; 133int rc = 0 ; 134for (int mode : {0 ,2 ,1 }) { 135const double t = pass (mode ); 136if (mode == 0 ) {y0 = y ;t0s = t ; } 137const bool same = std::memcmp (y0 .data (),y .data (),y .size ()* 4 )== 0 ; 138 std::printf ("expert gate/up %d down %d nt %d threads %d: %d experts, %.2f GB | mode %s %.3f s = %.1f GB/s (x%.2f) %s\n" ,tg ,td ,nt , 139threads ,ne ,gb ,mode == 0 ?"ggml " :mode == 2 ?"auto " :"own " ,t ,gb /t ,t0s /t ,same ?"bit-identical" :"DIFFERENT" ); 140if (!same )rc = 1 ; 141 } 142return rc ; 143} 144 145int main (int argc ,char ** argv ) { 146int type = 18 ,threads = 32 ,nt = 1 ,reps = 3 ; 147long mb = 3072 ; 148bool exact = false,expert = false,k512 = false,k256 = false,lane = false; 149int dtype = -1 ; 150 std::string dump ;// --dump FILE: ggml-cpu's results (nt x rows floats) written raw - compare two builds with cmp 151for (int i = 1 ;i < argc ;++ i ) { 152 std::string a = argv [i ]; 153auto val = [& ] {return i + 1 < argc ? std::atol (argv [++ i ]) :0L ; }; 154if (a == "--type" )type = (int )val (); 155else if (a == "--threads" )threads = (int )val (); 156else if (a == "--mb" )mb = val (); 157else if (a == "--nt" )nt = (int )val (); 158else if (a == "--reps" )reps = (int )val (); 159else if (a == "--exact" )exact = true; 160else if (a == "--expert" )expert = true; 161else if (a == "--lane" )lane = true; 162else if (a == "--k512" )k512 = true; 163else if (a == "--k256" )k256 = true; 164else if (a == "--dtype" )dtype = (int )val (); 165else if (a == "--dump" && i + 1 < argc )dump = argv [++ i ]; 166 } 167ggml_cpu_init (); 168 std::printf ("ggml-cpu compiled ISA: AVX2 %d FMA %d F16C %d\n" ,ggml_cpu_has_avx2 (),ggml_cpu_has_fma (),ggml_cpu_has_f16c ()); 169if (!ggml_cpu_has_avx2 ()|| !ggml_cpu_has_fma ()|| !ggml_cpu_has_f16c ()) 170 std::fprintf (stderr ,"warning: ggml-cpu lacks AVX2/FMA/F16C; own/auto may fall back after the exactness check. " 171"Use -DSTRATA_PORTABLE=ON if the compiler strips -march=native.\n" ); 172if (expert )return run_expert (type ,dtype < 0 ?type :dtype ,threads ,mb ,nt ,reps ,lane ); 173const int n = 5120 ;// a gate / up row 174IqCpu f ; 175 std::string err ; 176if (!gg_cpu_fmt (type ,type ,n ,2304 ,f ,err )) { 177 std::fprintf (stderr ,"gg_cpu_fmt: %s\n" ,err .c_str ()); 178return 2 ; 179 } 180const size_t rb = f .gu_row ; 181const long rows = (long ) ((size_t )mb * 1000000 /rb ) /8 * 8 ; 182 std::vector < uint8_t > w ((size_t )rows * rb ); 183uint64_t st = 0x9E3779B97F4A7C15ull ; 184auto next = [& st ] {st ^=st <<13 ;st ^=st >>7 ;st ^=st <<17 ;return st ; }; 185for (size_t o = 0 ;o + 8 <=w .size ();o += 8 ) {const uint64_t v = next (); std::memcpy (& w [o ],& v ,8 ); } 186const size_t bb = ggml_type_size ((ggml_type )type ); 187for (size_t o = 0 ;o + bb <=w .size ();o += bb ) {// the blocks' F16 scale: a small normal value 188const ggml_fp16_t d = ggml_fp32_to_fp16 (0.002f + 0.001f * (float ) (next () %16 )); 189if (type == 29 ) {// IQ1_M: no d field - its f16 is spread over the top nibbles of the four scale words (bytes 48..55) 190uint16_t sc [4 ]; 191 std::memcpy (sc ,& w [o + 48 ],8 ); 192for (int k = 0 ;k < 4 ;++ k )sc [k ]= (uint16_t ) ((sc [k ]& 0x0fff ) | ((d >> (4 * k ))& 0xf ) <<12 ); 193 std::memcpy (& w [o + 48 ],sc ,8 ); 194 }else { 195 std::memcpy (& w [o ],& d ,sizeof d ); 196 } 197 } 198 std::vector < std::vector < uint8_t >> a ((size_t )nt , std::vector < uint8_t > (f .act_bytes )); 199 std::vector < const void *> ap ((size_t )nt ); 200for (int t = 0 ;t < nt ;++ t ) { 201 std::vector < float > x ((size_t )n ); 202for (auto & v :x )v = ((float ) (next () %2001 )- 1000.0f )* 1e-3f ; 203gg_cpu_quant (f .gu_act ,x .data (),n ,a [(size_t )t ].data ()); 204ap [(size_t )t ]= a [(size_t )t ].data (); 205 } 206if (k512 || k256 ) {// Direct rows: no dispatcher or exactness fallback. 207const bool cpu_ok = k512 ? strata::kernels::cpu::cpu_avx512_ok () : strata::kernels::cpu::cpu_avx2_ok (); 208const bool sup = k512 ? strata::kernels::cpu::iq512x_supported (type ) : strata::kernels::cpu::iq256x_supported (type ); 209const auto rows_fn = k512 ? strata::kernels::cpu::iq512x_rows : strata::kernels::cpu::iq256x_rows ; 210const char * label = k512 ?"k512" :"k256" ; 211 std::printf ("%s: type %d nt %d: CPU support %d, format support %d%s\n" ,label ,type ,nt , (int )cpu_ok , (int )sup , 212cpu_ok && sup ?"" :" -> the rows cannot run here" ); 213if (!cpu_ok || !sup )return 3 ; 214const ggml_type_traits_cpu * tc = ggml_get_type_traits_cpu ((ggml_type )type ); 215 std::vector < std::vector < float >> r0v ((size_t )nt , std::vector < float > ((size_t )rows )),r1v = r0v ; 216 std::vector < float *> q1 ; 217for (int t = 0 ;t < nt ;++ t )q1 .push_back (r1v [(size_t )t ].data ()); 218for (long r = 0 ;r < rows ;++ r ) 219for (int t = 0 ;t < nt ;++ t )tc -> vec_dot (n ,& r0v [(size_t )t ][(size_t )r ],0 ,w .data ()+ (size_t )r * rb ,0 ,ap [(size_t )t ],0 ,1 ); 220rows_fn (type ,w .data (),rb ,n ,ap .data (),nt ,q1 .data (),0 , (int )rows ); 221long dif = 0 ; 222for (int t = 0 ;t < nt ;++ t ) 223for (long r = 0 ;r < rows ;++ r ) 224if (std::memcmp (& r0v [(size_t )t ][(size_t )r ],& r1v [(size_t )t ][(size_t )r ],4 )!= 0 )++ dif ; 225 std::printf ("%s: direct rows against ggml-cpu's dot: %ld of %ld differ in bits\n%s\n" ,label ,dif , (long )nt * rows ,dif == 0 ?"OK" :"FAIL" ); 226return dif == 0 ?0 :1 ; 227 } 228 std::vector < std::vector < float >> o0 ((size_t )nt , std::vector < float > ((size_t )rows )),o1 = o0 ; 229 std::vector < float *> p0 ,p1 ; 230for (int t = 0 ;t < nt ;++ t ) {p0 .push_back (o0 [(size_t )t ].data ());p1 .push_back (o1 [(size_t )t ].data ()); } 231 232// a pass over all rows on `threads` threads, mode 0 ggml-cpu, 1 Strata's rows; returns the best time of reps 233auto pass = [& ](int mode ,float * const * out ) { 234gg_cpu_set_iq256 (mode ); 235double best = 1e30 ; 236for (int r = 0 ;r < reps + 1 ;++ r ) { 237const auto t0 = clk::now (); 238 std::vector < std::thread > th ; 239 std::atomic < long > cursor {0 }; 240const long chunk = 64 ; 241for (int k = 0 ;k < threads ;++ k ) 242th .emplace_back ([& ] { 243for (;;) { 244const long r0 = cursor .fetch_add (chunk ); 245if (r0 >=rows )break ; 246// one "expert part" is 2304 rows; the engine hands a thread a few rows of it at a time 247gg_cpu_down (f ,w .data (),ap .data (),nt ,out , (int )r0 , (int ) std::min (rows ,r0 + chunk )); 248 } 249 }); 250for (auto & t :th )t .join (); 251if (r > 0 )best = std::min (best ,secs (t0 )); 252 } 253return best ; 254 }; 255// gg_cpu_down uses f.td / d_row; here td == tg and the activation has n_embd values: f.d_row would be for n_ff. 256// Use the gate rows through a second IqCpu whose down geometry is the gate's. 257f .td = f .tg ;f .d_row = f .gu_row ;f .n_ff = n ;f .d_act = f .gu_act ;f .h_bytes = f .act_bytes ; 258 259const double t_gg = pass (0 ,p0 .data ()); 260const double t_own = pass (1 ,p1 .data ()); 261if (!dump .empty ()) { 262if (std::FILE * df = std::fopen (dump .c_str (),"wb" )) { 263for (int t = 0 ;t < nt ;++ t ) std::fwrite (o0 [(size_t )t ].data (),4 , (size_t )rows ,df ); 264 std::fclose (df ); 265 } 266 } 267long bad = 0 ,differ = 0 ; 268double worst = 0 ,worst_ref = 0 ,absmax = 0 ,absdiff = 0 ; 269for (int t = 0 ;t < nt ;++ t ) 270for (long r = 0 ;r < rows ;++ r ) { 271const float x = o0 [(size_t )t ][(size_t )r ],y = o1 [(size_t )t ][(size_t )r ]; 272absmax = std::max (absmax , (double ) std::fabs (x )); 273absdiff = std::max (absdiff , (double ) std::fabs ((double )x - y )); 274if (std::memcmp (& x ,& y ,4 )!= 0 ) { 275++ differ ; 276const double rel = std::fabs ((double )x - y ) / (std::fabs ((double )x )+ 1e-3 ); 277worst = std::max (worst ,rel ); 278if (rel > 1e-5 )++ bad ; 279 } 280 } 281// The pass criterion above divides by one value's magnitude, so a token whose dot cancels to near zero fails it while 282// agreeing to a few ulps. The real bound is the L1 norm of the products (|x - ref| <= eps * sum|w x|): decode a 283// sample of rows with ggml's own to_float and the activation as its Q8_K blocks hold it, and compare in double. 284int sampled = 0 ; 285 { 286const ggml_type_traits * tt = ggml_get_type_traits ((ggml_type )type ); 287 std::vector < float > wrow ((size_t )n ); 288// the activations (Q8_K: float d, int8 qs[256], int16 bsums[16]) as the rows see them 289 std::vector < std::vector < float >> xv ((size_t )nt , std::vector < float > ((size_t )n )); 290for (int t = 0 ;t < nt ;++ t ) 291for (int b = 0 ;b < n /256 ;++ b ) { 292const uint8_t * p = (const uint8_t * )ap [(size_t )t ]+ (size_t )b * (f .act_bytes / (size_t ) (n /256 )); 293float d ; 294 std::memcpy (& d ,p ,4 ); 295const int8_t * q = (const int8_t * ) (p + 4 ); 296for (int j = 0 ;j < 256 ;++ j )xv [(size_t )t ][(size_t )b * 256 + j ]= d * (float )q [j ]; 297 } 298const long step = std::max (1L ,rows /64 ); 299for (long r = 0 ;r < rows && sampled < 64 ;r += step ,++ sampled ) { 300if (tt == nullptr || tt -> to_float == nullptr )break ; 301tt -> to_float (w .data ()+ (size_t )r * rb ,wrow .data (),n ); 302for (int t = 0 ;t < nt ;++ t ) { 303double ref = 0 ,l1 = 0 ; 304for (int j = 0 ;j < n ;++ j ) { 305const double pr = (double )wrow [(size_t )j ]* (double )xv [(size_t )t ][(size_t )j ]; 306ref += pr ; 307l1 += std::fabs (pr ); 308 } 309const double g = o0 [(size_t )t ][(size_t )r ],o = o1 [(size_t )t ][(size_t )r ]; 310worst_ref = std::max (worst_ref , std::fabs (g - ref ) / (l1 + 1e-30 )); 311worst_ref = std::max (worst_ref , std::fabs (o - ref ) / (l1 + 1e-30 )); 312 } 313 } 314 } 315// memory ceiling: a plain read of the same bytes on the same threads 316double t_rd = 1e30 ; 317for (int r = 0 ;r < reps + 1 ;++ r ) { 318const auto t0 = clk::now (); 319 std::vector < std::thread > th ; 320 std::vector < uint64_t > sink ((size_t )threads ); 321for (int k = 0 ;k < threads ;++ k ) 322th .emplace_back ([& ,k ] { 323const size_t lo = w .size () / (size_t )threads * (size_t )k ,hi = k + 1 == threads ?w .size () :w .size () / (size_t )threads * (size_t ) (k + 1 ); 324uint64_t s = 0 ,v ; 325for (size_t o = lo ;o + 8 <=hi ;o += 8 ) { std::memcpy (& v ,& w [o ],8 );s += v ; } 326sink [(size_t )k ]= s ; 327 }); 328for (auto & t :th )t .join (); 329if (r > 0 )t_rd = std::min (t_rd ,secs (t0 )); 330 } 331const double gb = (double )w .size () /1e9 ; 332 std::printf ("type %d nt %d threads %d: %.2f GB of weights (%ld rows)\n" ,type ,nt ,threads ,gb ,rows ); 333 std::printf (" ggml-cpu rows %.3f s = %.1f GB/s | Strata AVX2 rows %.3f s = %.1f GB/s (x%.2f) | plain read %.1f GB/s\n" ,t_gg ,gb /t_gg , 334t_own ,gb /t_own ,t_gg /t_own ,gb /t_rd ); 335 std::printf (" results: %ld of %ld differ in bits, worst |x-y|/|x| %.2e, %ld beyond 1e-5\n" ,differ , (long )nt * rows ,worst ,bad ); 336 std::printf (" vs a double reference on %d sampled rows: worst %.2e of the L1 norm (tol 1e-5); |x-y| max %.2e of |x| max %.2e\n" , 337sampled ,worst_ref ,absdiff ,absmax ); 338if (worst_ref > 1e-5 || absdiff > 1e-6 * absmax + 1e-30 || (exact && differ != 0 )) { 339 std::printf ("FAIL\n" ); 340return 1 ; 341 } 342 std::printf ("OK\n" ); 343return 0 ; 344}