okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7f46672a4
main
1// metal/tests/expert_parity.cpp - the grouped routed-expert kernels (moe.metal) against a double-precision CPU 2// reference, and their speed. 3// 4// expert_parity [--gu Q2_0] [--dn Q2_0] [--ntok 1..8] [--gucfg L,R,S] [--dncfg L,R,S] parity (synthetic) 5// expert_parity --bench [--gu ..] [--dn ..] [--ntok N] [--layers 8] [--reps 96] [--sweep] speed 6// EXPERT_F16=1 expert_parity [--ntok N] [--gucfg ..] [--dncfg ..] the fp16 experts (STRATA_METAL_F16, Q2_0 only) 7// 8// Gyro (agentionai's trellis experts, TQ2_T / TQK6 / TQK7): 9// expert_parity --gu TQK6 --dn TQK7 [--had-pack <pack dir>] synthetic blocks; with a pack, the Hadamard rotation of 10// x (CPU) and of h (the Metal had128 kernel) is part of it 11// expert_parity --gguf <Gyro file> --layer L [--had-pack <pack dir>] [--ntok N] [--seed S] REAL experts of layer L (64 of 12// the 512, random) instead of random blocks 13// expert_parity --had-test [--had-pack <pack dir>] the Metal had128 kernels (f32, f16, f16 rows) against the CPU rotation, bitwise 14// 15// Parity: random valid blocks for 64 experts, random activations x ~ U(-1,1), random distinct top-10 per token, 16// weights summing to 1. Checked: the plan (groups by expert id, entries in (token, k) order), h = silu(gate) * up 17// per entry and y = sum_k w * down . h, each against double; reported as max |err| / max |ref| and relative L2. 18// Bench: `layers` distinct copies of a 512-expert arena (no reuse across reps beyond chance; the SLC is ~32 MB), 19// a different random routing per rep; GB/s = bytes of the distinct experts the kernel must read / GPU time. 20#include "mtl_rt.h" 21#include "ref_quant.h" 22#include "engine/geo.h" 23#include "gguf_lite.h" 24// Gyro: the engine's CPU Hadamard rotation (the reference of the Metal one) and hadamard.txt's parser 25#include "../../src/kernels/cpu/hadamard.cpp" 26 27#include <algorithm> 28#include <cmath> 29#include <cstdio> 30#include <cstdlib> 31#include <cstring> 32#include <map> 33#include <set> 34#include <string> 35#include <vector> 36 37#include "ggml-common-tq.h" 38const uint16_t * tq_lut_for_test () {return tq_lut_f16 ; } 39 40namespace { 41 42int N_EMBD = strata_metal::geo::N ,N_FF = strata_metal::geo::NFF ;// the shape this build is compiled for (engine/geo.h); --embd / --ff change them (Q4-KQ: expert widths 512 and 1024) 43constexpr int TOPK = strata_metal::geo::TOPK ; 44// plan layout (moe.metal) 45constexpr int P_NG = 0 ,P_IGU = 4 ,P_IDN = 8 ,P_MAXE = 128 ,P_GEXP = 16 ,P_GSTART = P_GEXP + P_MAXE , 46P_ETOK = P_GSTART + P_MAXE + 4 ,P_EW = P_ETOK + P_MAXE ,P_TOKENT = P_EW + P_MAXE , 47P_INTS = P_TOKENT + P_MAXE ; 48 49struct MoeArgs { 50uint64_t gate_off ,up_off ,down_off ,gu_stride ,d_stride ; 51uint32_t gu_row ,d_row ,n_embd ,n_ff ,n_tok ,topk ,n_expert ,gx_gu ,gx_dn ,pad ; 52}; 53 54int type_of (const std::string & s ) { 55for (int t : {ref::TQ2_T , ref::TQK6 , ref::TQK7 , ref::Q2_0 , ref::IQ3_XXS , ref::IQ2_XXS , ref::IQ2_XS , ref::IQ2_S , ref::IQ3_S , ref::IQ4_NL , ref::IQ4_XS , ref::Q3_K , ref::Q4_K , ref::Q5_K , ref::Q6_K , ref::Q8_0 , ref::Q5_1 , ref::Q5_0 }) 56if (s == ref::type_name (t ))return t ; 57 std::fprintf (stderr ,"unknown type %s\n" ,s .c_str ()); 58 std::exit (2 ); 59} 60 61struct Cfg {int L ,R ,S ; }; 62Cfg parse_cfg (const char * s ) { 63Cfg c {}; 64if (std::sscanf (s ,"%d,%d,%d" ,& c .L ,& c .R ,& c .S )!= 3 ) { std::fprintf (stderr ,"bad cfg %s\n" ,s ); std::exit (2 ); } 65return c ; 66} 67std::string kname (const char * k ,int t ,Cfg c ) { 68return std::string (k )+ "_" + std::to_string (t )+ "_" + std::to_string (c .L )+ "_" + std::to_string (c .R )+ "_" + 69 std::to_string (c .S ); 70} 71int rows_per_tg (Cfg c ) {return c .S * (32 /c .L )* c .R ; } 72 73struct Layout { 74int gu ,dn ; 75size_t gu_row ,d_row ,up_off ,down_off ,blob ; 76}; 77Layout layout (int gu ,int dn ) { 78Layout L {gu ,dn }; 79L .gu_row = ref::row_bytes (gu ,N_EMBD ); 80L .d_row = ref::row_bytes (dn ,N_FF ); 81L .up_off = (size_t )N_FF * L .gu_row ; 82L .down_off = 2 * L .up_off ; 83L .blob = L .down_off + (size_t )N_EMBD * L .d_row ; 84return L ; 85} 86 87void random_routing (ref::Rng & r ,int ntok ,int n_expert , std::vector < int >& ids , std::vector < float >& w , 88double share = 0.0 ,const std::vector < int >* prev = nullptr ) { 89ids .assign (ntok * TOPK ,0 ); 90w .assign (ntok * TOPK ,0.0f ); 91for (int t = 0 ;t < ntok ;++ t ) { 92 std::set < int > used ; 93float sum = 0 ; 94for (int k = 0 ;k < TOPK ;++ k ) { 95int e ; 96do { 97// with probability `share`, reuse an expert of the previous token (verify windows share experts) 98if (t > 0 && share > 0 && r .uni ()< share )e = ids [(t - 1 )* TOPK + (r .next () %TOPK )]; 99else e = (int )(r .next () %n_expert ); 100 }while (used .count (e )); 101used .insert (e ); 102ids [t * TOPK + k ]= e ; 103w [t * TOPK + k ]= 0.2f + r .uni (); 104sum += w [t * TOPK + k ]; 105 } 106for (int k = 0 ;k < TOPK ;++ k )w [t * TOPK + k ] /=sum ; 107 } 108 (void )prev ; 109} 110 111struct Kernels { 112 mtl::Pipeline plan ,gu ,dn ,comb ,prep ; 113Cfg cgu ,cdn ; 114}; 115int xkind (int t ) { 116switch (t ) { 117case ref::Q2_0 :return 1 ; 118case ref::Q4_K :case ref::Q5_K :return 2 ; 119case ref::Q6_K :case ref::Q3_K :return 3 ; 120default :return 0 ; 121 } 122} 123constexpr int CAPE = 8 * TOPK ;// entries capacity of h 124// prepared buffers: x [8][N_EMBD] -> XPX, h [CAPE][N_FF] -> XPH (4 planes + S16) 125#define PLANE_X ((size_t)8 * N_EMBD) 126#define PLANE_H ((size_t)CAPE * N_FF) 127 128mtl::Dispatch prep_dispatch (const mtl::Pipeline & p ,const mtl::Buffer & x ,const mtl::Buffer & xp ,uint32_t n ,uint32_t nt ) { 129 mtl::Dispatch d ; 130d .p = & p ; 131d .args = {mtl::Arg ::B (x ), mtl::Arg ::B (xp ), mtl::Arg ::V (n ), mtl::Arg ::V (nt )}; 132d .tg [0 ]= 256 ; 133d .grid [0 ]= (n /16 * nt + 255 ) /256 ; 134return d ; 135} 136 137int g_gu_type = 0 ,g_dn_type = 0 ; 138// Gyro: the rotation of h between the gate/up and the down dispatch (the Metal had128_f32 kernel, signs of width n_ff) 139struct HadArgs {uint32_t width ,x_stride ,y_stride ;float scale ;uint32_t has_signs ,pad ; }; 140const mtl::Pipeline * g_had32 = nullptr ; 141const mtl::Buffer * g_hsh = nullptr ; 142bool g_had_h = false; 143bool g_dn_prep = false;// Q2_0 down: prepared h (an xprep dispatch) instead of the raw-x decoder 144const mtl::Buffer * g_xpx = nullptr ; 145const mtl::Buffer * g_xph = nullptr ; 146// EXPERT_F16=1: moe_gu16 / moe_down16 (STRATA_METAL_F16) - x from the half plane x * 4^-(i % 4), h handed down as half 147const bool g_f16 = std::getenv ("EXPERT_F16" )!= nullptr ; 148const mtl::Buffer * g_h16 = nullptr ; 149 150void encode_layer (std::vector < mtl::Dispatch >& ds ,const Kernels & K ,const mtl::Buffer & W ,size_t w_off , 151const mtl::Buffer & x ,const mtl::Buffer & h ,const mtl::Buffer & ye ,const mtl::Buffer & y , 152const mtl::Buffer & ids ,const mtl::Buffer & wts ,const mtl::Buffer & plan ,size_t plan_off , 153const MoeArgs & a ,bool with_plan ,bool with_gu ,bool with_dn ,bool with_comb ) { 154const mtl::Buffer & XPX = * g_xpx ; 155const mtl::Buffer & XPH = * g_xph ; 156if (with_plan ) { 157 mtl::Dispatch d ; 158d .p = & K .plan ; 159d .args = {mtl::Arg ::B (ids ), mtl::Arg ::B (wts ), mtl::Arg ::B (plan ,plan_off ), mtl::Arg ::V (a )}; 160d .tg [0 ]= 512 ; 161ds .push_back (d ); 162 } 163if (with_gu ) { 164 mtl::Dispatch d ; 165d .p = & K .gu ; 166d .args = {mtl::Arg ::B (W ,w_off ), mtl::Arg ::B (XPX ,4 * PLANE_X * xkind (g_gu_type )), mtl::Arg ::B (h ), 167 mtl::Arg ::B (plan ,plan_off ), mtl::Arg ::V (a ), mtl::Arg ::B (XPX ,4 * PLANE_X * 4 )}; 168if (g_f16 ) { 169d .args [1 ]= mtl::Arg ::B (XPX ,4 * (4 * PLANE_X + PLANE_X /16 )+ 2 * PLANE_X ); 170d .args .push_back (mtl::Arg ::B (* g_h16 )); 171 } 172d .tg [0 ]= K .cgu .S * 32 ; 173d .indirect = & plan ; 174d .ind_off = plan_off + P_IGU * 4 ; 175ds .push_back (d ); 176if (g_had_h ) {// H h in place, one row per entry (the entries are the window's token x k) 177static HadArgs ha ; 178ha = HadArgs {(uint32_t )N_FF , (uint32_t )N_FF , (uint32_t )N_FF ,1.0f / std::sqrt (128.0f ),g_hsh ?1u :0u ,0u }; 179 mtl::Dispatch hd ; 180hd .p = g_had32 ; 181hd .args = {mtl::Arg ::B (h ), mtl::Arg ::B (h ), mtl::Arg ::B (g_hsh ?* g_hsh :h ), mtl::Arg ::V (ha )}; 182hd .grid [0 ]= N_FF /128 ; 183hd .grid [1 ]= a .n_tok * TOPK ; 184hd .tg [0 ]= 128 ; 185ds .push_back (hd ); 186 } 187 } 188if (with_dn ) { 189const int dk = g_dn_prep ?xkind (g_dn_type ) :0 ; 190if (dk )ds .push_back (prep_dispatch (K .prep ,h ,XPH ,N_FF ,CAPE )); 191 mtl::Dispatch d ; 192d .p = & K .dn ; 193d .args = {mtl::Arg ::B (W ,w_off ), 194dk ? mtl::Arg ::B (XPH ,4 * PLANE_H * dk ) : mtl::Arg ::B (h ), mtl::Arg ::B (ye ), 195 mtl::Arg ::B (plan ,plan_off ), mtl::Arg ::V (a ), mtl::Arg ::B (XPH ,4 * PLANE_H * 4 )}; 196if (g_f16 )d .args = {mtl::Arg ::B (W ,w_off ), mtl::Arg ::B (* g_h16 ), mtl::Arg ::B (ye ), mtl::Arg ::B (plan ,plan_off ), mtl::Arg ::V (a )}; 197d .tg [0 ]= K .cdn .S * 32 ; 198d .indirect = & plan ; 199d .ind_off = plan_off + P_IDN * 4 ; 200ds .push_back (d ); 201 } 202if (with_comb ) { 203 mtl::Dispatch d ; 204d .p = & K .comb ; 205d .args = {mtl::Arg ::B (ye ), mtl::Arg ::B (y ), mtl::Arg ::B (plan ,plan_off ), mtl::Arg ::V (a )}; 206d .tg [0 ]= 256 ; 207d .grid [0 ]= (a .n_tok * N_EMBD + 255 ) /256 ; 208ds .push_back (d ); 209 } 210} 211 212struct Err { 213double max_abs = 0 ,max_ref = 0 ,se = 0 ,sr = 0 ; 214void add (double got ,double ref ) { 215max_abs = std::max (max_abs , std::fabs (got - ref )); 216max_ref = std::max (max_ref , std::fabs (ref )); 217se += (got - ref )* (got - ref ); 218sr += ref * ref ; 219 } 220double rel_max ()const {return max_ref > 0 ?max_abs /max_ref :max_abs ; } 221double rel_l2 ()const {return sr > 0 ? std::sqrt (se /sr ) : std::sqrt (se ); } 222}; 223 224double median (std::vector < double > v ) { 225 std::sort (v .begin (),v .end ()); 226return v [v .size () /2 ]; 227} 228 229}// namespace 230 231int main (int argc ,char ** argv ) { 232int gu = ref::Q2_0 ,dn = ref::Q2_0 ,ntok = 1 ,layers = 8 ,reps = 96 ; 233Cfg cgu {32 ,2 ,4 },cdn {8 ,2 ,4 }; 234bool bench = false,sweep = false,had_test = false,decode_check = false; 235double share = 0.0 ; 236 std::string gguf_path ,had_pack ; 237int real_layer = 0 ,experts_first = 0 ; 238uint64_t seed = 1 ; 239bool cfg_gu_set = false,cfg_dn_set = false; 240for (int i = 1 ;i < argc ;++ i ) { 241 std::string a = argv [i ]; 242auto nx = [& ] {return i + 1 < argc ?argv [++ i ] : (std::fprintf (stderr ,"%s needs a value\n" ,a .c_str ()), std::exit (2 ), (char * )nullptr ); }; 243if (a == "--gu" )gu = type_of (nx ()); 244else if (a == "--dn" )dn = type_of (nx ()); 245else if (a == "--ntok" )ntok = std::atoi (nx ()); 246else if (a == "--gucfg" ) {cgu = parse_cfg (nx ());cfg_gu_set = true; } 247else if (a == "--dncfg" ) {cdn = parse_cfg (nx ());cfg_dn_set = true; } 248else if (a == "--bench" )bench = true; 249else if (a == "--sweep" )sweep = true; 250else if (a == "--layers" )layers = std::atoi (nx ()); 251else if (a == "--reps" )reps = std::atoi (nx ()); 252else if (a == "--share" )share = std::atof (nx ()); 253else if (a == "--dn-prep" )g_dn_prep = true; 254else if (a == "--gguf" )gguf_path = nx (); 255else if (a == "--layer" )real_layer = std::atoi (nx ()); 256else if (a == "--experts-first" )experts_first = std::atoi (nx ());// only experts 0..N-1 of the layer are in the file (a sparse copy) 257else if (a == "--had-pack" )had_pack = nx (); 258else if (a == "--had-test" )had_test = true; 259else if (a == "--decode-check" )decode_check = true; 260else if (a == "--ff" )N_FF = std::atoi (nx ()); 261else if (a == "--embd" )N_EMBD = std::atoi (nx ()); 262else if (a == "--seed" )seed = std::strtoull (nx (),nullptr ,10 ); 263else { std::fprintf (stderr ,"unknown argument %s\n" ,a .c_str ());return 2 ; } 264 } 265 (void )cfg_gu_set ; 266 (void )cfg_dn_set ; 267if (dn == ref::IQ4_NL && cdn .L == 8 && !cfg_dn_set )cdn = {4 ,2 ,4 }; 268 gguf::File gf ; 269const gguf::Tensor * tg_ = nullptr ,* tu_ = nullptr ,* td_ = nullptr ; 270if (!gguf_path .empty ()) {// real experts: the types come from the file 271 std::string err ; 272if (!gf .open (gguf_path ,err )) { std::fprintf (stderr ,"%s\n" ,err .c_str ());return 2 ; } 273const std::string b = "blk." + std::to_string (real_layer )+ "." ; 274tg_ = gf .find (b + "ffn_gate_exps.weight" ); 275tu_ = gf .find (b + "ffn_up_exps.weight" ); 276td_ = gf .find (b + "ffn_down_exps.weight" ); 277if (!tg_ || !tu_ || !td_ ) { std::fprintf (stderr ,"no routed experts in layer %d of %s\n" ,real_layer ,gguf_path .c_str ());return 2 ; } 278gu = tg_ -> type ; 279dn = td_ -> type ; 280 } 281 mtl::Context cx ; 282if (g_f16 && (gu != ref::Q2_0 || dn != ref::Q2_0 || g_dn_prep || !had_pack .empty ())) { 283 std::fprintf (stderr ,"EXPERT_F16: Q2_0 gate/up and down only, without --dn-prep and Hadamard\n" ); 284return 2 ; 285 } 286// the host defines STRATA_KQ_DOWN only for a model whose downs are K-quant / IQ4_XS / IQ3_S (window.cpp kq_down_prelude) 287const bool kq_dn = dn == ref::Q3_K || dn == ref::Q4_K || dn == ref::Q5_K || dn == ref::Q6_K || dn == ref::IQ3_S || dn == ref::IQ4_XS ; 288const int lib = cx .compile ({"quant.metal" ,"units.metal" ,"moe.metal" }, 289 std::string (g_f16 ?"#define STRATA_METAL_F16 1\n" :"" )+ (kq_dn ?"#define STRATA_KQ_DOWN 1\n" :"" )); 290const Layout L = layout (gu ,dn ); 291// Gyro: the pack's hadamard.txt (the signs of the widths 2560 and 640) -> the engine's CPU spec (the reference) 292 mtl::Buffer hsx ,hsh ; 293 mtl::Pipeline had32 = cx .pipeline (lib ,"had128_f32" ),had16 = cx .pipeline (lib ,"had128_f16" ),had16r = cx .pipeline (lib ,"had128_f16_rows" ); 294const float * sgx = nullptr ; 295const float * sgh = nullptr ; 296if (!had_pack .empty ()) { 297 strata::kernels::cpu::HadamardSpec spec ; 298 std::string err ; 299if (!strata::kernels::cpu::hadamard_parse (had_pack + "/hadamard.txt" ,48 ,spec ,err )) { 300 std::fprintf (stderr ,"%s\n" ,err .c_str ()); 301return 2 ; 302 } 303 strata::kernels::cpu::hadamard_set (std::move (spec )); 304sgx = strata::kernels::cpu::hadamard_signs (N_EMBD ); 305sgh = strata::kernels::cpu::hadamard_signs (N_FF ); 306if (sgx ) {hsx = cx .alloc (4 * N_EMBD ); std::memcpy (hsx .ptr ,sgx ,4 * N_EMBD ); } 307if (sgh ) {hsh = cx .alloc (4 * N_FF ); std::memcpy (hsh .ptr ,sgh ,4 * N_FF ); } 308g_had32 = & had32 ; 309g_hsh = sgh ?& hsh :nullptr ; 310g_had_h = !had_test ; 311 std::printf ("Hadamard: block %d, signs for %s%s\n" , strata::kernels::cpu::hadamard_spec ().block ,sgx ?"2560 " :"" ,sgh ?"640" :"(none)" ); 312 } 313if (decode_check ) { 314// the decoder the Metal kernels and ref_quant share the meaning of, written a third time straight from the format's 315// definition (ggml-common-tq.h): step t's state = 16 stream bits from bit (31 - t) * K, LSB first, circular modulo 32 K 316// bits, masked to 15 bits (TQ2_T: qs[(t + 31) % 32] << 8 | qs[t]); x = state * 0x9e3779b1; points lut[x >> 21] and 317// lut[(x >> 10) & 2047]; weights = fp16 values * d. Compared bit for bit with ref::dequant on the real tensors. 318extern const uint16_t * tq_lut_for_test (); 319long blocks = 0 ,bad = 0 ; 320const gguf::Tensor * ts [3 ]= {tg_ ,tu_ ,td_ }; 321if (!tg_ ) { std::fprintf (stderr ,"--decode-check needs --gguf\n" );return 2 ; } 322for (const gguf::Tensor * t :ts ) { 323const int ty = t -> type ,K = ty == ref::TQ2_T ?8 :ty == ref::TQK6 ?6 :7 ,bb = ref::block_bytes (ty ); 324const uint8_t * base = (const uint8_t * )gf .map + t -> offset ; 325const size_t nb = t -> bytes /bb ; 326const size_t step = std::max < size_t > (1 ,nb /200000 );// up to 200k blocks a tensor, spread over it 327for (size_t i = 0 ;i < nb ;i += step ) { 328const uint8_t * b = base + i * bb ; 329float want [128 ],got [128 ]; 330const float d = ref::f16_to_f32 ((uint16_t )(b [0 ] | (b [1 ] <<8 ))); 331const uint8_t * qs = b + 2 ; 332for (int st = 0 ;st < 32 ;++ st ) { 333uint32_t state ; 334if (K == 8 )state = (((uint32_t )qs [(st + 31 ) %32 ] <<8 ) |qs [st ])& 0x7fff ; 335else { 336const int off = ((31 - st )* K ) % (32 * K ); 337uint32_t v = 0 ; 338for (int bit = 0 ;bit < 16 ;++ bit ) { 339const int pos = (off + bit ) % (32 * K ); 340v |= (uint32_t )((qs [pos /8 ] >> (pos %8 ))& 1 ) <<bit ; 341 } 342state = v & 0x7fff ; 343 } 344const uint32_t x = state * 0x9e3779b1u ; 345const uint16_t * lut = tq_lut_for_test (); 346const uint32_t pa = x >>21 ,pb = (x >>10 )& 2047u ; 347want [4 * st ]= ref::f16_to_f32 (lut [2 * pa ])* d ; 348want [4 * st + 1 ]= ref::f16_to_f32 (lut [2 * pa + 1 ])* d ; 349want [4 * st + 2 ]= ref::f16_to_f32 (lut [2 * pb ])* d ; 350want [4 * st + 3 ]= ref::f16_to_f32 (lut [2 * pb + 1 ])* d ; 351 } 352 ref::dequant (ty ,b ,got ,128 ); 353bad += std::memcmp (want ,got ,sizeof want )!= 0 ; 354++ blocks ; 355 } 356 } 357 std::printf ("decode-check layer %d: %ld blocks of the real tensors, %ld differ from the format's definition %s\n" ,real_layer , 358blocks ,bad ,bad == 0 ?"PASS" :"FAIL" ); 359return bad == 0 ?0 :1 ; 360 } 361if (had_test ) { 362// the Metal rotation kernels against the CPU's (hadamard_rotate), bit for bit 363int bad = 0 ; 364 ref::Rng r2 (77 + seed ); 365for (int width : {N_FF ,N_EMBD }) { 366const int rows = 37 ; 367const float * sg = width == N_EMBD ?sgx :sgh ; 368const mtl::Buffer & sb = width == N_EMBD ?hsx :hsh ; 369const float scale = 1.0f / std::sqrt (128.0f ); 370 std::vector < float > in ((size_t )rows * width ); 371for (auto & v :in )v = r2 .sym ()* 3.0f ; 372 mtl::Buffer bx = cx .alloc (4 * in .size ()),by = cx .alloc (4 * in .size ()); 373 std::memcpy (bx .ptr ,in .data (),4 * in .size ()); 374HadArgs ha {(uint32_t )width , (uint32_t )width , (uint32_t )width ,scale ,sg ?1u :0u ,0u }; 375auto run32 = [& ](const mtl::Buffer & src ,const mtl::Buffer & dst ) { 376 mtl::Dispatch d ; 377d .p = & had32 ; 378d .args = {mtl::Arg ::B (src ), mtl::Arg ::B (dst ), mtl::Arg ::B (sg ?sb :src ), mtl::Arg ::V (ha )}; 379d .grid [0 ]= width /128 ;d .grid [1 ]= rows ;d .tg [0 ]= 128 ; 380cx .run ({d }); 381 }; 382run32 (bx ,by );// out of place 383 std::vector < float > want = in ; 384for (int r = 0 ;r < rows ;++ r ) strata::kernels::cpu::hadamard_rotate (want .data ()+ (size_t )r * width ,width ,128 ,sg ); 385int b32 = 0 ; 386for (size_t i = 0 ;i < in .size ();++ i )b32 += std::memcmp (& want [i ],by .as < float > ()+ i ,4 )!= 0 ; 387run32 (bx ,bx );// in place 388int b32i = 0 ; 389for (size_t i = 0 ;i < in .size ();++ i )b32i += std::memcmp (& want [i ],bx .as < float > ()+ i ,4 )!= 0 ; 390// f16 (no signs): out of place, and the rows kernel in place; the CPU's float result rounded to half 391 std::vector < _Float16 > hin (in .size ()); 392for (size_t i = 0 ;i < in .size ();++ i )hin [i ]= (_Float16 )in [i ]; 393 std::vector < float > hw (in .size ()); 394for (size_t i = 0 ;i < in .size ();++ i )hw [i ]= (float )hin [i ]; 395for (int r = 0 ;r < rows ;++ r ) strata::kernels::cpu::hadamard_rotate (hw .data ()+ (size_t )r * width ,width ,128 ,nullptr ); 396 mtl::Buffer hx = cx .alloc (2 * in .size ()),hy = cx .alloc (2 * in .size ()); 397 std::memcpy (hx .ptr ,hin .data (),2 * in .size ()); 398HadArgs hb {(uint32_t )width , (uint32_t )width , (uint32_t )width ,scale ,0u ,0u }; 399 { 400 mtl::Dispatch d ; 401d .p = & had16 ; 402d .args = {mtl::Arg ::B (hx ), mtl::Arg ::B (hy ), mtl::Arg ::B (hx ), mtl::Arg ::V (hb )}; 403d .grid [0 ]= width /128 ;d .grid [1 ]= rows ;d .tg [0 ]= 128 ; 404cx .run ({d }); 405 } 406int b16 = 0 ; 407for (size_t i = 0 ;i < in .size ();++ i ) { 408const _Float16 w = (_Float16 )hw [i ]; 409b16 += std::memcmp (& w ,hy .as < _Float16 > ()+ i ,2 )!= 0 ; 410 } 411 { 412 mtl::Dispatch d ; 413d .p = & had16r ; 414d .args = {mtl::Arg ::B (hx ), mtl::Arg ::B (hx ), mtl::Arg ::B (hx ), mtl::Arg ::V (hb )}; 415d .grid [0 ]= rows ;d .tg [0 ]= 128 ; 416cx .run ({d }); 417 } 418int b16r = 0 ; 419for (size_t i = 0 ;i < in .size ();++ i ) { 420const _Float16 w = (_Float16 )hw [i ]; 421b16r += std::memcmp (& w ,hx .as < _Float16 > ()+ i ,2 )!= 0 ; 422 } 423 std::printf ("had-test width %d, %d rows%s: f32 %d / f32 in place %d / f16 %d / f16 rows %d of %zu values differ from the CPU\n" , 424width ,rows ,sg ?" (with signs)" :" (no signs)" ,b32 ,b32i ,b16 ,b16r ,in .size ()); 425bad += b32 + b32i + b16 + b16r ; 426 } 427 std::printf ("had-test %s\n" ,bad == 0 ?"PASS (bitwise)" :"FAIL" ); 428return bad == 0 ?0 :1 ; 429 } 430 std::printf ("device %s; gate/up %s, down %s, blob %zu bytes; %d token(s)\n" ,cx .device_name ().c_str (), 431 ref::type_name (gu ), ref::type_name (dn ),L .blob ,ntok ); 432 433auto make = [& ](Cfg a ,Cfg b ) { 434Kernels K ; 435K .plan = cx .pipeline (lib ,"moe_plan" ); 436K .prep = cx .pipeline (lib ,"xprep" ); 437K .comb = cx .pipeline (lib ,"moe_combine" ); 438K .gu = cx .pipeline (lib ,kname (g_f16 ?"moe_gu16" :"moe_gu" ,gu ,a ), mtl::Constants ().i (22 , std::getenv ("MOE_PROBE" ) ? std::atoi (std::getenv ("MOE_PROBE" )) :0 ).b (23 , std::getenv ("QUANT_CTAB" )!= nullptr )); 439K .dn = cx .pipeline (lib ,kname (g_f16 ?"moe_down16" :"moe_down" ,dn == ref::Q2_0 && !g_dn_prep ?142 :dn ,b )); 440K .cgu = a ; 441K .cdn = b ; 442if (std::getenv ("PIPE_INFO" )) 443 std::printf ("pipelines: gu %s max threads %d tg mem %d | dn %s max threads %d tg mem %d\n" ,K .gu .name .c_str (),K .gu .max_threads , 444K .gu .static_tg_mem ,K .dn .name .c_str (),K .dn .max_threads ,K .dn .static_tg_mem ); 445return K ; 446 }; 447auto args_for = [& ](const Kernels & K ,int nt ,int n_expert ) { 448MoeArgs a {}; 449a .gate_off = 0 ; 450a .up_off = L .up_off ; 451a .down_off = L .down_off ; 452a .gu_stride = L .blob ; 453a .d_stride = L .blob ; 454a .gu_row = (uint32_t )L .gu_row ; 455a .d_row = (uint32_t )L .d_row ; 456a .n_embd = N_EMBD ; 457a .n_ff = N_FF ; 458a .n_tok = nt ; 459a .topk = TOPK ; 460a .n_expert = n_expert ; 461a .gx_gu = N_FF /rows_per_tg (K .cgu ); 462a .gx_dn = N_EMBD /rows_per_tg (K .cdn ); 463return a ; 464 }; 465 466 mtl::Buffer x = cx .alloc (4 * 8 * N_EMBD ),h = cx .alloc (4 * 8 * TOPK * N_FF ),ye = cx .alloc (4 * 8 * TOPK * N_EMBD ), 467y = cx .alloc (4 * 8 * N_EMBD ); 468 mtl::Buffer XPX = cx .alloc (4 * (4 * PLANE_X + PLANE_X /16 )+ (g_f16 ?2 * 3 * PLANE_X :0 )), 469XPH = cx .alloc (4 * (4 * PLANE_H + PLANE_H /16 )),h16 = g_f16 ?cx .alloc (2 * 8 * TOPK * N_FF ) : mtl::Buffer {}; 470g_xpx = & XPX ; 471g_h16 = & h16 ; 472g_xph = & XPH ; 473g_gu_type = gu ; 474g_dn_type = dn ; 475 ref::Rng rng (12345 + (seed - 1 )); 476for (int i = 0 ;i < 8 * N_EMBD ;++ i )x .as < float > ()[i ]= rng .sym (); 477if (g_had_h ) {// H (s * x) per token on the GPU, checked against the CPU's; x then holds the rotated rows 478 std::vector < float > want (x .as < float > (),x .as < float > ()+ 8 * N_EMBD ); 479for (int t = 0 ;t < 8 ;++ t ) strata::kernels::cpu::hadamard_rotate (want .data ()+ t * N_EMBD ,N_EMBD ,128 ,sgx ); 480HadArgs ha {(uint32_t )N_EMBD , (uint32_t )N_EMBD , (uint32_t )N_EMBD ,1.0f / std::sqrt (128.0f ),sgx ?1u :0u ,0u }; 481 mtl::Dispatch d ; 482d .p = & had32 ; 483d .args = {mtl::Arg ::B (x ), mtl::Arg ::B (x ), mtl::Arg ::B (sgx ?hsx :x ), mtl::Arg ::V (ha )}; 484d .grid [0 ]= N_EMBD /128 ;d .grid [1 ]= 8 ;d .tg [0 ]= 128 ; 485cx .run ({d }); 486int bad = 0 ; 487for (int i = 0 ;i < 8 * N_EMBD ;++ i )bad += std::memcmp (& want [i ],x .as < float > ()+ i ,4 )!= 0 ; 488 std::printf ("x rotation on the GPU vs the CPU: %d of %d values differ\n" ,bad ,8 * N_EMBD ); 489 } 490 { 491 mtl::Pipeline pp = cx .pipeline (lib ,"xprep" ,g_f16 ? mtl::Constants ().b (25 , true) : mtl::Constants ()); 492cx .run ({prep_dispatch (pp ,x ,XPX ,N_EMBD ,8 )}); 493 } 494 495if (!bench ) { 496// ---------------- parity ---------------- 497const int NE = tg_ && experts_first ? std::max (experts_first ,2 * TOPK ) :64 ; 498 mtl::Buffer W = cx .alloc (L .blob * NE ); 499 std::vector < int > pick ; 500for (int e = 0 ;e < NE ;++ e ) { 501uint8_t * b = W .as < uint8_t > ()+ e * L .blob ; 502if (tg_ ) {// real experts of the file: expert `ex` of the layer's three tensors 503int ex ; 504if (experts_first )ex = e %experts_first ;// (a sparse copy holds only the first experts: reused when NE is larger) 505else do ex = (int )(rng .next () %512 );while (std::find (pick .begin (),pick .end (),ex )!= pick .end ()); 506pick .push_back (ex ); 507 std::memcpy (b , (const uint8_t * )gf .map + tg_ -> offset + (size_t )ex * L .gu_row * N_FF ,L .gu_row * N_FF ); 508 std::memcpy (b + L .up_off , (const uint8_t * )gf .map + tu_ -> offset + (size_t )ex * L .gu_row * N_FF ,L .gu_row * N_FF ); 509 std::memcpy (b + L .down_off , (const uint8_t * )gf .map + td_ -> offset + (size_t )ex * L .d_row * N_EMBD ,L .d_row * N_EMBD ); 510 }else { 511 ref::random_blocks (gu ,b ,2 * N_FF ,N_EMBD ,1000 + e + 100 * (seed - 1 )); 512 ref::random_blocks (dn ,b + L .down_off ,N_EMBD ,N_FF ,5000 + e + 100 * (seed - 1 )); 513 } 514 } 515 std::vector < int > ids ; 516 std::vector < float > w ; 517random_routing (rng ,ntok ,NE ,ids ,w ,0.3 ); 518 mtl::Buffer bid = cx .alloc (4 * ids .size ()),bw = cx .alloc (4 * w .size ()),plan = cx .alloc (4 * P_INTS ); 519 std::memcpy (bid .ptr ,ids .data (),4 * ids .size ()); 520 std::memcpy (bw .ptr ,w .data (),4 * w .size ()); 521Kernels K = make (cgu ,cdn ); 522MoeArgs a = args_for (K ,ntok ,512 ); 523 std::vector < mtl::Dispatch > ds ; 524encode_layer (ds ,K ,W ,0 ,x ,h ,ye ,y ,bid ,bw ,plan ,0 ,a , true, true, true, true); 525cx .run (ds ); 526// the plan 527const int * P = plan .as < int > (); 528 std::set < int > distinct (ids .begin (),ids .end ()); 529bool plan_ok = P [P_NG ]== (int )distinct .size ()&& P [P_IGU + 1 ]== P [P_NG ]&& P [P_IDN + 1 ]== P [P_NG ]; 530 { 531int gi = 0 ; 532for (int e :distinct ) { 533if (P [P_GEXP + gi ]!= e )plan_ok = false; 534int j = P [P_GSTART + gi ]; 535for (int i = 0 ;i < ntok * TOPK ;++ i ) 536if (ids [i ]== e ) { 537if (P [P_ETOK + j ]!= i /TOPK || P [P_TOKENT + i ]!= j )plan_ok = false; 538float fw ; 539 std::memcpy (& fw ,& P [P_EW + j ],4 ); 540if (fw != w [i ])plan_ok = false; 541++ j ; 542 } 543if (j != P [P_GSTART + gi + 1 ])plan_ok = false; 544++ gi ; 545 } 546 } 547// the reference 548Err eh ,ey ; 549 std::vector < float > wg (N_FF * N_EMBD ),wu (N_FF * N_EMBD ),wd (N_EMBD * N_FF ); 550 std::vector < double > yref (ntok * N_EMBD ,0.0 ); 551for (int i = 0 ;i < ntok * TOPK ;++ i ) { 552const int e = ids [i ],t = i /TOPK ; 553const uint8_t * b = W .as < uint8_t > ()+ e * L .blob ; 554 ref::dequant (gu ,b ,wg .data (),wg .size ()); 555 ref::dequant (gu ,b + L .up_off ,wu .data (),wu .size ()); 556 ref::dequant (dn ,b + L .down_off ,wd .data (),wd .size ()); 557const float * xt = x .as < float > ()+ t * N_EMBD ; 558 std::vector < double > hr (N_FF ); 559const int ent = P [P_TOKENT + i ]; 560for (int r = 0 ;r < N_FF ;++ r ) { 561double g = 0 ,u = 0 ; 562for (int k = 0 ;k < N_EMBD ;++ k ) { 563g += (double )wg [r * N_EMBD + k ]* xt [k ]; 564u += (double )wu [r * N_EMBD + k ]* xt [k ]; 565 } 566hr [r ]= g / (1.0 + std::exp (- g ))* u ; 567 } 568if (g_had_h ) {// the reference of the down input: H h, in float as the engine's CPU path does 569 std::vector < float > hf (N_FF ); 570for (int r = 0 ;r < N_FF ;++ r )hf [r ]= (float )hr [r ]; 571 strata::kernels::cpu::hadamard_rotate (hf .data (),N_FF ,128 ,sgh ); 572for (int r = 0 ;r < N_FF ;++ r )hr [r ]= hf [r ]; 573 } 574for (int r = 0 ;r < N_FF ;++ r )eh .add (h .as < float > ()[ent * N_FF + r ],hr [r ]); 575for (int r = 0 ;r < N_EMBD ;++ r ) { 576double s = 0 ; 577// the reference down uses the GPU's h (float) so that the y check isolates the down kernel ... 578for (int k = 0 ;k < N_FF ;++ k )s += (double )wd [r * N_FF + k ]* h .as < float > ()[ent * N_FF + k ]; 579yref [t * N_EMBD + r ]+= w [i ]* s ; 580 } 581 } 582for (int i = 0 ;i < ntok * N_EMBD ;++ i )ey .add (y .as < float > ()[i ],yref [i ]); 583// fp16: half products and h rounded to half on the way down - rel L2 ~1e-3 against double 584const double tl2 = g_f16 ?4e-3 :1e-5 ,tmax = g_f16 ?1e-2 :1e-4 ; 585const bool ok = plan_ok && eh .rel_l2 ()< tl2 && ey .rel_l2 ()< tl2 && eh .rel_max ()< tmax && ey .rel_max ()< tmax ; 586 std::printf ("parity %s/%s ntok %d gu %d,%d,%d dn %d,%d,%d: plan %s (%d groups), h rel L2 %.2e max %.2e, " 587"y rel L2 %.2e max %.2e %s\n" , 588 ref::type_name (gu ), ref::type_name (dn ),ntok ,cgu .L ,cgu .R ,cgu .S ,cdn .L ,cdn .R ,cdn .S , 589plan_ok ?"ok" :"WRONG" ,P [P_NG ],eh .rel_l2 (),eh .rel_max (),ey .rel_l2 (),ey .rel_max (), 590ok ?"PASS" :"FAIL" ); 591return ok ?0 :1 ; 592 } 593 594// ---------------- bench ---------------- 595const int NE = 512 ; 596const size_t layer_bytes = L .blob * NE ; 597 std::printf ("arena: %d layers x %d experts = %.2f GB (max buffer %.1f GB)\n" ,layers ,NE ,layers * layer_bytes /1e9 , 598cx .max_buffer_length () /1e9 ); 599 mtl::Buffer W = cx .alloc (layer_bytes * layers ); 600 { 601// 64 distinct random experts, copied over the arena 602 std::vector < uint8_t > tmp (L .blob * 64 ); 603for (int e = 0 ;e < 64 ;++ e ) { 604 ref::random_blocks (gu ,tmp .data ()+ e * L .blob ,2 * N_FF ,N_EMBD ,1000 + e ); 605 ref::random_blocks (dn ,tmp .data ()+ e * L .blob + L .down_off ,N_EMBD ,N_FF ,5000 + e ); 606 } 607for (size_t e = 0 ;e < (size_t )NE * layers ;++ e ) 608 std::memcpy (W .as < uint8_t > ()+ e * L .blob ,tmp .data ()+ (e %64 )* L .blob ,L .blob ); 609 } 610 std::vector < std::vector < int >> rids (reps ); 611 std::vector < std::vector < float >> rw (reps ); 612 mtl::Buffer bid = cx .alloc (4 * 8 * TOPK * reps ),bw = cx .alloc (4 * 8 * TOPK * reps ),plan = cx .alloc (4 * P_INTS * reps ); 613auto set_routing = [& ](int nt ) { 614double groups = 0 ; 615for (int r = 0 ;r < reps ;++ r ) { 616random_routing (rng ,nt ,NE ,rids [r ],rw [r ],share ); 617 std::memcpy (bid .as < int > ()+ r * 8 * TOPK ,rids [r ].data (),4 * rids [r ].size ()); 618 std::memcpy (bw .as < float > ()+ r * 8 * TOPK ,rw [r ].data (),4 * rw [r ].size ()); 619groups += std::set < int > (rids [r ].begin (),rids [r ].end ()).size (); 620 } 621return groups /reps ; 622 }; 623auto run_cfg = [& ](const Kernels & K ,int nt ,double groups ,bool const MoeArgs a = args_for (K ,nt ,NE ); 625 std::vector < mtl::Dispatch > dp ,dg ,dd ,dall ; 626for (int r = 0 ;r < reps ;++ r ) { 627const size_t woff = (size_t )(r %layers )* layer_bytes ; 628 std::vector < mtl::Dispatch > one ; 629encode_layer (one ,K ,W ,woff ,x ,h ,ye ,y ,bid ,bw ,plan , (size_t )r * P_INTS * 4 ,a , true, false, false, false); 630one [0 ].args [0 ]= mtl::Arg ::B (bid , (size_t )r * 8 * TOPK * 4 ); 631one [0 ].args [1 ]= mtl::Arg ::B (bw , (size_t )r * 8 * TOPK * 4 ); 632dp .push_back (one [0 ]); 633 std::vector < mtl::Dispatch > g ,d ; 634encode_layer (g ,K ,W ,woff ,x ,h ,ye ,y ,bid ,bw ,plan , (size_t )r * P_INTS * 4 ,a , false, true, false, false); 635encode_layer (d ,K ,W ,woff ,x ,h ,ye ,y ,bid ,bw ,plan , (size_t )r * P_INTS * 4 ,a , false, false, true, false); 636dg .push_back (g [0 ]); 637for (auto & z :d )dd .push_back (z ); 638dall .push_back (one [0 ]); 639dall .push_back (g [0 ]); 640for (auto & z :d )dall .push_back (z ); 641 } 642cx .run (dp );// plans in place 643cx .warm (dall ,0.1 ); 644 std::vector < double > tp ,tg ,td ,ta ; 645for (int it = 0 ;it < 7 ;++ it ) { 646tp .push_back (cx .run (dp ) /reps ); 647tg .push_back (cx .run (dg ) /reps ); 648td .push_back (cx .run (dd ) /reps ); 649ta .push_back (cx .run (dall ) /reps ); 650 } 651const double mp = median (tp ),mg = median (tg ),md = median (td ),ma = median (ta ); 652const double bg = groups * 2.0 * N_FF * L .gu_row ,bd = groups * N_EMBD * L .d_row ; 653if (printf ("ntok %d groups %5.1f | gu %2d,%d,%d %7.1f us %6.1f GB/s | dn %2d,%d,%d %7.1f us %6.1f GB/s | " 655"plan %5.1f us | layer %7.1f us = %6.1f GB/s (%4.1f%% of 585)\n" , 656nt ,groups ,K .cgu .L ,K .cgu .R ,K .cgu .S ,mg * 1e6 ,bg /mg /1e9 ,K .cdn .L ,K .cdn .R ,K .cdn .S , 657md * 1e6 ,bd /md /1e9 ,mp * 1e6 ,ma * 1e6 , (bg + bd ) /ma /1e9 , 658 (bg + bd ) /ma /1e9 /585 * 100 ); 659return std::make_pair (mg ,md ); 660 }; 661const std::vector < Cfg > gus = {{32 ,1 ,4 }, {32 ,2 ,4 }, {32 ,4 ,4 }, {32 ,2 ,2 }, {32 ,2 ,8 }, {32 ,1 ,8 }, 662 {16 ,1 ,4 }, {16 ,2 ,4 }, {8 ,1 ,4 }, {8 ,2 ,4 }, {8 ,1 ,2 }}; 663const std::vector < Cfg > dns = {{8 ,1 ,4 }, {8 ,2 ,4 }, {8 ,4 ,4 }, {8 ,1 ,8 }, {8 ,2 ,8 }, {4 ,1 ,4 }, 664 {4 ,2 ,4 }, {4 ,4 ,4 }, {16 ,1 ,4 }, {16 ,2 ,4 }, {32 ,1 ,4 }, {2 ,2 ,4 }}; 665 std::vector < int > ntoks = {ntok }; 666if (sweep )ntoks = {1 ,2 ,3 ,4 ,8 }; 667for (int nt :ntoks ) { 668const double groups = set_routing (nt ); 669if (sweep ) { 670// gate/up sweep with the default down, then down sweep with the best gate/up 671Cfg bgu = cgu ,bdn = cdn ; 672double best = 1e9 ; 673for (Cfg c :gus ) { 674if (N_FF %rows_per_tg (c ))continue ; 675auto t = run_cfg (make (c ,cdn ),nt ,groups , false); 676 std::printf (" gu %2d,%d,%d: %7.1f us %6.1f GB/s\n" ,c .L ,c .R ,c .S ,t .first * 1e6 , 677groups * 2.0 * N_FF * L .gu_row /t .first /1e9 ); 678if (t .first < best ) {best = t .first ;bgu = c ; } 679 } 680best = 1e9 ; 681for (Cfg c :dns ) { 682if (N_EMBD %rows_per_tg (c ))continue ; 683auto t = run_cfg (make (bgu ,c ),nt ,groups , false); 684 std::printf (" dn %2d,%d,%d: %7.1f us %6.1f GB/s\n" ,c .L ,c .R ,c .S ,t .second * 1e6 , 685groups * N_EMBD * L .d_row /t .second /1e9 ); 686if (t .second < best ) {best = t .second ;bdn = c ; } 687 } 688run_cfg (make (bgu ,bdn ),nt ,groups , true); 689 }else { 690run_cfg (make (cgu ,cdn ),nt ,groups , true); 691 } 692 } 693return 0 ; 694}