okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5a9b4f4fc
main
1// src/kernels/cpu/tq_cpu_parity.cpp - the CPU trellis kernels (tq_cpu.hpp: TQ2_T / TQK6 / TQK7) against their scalar 2// reference, against ggml-cpu's own vec_dot and to_float, and their speed. CPU only (no GPU runtime needed). 3// 4// tq_cpu_parity every check below for tqk6/tqk7 and tq2_t/tq2_t, plain and Hadamard 5// tq_cpu_parity --synthetic GU/DOWN one expert pair (types by ggml name, e.g. tqk6/tqk7) 6// tq_cpu_parity --synthetic-hadamard GU/DOWN the same with the block-128 Hadamard rotation of the activations 7// tq_cpu_parity --bench [--quick] [--only K] the micro-benchmark (run it pinned: taskset -c <cores>); 8// --only: the kernels whose name contains K 9// 10// Checks, per matrix (random stream bytes and scales, so every state is reached, and ggml-quantized Gaussian rows): 11// (1) AVX2 and AVX-512 kernels == the scalar kernel, bit for bit, for groups of 1..8 tokens 12// (2) a token's row in a group of k == the same token alone, bit for bit (no group-size dependence) 13// (3) vs ggml-cpu's vec_dot on the same Q8_0 activations: the same integers summed in another float order, so 14// ~1e-7 relative 15// (4) vs ggml's to_float weights . the dequantized Q8_0 activations in double: the int16 state table's rounding 16// (exact for |codebook| >= 2^-3, within 2^-14 below) plus float rounding, ~1e-6 relative 17// and per expert (native_gu_rows -> native_quant_h -> native_down_rows, the engine's entry points, which now take 18// these kernels) against the same expert computed with ggml-cpu's vec_dot: float rounding plus the odd Q8_0 19// rounding flip of the intermediate. 20#include "strata/kernels/cpu/tq_cpu.hpp" 21#include "strata/kernels/cpu/native_expert.hpp" 22#include "strata/kernels/cpu/expert.hpp" 23#include "strata/kernels/cpu/expert_layout.hpp" 24#include "strata/kernels/cpu/hadamard.hpp" 25 26#include "ggml.h" 27#include "ggml-cpu.h" 28 29#include <algorithm> 30#include <atomic> 31#include <chrono> 32#include <cmath> 33#include <cstdio> 34#include <cstdlib> 35#include <cstring> 36#include <functional> 37#include <random> 38#include <string> 39#include <thread> 40#include <vector> 41 42using namespace strata::kernels::cpu ; 43 44namespace { 45 46constexpr int H = 2560 ,FF = 640 ; 47 48int type_by_name (const std::string & s ) { 49for (int t = 0 ;t < GGML_TYPE_COUNT ;++ t ) { 50const char * n = ggml_type_name ((ggml_type )t ); 51if (n != nullptr && s == n )return t ; 52 } 53return -1 ; 54} 55 56uint16_t f2h (float f ) {return ggml_fp32_to_fp16 (f ); } 57 58// rows x n weights of `type`: random stream bytes and scales (every state reachable, both scale signs), and the 59// last rows (up to 32, ggml's trellis encoder is slow) ggml's own encoding of Gaussian rows 60std::vector < uint8_t > make_matrix (int type ,int rows ,int n ,uint32_t seed ) { 61const size_t rb = ggml_row_size ((ggml_type )type ,n ); 62 std::vector < uint8_t > m (rb * rows ); 63 std::mt19937 rng (seed ); 64 std::uniform_int_distribution < int > byte (0 ,255 ); 65 std::uniform_real_distribution < float > scale (0.002f ,0.05f ); 66const size_t bsz = rb / (size_t ) (n /128 ); 67const int half = rows - std::min (rows /2 ,32 ); 68for (int r = 0 ;r < half ;++ r ) 69for (int b = 0 ;b < n /128 ;++ b ) { 70uint8_t * blk = m .data ()+ (size_t )r * rb + (size_t )b * bsz ; 71const uint16_t d = f2h ((byte (rng )& 1 ?-1.f :1.f )* scale (rng )); 72 std::memcpy (blk ,& d ,2 ); 73for (size_t j = 2 ;j < bsz ;++ j )blk [j ]= (uint8_t )byte (rng ); 74 } 75 std::normal_distribution < float > nd (0.f ,0.02f ); 76 std::vector < float > wf ((size_t ) (rows - half )* n ); 77for (auto & v :wf )v = nd (rng ); 78ggml_quantize_chunk ((ggml_type )type ,wf .data (),m .data ()+ (size_t )half * rb ,0 ,rows - half ,n ,nullptr ); 79return m ; 80} 81 82std::vector < float > make_x (int n ,uint32_t seed ) { 83 std::mt19937 rng (seed ); 84 std::normal_distribution < float > nd (0.f ,1.f ); 85 std::vector < float > x (n ); 86for (auto & v :x )v = nd (rng ); 87x [(size_t ) (seed % (uint32_t )n )]= 40.f ;// a massive channel, as the residual stream has 88return x ; 89} 90 91std::vector < uint8_t > q8_0 (const std::vector < float >& x ) { 92 std::vector < uint8_t > q (ggml_row_size (GGML_TYPE_Q8_0 , (int64_t )x .size ())); 93ggml_get_type_traits_cpu (GGML_TYPE_Q8_0 )-> from_float (x .data (),q .data (), (int64_t )x .size ()); 94return q ; 95} 96 97bool same_bits (const float * a ,const float * b ,size_t n ) {return std::memcmp (a ,b ,n * sizeof (float ))== 0 ; } 98 99// one matrix: checks (1) - (4); returns failures 100int check_matrix (int type ,int rows ,int n ,uint32_t seed ,bool hadamard ) { 101int fails = 0 ; 102const size_t rb = ggml_row_size ((ggml_type )type ,n ); 103const auto m = make_matrix (type ,rows ,n ,seed ); 104constexpr int NT = kTqMaxTokens ; 105 std::vector < std::vector < uint8_t >> act (NT ); 106 std::vector < std::vector < float >> xr (NT ); 107 std::vector < float > signs (n ); 108for (int i = 0 ;i < n ;++ i )signs [i ]= ((i * 2654435761u ) >>7 )& 1 ?-1.f :1.f ; 109const void * ap [NT ]; 110for (int t = 0 ;t < NT ;++ t ) { 111xr [t ]= make_x (n ,seed * 31 + t ); 112if (hadamard )hadamard_rotate (xr [t ].data (),n ,128 ,signs .data ()); 113act [t ]= q8_0 (xr [t ]); 114ap [t ]= act [t ].data (); 115 } 116auto run = [& ](TqIsa isa ,int nt ,const void * const * a , std::vector < float >& o ) { 117o .assign ((size_t )nt * rows ,0.f ); 118float * op [NT ]; 119for (int t = 0 ;t < nt ;++ t )op [t ]= o .data ()+ (size_t )t * rows ; 120// two row ranges, as the pool splits them 121tq_rows (isa ,type ,m .data (),rb ,n ,a ,nt ,op ,0 ,rows /3 ); 122tq_rows (isa ,type ,m .data (),rb ,n ,a ,nt ,op ,rows /3 ,rows ); 123 }; 124 std::vector < float > ref ,got ; 125run (TqIsa ::scalar ,NT ,ap ,ref ); 126// (1) every ISA this CPU has, every group size, == scalar bit for bit; (2) group-size independence 127for (TqIsa isa : {TqIsa ::scalar ,TqIsa ::avx2 ,TqIsa ::avx512 }) { 128if (!tq_isa_ok (isa )) { std::printf (" %-6s not on this CPU: skipped\n" ,tq_isa_name (isa ));continue ; } 129bool ok = true; 130for (int nt = 1 ;nt <=NT ;++ nt ) 131for (int t0 = 0 ;t0 + nt <=NT ;t0 += nt ) { 132run (isa ,nt ,ap + t0 ,got ); 133ok = ok && same_bits (got .data (),ref .data ()+ (size_t )t0 * rows , (size_t )nt * rows ); 134 } 135 std::printf (" %-6s groups of 1..%d tokens vs the scalar kernel's 8-token run: %s\n" ,tq_isa_name (isa ),NT , 136ok ?"bitwise equal" :"DIFFERENT" ); 137fails += !ok ; 138 } 139// (3) ggml-cpu's vec_dot, (4) to_float in double 140const auto * tc = ggml_get_type_traits_cpu ((ggml_type )type ); 141const auto * tt = ggml_get_type_traits ((ggml_type )type ); 142const auto * q8t = ggml_get_type_traits (GGML_TYPE_Q8_0 ); 143double num3 = 0 ,num4 = 0 ,den = 0 ,max3 = 0 ; 144 std::vector < float > wf (n ),af (n ); 145for (int t = 0 ;t < 2 ;++ t ) { 146q8t -> to_float (act [t ].data (),af .data (),n ); 147for (int r = 0 ;r < rows ;++ r ) { 148float g = 0 ; 149tc -> vec_dot (n ,& g ,0 ,m .data ()+ (size_t )r * rb ,0 ,act [t ].data (),0 ,1 ); 150tt -> to_float (m .data ()+ (size_t )r * rb ,wf .data (),n ); 151double d = 0 ,mag = 0 ; 152for (int i = 0 ;i < n ;++ i ) {d += (double )wf [i ]* af [i ];mag += std::fabs ((double )wf [i ]* af [i ]); } 153const double ours = ref [(size_t )t * rows + r ]; 154num3 += (ours - g )* (ours - g ); 155num4 += (ours - d )* (ours - d ); 156den += d * d ; 157max3 = std::max (max3 , std::fabs (ours - g ) / (mag + 1e-30 )); 158 } 159 } 160const double r3 = std::sqrt (num3 /den ),r4 = std::sqrt (num4 /den ); 161const bool ok3 = r3 < 1e-5 && max3 < 1e-5 ,ok4 = r4 < 1e-4 ; 162 std::printf (" vs ggml-cpu vec_dot: rel %.2e (worst row %.2e of sum|w a|) %s | vs to_float in double: rel %.2e %s\n" , 163r3 ,max3 ,ok3 ?"ok" :"FAILED" ,r4 ,ok4 ?"ok" :"FAILED" ); 164return fails + !ok3 + !ok4 ; 165} 166 167// a whole expert through the engine's entry points vs the same expert on ggml-cpu's vec_dot 168int check_expert (int gu ,int dn ,bool hadamard ) { 169NativeFmt f ; 170 std::string err ; 171if (!native_fmt (gu ,dn ,H ,FF ,f ,err )) { std::printf ("native_fmt: %s\n" ,err .c_str ());return 1 ; } 172 std::vector < float > sh (H ),sf (FF ); 173for (int i = 0 ;i < H ;++ i )sh [i ]= (i * 7 %3 ) ?1.f :-1.f ; 174for (int i = 0 ;i < FF ;++ i )sf [i ]= (i * 5 %3 ) ?-1.f :1.f ; 175if (hadamard ) { 176f .had_block = 128 ; 177f .had_gu = f .had_d = true; 178f .gu_signs = sh .data (); 179f .d_signs = sf .data (); 180 } 181 std::vector < uint8_t > blob (f .bytes ); 182const auto g = make_matrix (gu ,FF ,H ,101 ),u = make_matrix (gu ,FF ,H ,202 ),d = make_matrix (dn ,H ,FF ,303 ); 183 std::memcpy (blob .data (),g .data (),g .size ()); 184 std::memcpy (blob .data ()+ f .up_off ,u .data (),u .size ()); 185 std::memcpy (blob .data ()+ f .down_off ,d .data (),d .size ()); 186constexpr int NT = 3 ; 187double worst = 0 ; 188bool bitwise_group = true; 189 std::vector < std::vector < float >> outs (NT , std::vector < float > (H )); 190 std::vector < std::vector < uint8_t >> acts (NT , std::vector < uint8_t > (kNativeActBytes )); 191 std::vector < std::vector < float >> ffs (NT , std::vector < float > (FF )); 192 std::vector < std::vector < uint8_t >> hqs (NT , std::vector < uint8_t > (kNativeHBytes )); 193const void * a [NT ]; 194float * ffp [NT ]; 195const void * hp [NT ]; 196float * op [NT ]; 197for (int t = 0 ;t < NT ;++ t ) { 198const auto x = make_x (H ,7 + t ); 199native_quant_act (f ,x .data (),acts [t ].data ()); 200a [t ]= acts [t ].data (); 201ffp [t ]= ffs [t ].data (); 202hp [t ]= hqs [t ].data (); 203op [t ]= outs [t ].data (); 204 } 205native_gu_rows (f ,blob .data (),a ,NT ,ffp ,0 ,FF ); 206for (int t = 0 ;t < NT ;++ t )native_quant_h (f ,ffs [t ].data (),hqs [t ].data ()); 207native_down_rows (f ,blob .data (),hp ,NT ,op ,0 ,H ); 208const auto * tg = ggml_get_type_traits_cpu ((ggml_type )gu ); 209const auto * td = ggml_get_type_traits_cpu ((ggml_type )dn ); 210for (int t = 0 ;t < NT ;++ t ) { 211 std::vector < float > ff (FF ),out (H ); 212for (int r = 0 ;r < FF ;++ r ) { 213float gg = 0 ,uu = 0 ; 214tg -> vec_dot (H ,& gg ,0 ,blob .data ()+ (size_t )r * f .gu_row ,0 ,a [t ],0 ,1 ); 215tg -> vec_dot (H ,& uu ,0 ,blob .data ()+ f .up_off + (size_t )r * f .gu_row ,0 ,a [t ],0 ,1 ); 216ff [r ]= (gg / (1.f + std::exp (- gg )))* uu ; 217 } 218 std::vector < uint8_t > hq (kNativeHBytes ); 219native_quant_h (f ,ff .data (),hq .data ()); 220for (int r = 0 ;r < H ;++ r ) 221td -> vec_dot (FF ,& out [r ],0 ,blob .data ()+ f .down_off + (size_t )r * f .d_row ,0 ,hq .data (),0 ,1 ); 222double num = 0 ,den = 0 ; 223for (int r = 0 ;r < H ;++ r ) {num += std::pow ((double )outs [t ][r ]- out [r ],2 );den += (double )out [r ]* out [r ]; } 224worst = std::max (worst , std::sqrt (num /den )); 225// the same token alone through the engine path: the same bits as in the group of three 226 std::vector < float > ff1 (FF ),o1 (H ); 227float * f1 [1 ]= {ff1 .data ()}; 228float * o1p [1 ]= {o1 .data ()}; 229const void * a1 [1 ]= {a [t ]}; 230native_gu_rows (f ,blob .data (),a1 ,1 ,f1 ,0 ,FF ); 231 std::vector < uint8_t > h1 (kNativeHBytes ); 232native_quant_h (f ,ff1 .data (),h1 .data ()); 233const void * h1p [1 ]= {h1 .data ()}; 234native_down_rows (f ,blob .data (),h1p ,1 ,o1p ,0 ,H ); 235bitwise_group = bitwise_group && same_bits (o1 .data (),outs [t ].data (),H ); 236 } 237const bool ok = worst < 2e-3 && bitwise_group ; 238 std::printf (" expert %s/%s%s through native_gu_rows/native_down_rows (%s, %s): vs ggml-cpu vec_dot rel %.2e, " 239"alone vs in a group of %d: %s %s\n" , 240ggml_type_name ((ggml_type )gu ),ggml_type_name ((ggml_type )dn ),hadamard ?" +hadamard" :"" , 241tq_kernels_enabled () ?"tq kernels" :"ggml-cpu" ,tq_isa_name (tq_isa ()),worst ,NT , 242bitwise_group ?"bitwise equal" :"DIFFERENT" ,ok ?"ok" :"FAILED" ); 243return ok ?0 :1 ; 244} 245 246int synthetic (int gu ,int dn ,bool hadamard ) { 247int fails = 0 ; 248 std::printf ("%s/%s%s (tq kernels: %s, best ISA here %s)\n" ,ggml_type_name ((ggml_type )gu ), 249ggml_type_name ((ggml_type )dn ),hadamard ?" +hadamard" :"" ,tq_kernels_enabled () ?"on" :"off" , 250tq_isa_name (tq_isa ())); 251 std::printf (" %s, 96 rows of %d (gate/up shape)\n" ,ggml_type_name ((ggml_type )gu ),H ); 252fails += check_matrix (gu ,96 ,H ,1000 + gu ,hadamard ); 253 std::printf (" %s, 256 rows of %d (down shape)\n" ,ggml_type_name ((ggml_type )dn ),FF ); 254fails += check_matrix (dn ,256 ,FF ,2000 + dn ,hadamard ); 255fails += check_expert (gu ,dn ,hadamard ); 256return fails ; 257} 258 259// ------------------------------------------------------------------------------------------------ the benchmark 260 261double now_us () { 262return std::chrono::duration < double , std::micro > (std::chrono::steady_clock::now ().time_since_epoch ()).count (); 263} 264 265struct BenchExpert { 266 std::vector < uint8_t > gu ,dn ;// gate rows then up rows; down rows 267size_t gu_row ,d_row ; 268}; 269 270// one variant: compute one expert (gate+up rows, then down rows) for `nt` tokens 271using ExpertFn = std::function < void (const BenchExpert & ,int nt )> ; 272 273// the core clock right now: a chain of dependent adds runs at one per cycle (GCC / Clang on x86-64; 0 elsewhere) 274double core_ghz () { 275#if defined(__GNUC__ )&& defined(__x86_64__ ) 276uint64_t x = 0 ; 277const long n = 1000000 ; 278const double t0 = now_us (); 279for (long i = 0 ;i < n ;++ i ) __asm__volatile ("add $1, %0\n\tadd $1, %0\n\tadd $1, %0\n\tadd $1, %0" :"+r" (x )); 280return 4.0 * n / ((now_us ()- t0 )* 1e3 ); 281#else 282return 0.0 ; 283#endif 284} 285 286constexpr double kBlocksPerExpert = 2.0 * FF * (H /128 )+ (double )H * (FF /128 );// 128-weight blocks 287 288// one slice of `ms` milliseconds cycling over the experts: ns per expert call and the clock around it (negated when 289// the clock moved by more than 5% during the slice: such samples count only when a variant has no other) 290std::pair < double ,double > time_slice (const std::vector < BenchExpert >& ex ,const ExpertFn & fn ,int nt ,double ms , 291size_t & next ) { 292const double g0 = core_ghz (); 293int it = 0 ; 294const double t0 = now_us (); 295double t1 = t0 ; 296do { 297fn (ex [next ++ %ex .size ()],nt ); 298++ it ; 299t1 = now_us (); 300 }while (t1 - t0 < ms * 1000.0 || it < 2 ); 301const double g1 = core_ghz (); 302const double ghz = 0.5 * (g0 + g1 ); 303return {(t1 - t0 )* 1e3 /it ,ghz > 0 && std::fabs (g1 - g0 )> 0.05 * g0 ?- ghz :ghz }; 304} 305 306double median (std::vector < double > v ) { 307if (v .empty ())return 0.0 ; 308 std::sort (v .begin (),v .end ()); 309return v [v .size () /2 ]; 310} 311 312// `threads` threads, each cycling over its own experts: aggregate weight GB/s 313double time_parallel (const std::vector < BenchExpert >& ex ,const ExpertFn & fn ,int threads ,double ms ) { 314 std::atomic < long > done {0 }; 315 std::atomic < bool > stop {false}; 316 std::vector < std::thread > th ; 317const double t0 = now_us (); 318for (int k = 0 ;k < threads ;++ k ) 319th .emplace_back ([& ,k ] { 320long c = 0 ; 321for (size_t i = (size_t )k ; !stop .load (std::memory_order_relaxed );i += (size_t )threads ,++ c ) 322fn (ex [i %ex .size ()],1 ); 323done += c ; 324 }); 325 std::this_thread::sleep_for (std::chrono::milliseconds ((int )ms )); 326stop = true; 327for (auto & t :th )t .join (); 328const double us = now_us ()- t0 ; 329const double bytes = (double ) (ex [0 ].gu_row * 2 * FF + ex [0 ].dn .size ())* (double )done .load (); 330return bytes / (us * 1e3 ); 331} 332 333int bench (bool quick ,const std::string & only ) { 334const int ncold = quick ?48 :96 ;// ~50-130 MB of weights: past the last-level cache 335 std::printf ("CPU: %s | AVX-512 kernels: %s, AVX2: %s | ggml-cpu built for this CPU (-march=native unless " 336"STRATA_PORTABLE)\n" ,cpu_name ().c_str (),cpu_avx512_ok () ?"yes" :"no" ,cpu_avx2_ok () ?"yes" :"no" ); 337 std::printf ("expert = gate+up %d x %d and down %d x %d of one type, %d distinct experts cycled (their weights come " 338"from DRAM, as a cache miss's do)\n\n" ,FF ,H ,H ,FF ,ncold ); 339struct Variant { std::string name ;int type ;ExpertFn fn ;bool ok ; }; 340 std::vector < Variant > vars ; 341auto add_tq = [& ](int type ) { 342for (TqIsa isa : {TqIsa ::scalar ,TqIsa ::avx2 ,TqIsa ::avx512 }) { 343vars .push_back ({std::string ("strata " )+ tq_isa_name (isa ),type , 344 [type ,isa ](const BenchExpert & e ,int nt ) { 345 thread_local std::vector < uint8_t > a ,h ; 346 thread_local std::vector < float > ff ,out ; 347a .resize (ggml_row_size (GGML_TYPE_Q8_0 ,H )* kTqMaxTokens ); 348h .resize (ggml_row_size (GGML_TYPE_Q8_0 ,FF )* kTqMaxTokens ); 349ff .resize ((size_t )FF * kTqMaxTokens ); 350out .resize ((size_t )H * kTqMaxTokens ); 351const void * ap [kTqMaxTokens ]; 352const void * hp [kTqMaxTokens ]; 353float * fp [kTqMaxTokens ]; 354float * op [kTqMaxTokens ]; 355for (int t = 0 ;t < nt ;++ t ) { 356ap [t ]= a .data ()+ t * ggml_row_size (GGML_TYPE_Q8_0 ,H ); 357hp [t ]= h .data ()+ t * ggml_row_size (GGML_TYPE_Q8_0 ,FF ); 358fp [t ]= ff .data ()+ (size_t )t * FF ; 359op [t ]= out .data ()+ (size_t )t * H ; 360 } 361tq_gu_rows (isa ,type ,e .gu .data (),e .gu_row ,e .gu_row * FF ,H ,ap ,nt ,fp ,0 ,FF ); 362tq_rows (isa ,type ,e .dn .data (),e .d_row ,FF ,hp ,nt ,op ,0 ,H ); 363 }, 364tq_isa_ok (isa )}); 365 } 366vars .push_back ({"ggml-cpu vec_dot" ,type , 367 [type ](const BenchExpert & e ,int nt ) { 368const auto * tc = ggml_get_type_traits_cpu ((ggml_type )type ); 369 thread_local std::vector < uint8_t > a (ggml_row_size (GGML_TYPE_Q8_0 ,H )), 370h (ggml_row_size (GGML_TYPE_Q8_0 ,FF )); 371 thread_local std::vector < float > ff (FF ),out (H ); 372for (int t = 0 ;t < nt ;++ t ) { 373for (int r = 0 ;r < FF ;++ r ) { 374float g ,u ; 375tc -> vec_dot (H ,& g ,0 ,e .gu .data ()+ (size_t )r * e .gu_row ,0 ,a .data (),0 ,1 ); 376tc -> vec_dot (H ,& u ,0 ,e .gu .data ()+ (size_t ) (FF + r )* e .gu_row ,0 ,a .data (),0 ,1 ); 377ff [r ]= (g / (1.f + std::exp (- g )))* u ; 378 } 379for (int r = 0 ;r < H ;++ r ) 380tc -> vec_dot (FF ,& out [r ],0 ,e .dn .data ()+ (size_t )r * e .d_row ,0 ,h .data (),0 ,1 ); 381 } 382 }, 383 true}); 384 }; 385auto add_q2 = [& ](bool avx512 ) { 386vars .push_back ({avx512 ?"strata Q2_0 avx512" :"strata Q2_0 avx2" ,42 , 387 [avx512 ](const BenchExpert & e ,int nt ) { 388 thread_localActQ a1 [MAXT ],a2 [MAXT ]; 389 thread_localbool init = false; 390if (!init ) {// real scales and codes (the kernel reads every field) 391const auto x = make_x (H ,3 ),h = make_x (FF ,4 ); 392for (int t = 0 ;t < MAXT ;++ t ) {act_quant_q8_1_avx2 (x .data (),H ,a1 [t ]);act_quant_q8_1_avx2 (h .data (),FF ,a2 [t ]); } 393init = true; 394 } 395 thread_localfloat g [MAXT ][FF ],u [MAXT ][FF ],out [MAXT ][H ]; 396const ActQ * ap [MAXT ]; 397const ActQ * hp [MAXT ]; 398float * gp [MAXT ]; 399float * up [MAXT ]; 400float * op [MAXT ]; 401for (int t = 0 ;t < nt ;++ t ) {ap [t ]= & a1 [t ];hp [t ]= & a2 [t ];gp [t ]= g [t ];up [t ]= u [t ];op [t ]= out [t ]; } 402auto rows = avx512 ?q2_0_gguf_rows_multi :q2_0_gguf_rows_multi_avx2 ; 403rows (e .gu .data (),e .gu_row ,H /64 ,ap ,nt ,gp ,0 ,FF ); 404rows (e .gu .data ()+ e .gu_row * FF ,e .gu_row ,H /64 ,ap ,nt ,up ,0 ,FF ); 405for (int t = 0 ;t < nt ;++ t ) 406for (int r = 0 ;r < FF ;++ r )g [t ][r ]= (g [t ][r ] / (1.f + std::exp (- g [t ][r ])))* u [t ][r ]; 407rows (e .dn .data (),e .d_row ,FF /64 ,hp ,nt ,op ,0 ,H ); 408 }, 409avx512 ?cpu_avx512_ok () :cpu_avx2_ok ()}); 410 }; 411for (int type : {145 ,146 ,144 })add_tq (type ); 412add_q2 (false); 413add_q2 (true); 414// the Q2_0 pack's own AVX-512 kernel (the repacked 1,382,400-byte blob that setup makes on AVX-512 CPUs) 415vars .push_back ({"strata Q2_0 avx512 pack" ,42 , 416 [](const BenchExpert & e ,int nt ) { 417 thread_localActQ a1 ,a2 ; 418 thread_localbool init = false; 419if (!init ) { 420const auto x = make_x (H ,3 ),h = make_x (FF ,4 ); 421act_quant_q8_1 (x .data (),H ,a1 ); 422act_quant_q8_1 (h .data (),FF ,a2 ); 423init = true; 424 } 425 thread_localfloat ff [FF ],out [H ]; 426for (int t = 0 ;t < nt ;++ t ) {// its multi-token kernels are the same per token 427s2_expert_gu_rows (e .gu .data (),a1 ,ff ,0 ,FF ); 428s2_expert_down_rows (e .gu .data (),a2 ,out ,0 ,H ); 429 } 430 }, 431cpu_avx512_ok ()}); 432 433auto make_experts = [& ](int type ,int count ) { 434 std::vector < BenchExpert > v ((size_t )count ); 435for (int k = 0 ;k < count ;++ k ) { 436BenchExpert & e = v [(size_t )k ]; 437e .gu_row = ggml_row_size ((ggml_type )type ,H ); 438e .d_row = ggml_row_size ((ggml_type )type ,FF ); 439// (Q2_0: room for one repacked blob too, which the pack kernel reads from the same buffer) 440e .gu .resize (type == 42 ? std::max (e .gu_row * 2 * FF , (size_t )BLOB ) :e .gu_row * 2 * FF ); 441e .dn .resize (e .d_row * H ); 442 std::mt19937 rng (77 + k ); 443for (auto & b :e .gu )b = (uint8_t )rng (); 444for (auto & b :e .dn )b = (uint8_t )rng (); 445// sane fp16 scales at every block start (Q2_0: 18-byte blocks, TQ: 26/30/34) 446const size_t bsz = type == 42 ?18 :ggml_row_size ((ggml_type )type ,128 ); 447const uint16_t d = f2h (0.01f ); 448for (size_t o = 0 ;o + bsz <=e .gu .size ();o += bsz ) std::memcpy (e .gu .data ()+ o ,& d ,2 ); 449for (size_t o = 0 ;o + bsz <=e .dn .size ();o += bsz ) std::memcpy (e .dn .data ()+ o ,& d ,2 ); 450if (type == 42 ) {// the same bytes also hold one repacked Q2_0 blob (codes, then fp16 scales) 451for (size_t o = O_GU_SCALES ;o + 2 <=BLOB ;o += 2 ) std::memcpy (e .gu .data ()+ o ,& d ,2 ); 452 } 453 } 454return v ; 455 }; 456// Single thread, the variants of a type interleaved in short slices over several rounds (this machine's clock 457// moves; a slice whose clock moved is dropped), medians reported: ns and core cycles per 128-weight block, us 458// per expert, weight GB/s; and per token in a group of three (a verify window's tokens routed to one expert). 459// The activations are zero-filled (the kernels do not branch on values) except Q2_0's, which are real. 460const int rounds = quick ?5 :15 ; 461const double slice_ms = quick ?40 :60 ; 462 std::printf ("%-6s %-24s %9s %8s %8s %8s | %10s %8s\n" ,"type" ,"kernel" ,"us/expert" ,"ns/blk" ,"cyc/blk" ,"GB/s" , 463"x3: us/tok" ,"cyc/blk" ); 464for (int type : {145 ,146 ,144 ,42 }) { 465const auto cold = make_experts (type ,ncold ); 466const double eb = (double ) (cold [0 ].gu_row * 2 * FF + cold [0 ].dn .size ());// weight bytes per expert 467 std::vector < const Variant *> vs ; 468for (const auto & v :vars ) 469if (v .type == type && v .name .find (only )!= std::string::npos ) { 470if (v .ok )vs .push_back (& v ); 471else std::printf ("%-6s %-24s (not on this CPU)\n" ,ggml_type_name ((ggml_type )type ),v .name .c_str ()); 472 } 473 std::vector < std::vector < double >> ns1 (vs .size ()),cy1 (vs .size ()),ns3 (vs .size ()),cy3 (vs .size ()); 474 std::vector < std::vector < double >> ns1m (vs .size ()),cy1m (vs .size ()),ns3m (vs .size ()),cy3m (vs .size ()); 475size_t next = 0 ; 476for (auto * v :vs )v -> fn (cold [0 ],3 );// warm-up: tables, buffers 477for (int r = 0 ;r < rounds ;++ r ) 478for (size_t k = 0 ;k < vs .size ();++ k ) { 479const bool slow = vs [k ]-> name .find ("scalar" )!= std::string::npos ; 480const auto a = time_slice (cold ,vs [k ]-> fn ,1 ,slow ?slice_ms /2 :slice_ms ,next ); 481const auto b = time_slice (cold ,vs [k ]-> fn ,3 ,slow ?slice_ms /2 :slice_ms ,next ); 482if (a .second >=0 ) {ns1 [k ].push_back (a .first );cy1 [k ].push_back (a .first * a .second ); } 483else {ns1m [k ].push_back (a .first );cy1m [k ].push_back (- a .first * a .second ); } 484if (b .second >=0 ) {ns3 [k ].push_back (b .first );cy3 [k ].push_back (b .first * b .second ); } 485else {ns3m [k ].push_back (b .first );cy3m [k ].push_back (- b .first * b .second ); } 486 } 487 std::vector < size_t > steady (vs .size ()); 488for (size_t k = 0 ;k < vs .size ();++ k ) { 489steady [k ]= ns1 [k ].size (); 490if (ns1 [k ].empty ()) {ns1 [k ]= ns1m [k ];cy1 [k ]= cy1m [k ]; } 491if (ns3 [k ].empty ()) {ns3 [k ]= ns3m [k ];cy3 [k ]= cy3m [k ]; } 492 } 493for (size_t k = 0 ;k < vs .size ();++ k ) { 494const double n1 = median (ns1 [k ]),c1 = median (cy1 [k ]),n3 = median (ns3 [k ]),c3 = median (cy3 [k ]); 495 std::printf ("%-6s %-24s %9.1f %8.1f %8.1f %8.2f | %10.1f %8.1f (%zu/%d steady)\n" , 496ggml_type_name ((ggml_type )type ),vs [k ]-> name .c_str (),n1 /1e3 ,n1 /kBlocksPerExpert , 497c1 /kBlocksPerExpert ,eb /n1 ,n3 /3e3 ,c3 /kBlocksPerExpert ,steady [k ],rounds ); 498 } 499 std::fflush (stdout ); 500 } 501// several workers at once (as the pool runs a layer's misses): aggregate GB/s on the cold set 502const int nthr = (int ) std::max (1u , std::min (4u , std::thread::hardware_concurrency ())); 503 std::printf ("\n%d threads at once, cold experts, one token: aggregate weight GB/s (us per expert per thread)\n" ,nthr ); 504for (int type : {145 ,146 ,144 ,42 }) { 505const auto cold = make_experts (type ,ncold ); 506const double eb = (double ) (cold [0 ].gu_row * 2 * FF + cold [0 ].dn .size ()); 507 std::vector < const Variant *> vs ; 508for (const auto & v :vars ) 509if (v .type == type && v .ok && v .name .find ("scalar" )== std::string::npos && v .name .find (only )!= std::string::npos ) 510vs .push_back (& v ); 511 std::vector < std::vector < double >> g (vs .size ()); 512for (int r = 0 ;r < (quick ?2 :4 );++ r ) 513for (size_t k = 0 ;k < vs .size ();++ k )g [k ].push_back (time_parallel (cold ,vs [k ]-> fn ,nthr ,quick ?150 :250 )); 514for (size_t k = 0 ;k < vs .size ();++ k ) { 515const double gbs = median (g [k ]); 516 std::printf ("%-6s %-24s %8.2f GB/s (%7.1f us per expert per thread)\n" ,ggml_type_name ((ggml_type )type ), 517vs [k ]-> name .c_str (),gbs ,eb / (gbs * 1e3 )* nthr ); 518 } 519 std::fflush (stdout ); 520 } 521// the per-token Hadamard rotation of one layer's activation (once per token per layer, shared by its experts) 522 { 523 std::vector < float > x = make_x (H ,5 ),s (H ,1.f ); 524const int it = 20000 ; 525const double t0 = now_us (); 526for (int i = 0 ;i < it ;++ i )hadamard_rotate (x .data (),H ,128 ,s .data ()); 527 std::printf ("\nHadamard rotation of one %d-wide activation (block 128): %.2f us\n" ,H , (now_us ()- t0 ) /it ); 528 } 529return 0 ; 530} 531 532}// namespace 533 534int main (int argc ,char ** argv ) { 535ggml_cpu_init (); 536if (GGML_TYPE_COUNT <=146 ) { 537 std::fprintf (stderr ,"this ggml has no trellis types (build with STRATA_GGML_DIR = the agention llama.cpp fork): skipped\n" ); 538return 77 ;// ctest SKIP_RETURN_CODE: a plain ggml is not a failure (#3358) 539 } 540if (argc >=2 && std::strcmp (argv [1 ],"--bench" )== 0 ) {// --bench [--quick] [--only <kernel name part>] 541bool quick = false; 542 std::string only ; 543for (int i = 2 ;i < argc ;++ i ) { 544if (std::strcmp (argv [i ],"--quick" )== 0 )quick = true; 545else if (std::strcmp (argv [i ],"--only" )== 0 && i + 1 < argc )only = argv [++ i ]; 546 } 547return bench (quick ,only ); 548 } 549if (argc >=3 && (std::strcmp (argv [1 ],"--synthetic" )== 0 || std::strcmp (argv [1 ],"--synthetic-hadamard" )== 0 )) { 550const std::string pair = argv [2 ]; 551const size_t sl = pair .find ('/' ); 552const int gu = type_by_name (pair .substr (0 ,sl )),dn = sl == std::string::npos ?gu :type_by_name (pair .substr (sl + 1 )); 553if (!tq_supported (gu )|| !tq_supported (dn )) { std::fprintf (stderr ,"not a trellis pair: %s\n" ,argv [2 ]);return 2 ; } 554const int f = synthetic (gu ,dn , std::strcmp (argv [1 ],"--synthetic-hadamard" )== 0 ); 555 std::printf ("%d failures\n" ,f ); 556return f ?1 :0 ; 557 } 558int f = 0 ; 559for (bool had : {false, true}) { 560f += synthetic (145 ,146 ,had );// Gyro-S 561f += synthetic (144 ,144 ,had );// Gyro-M 562 } 563 std::printf ("%d failures\n" ,f ); 564return f ?1 :0 ; 565}