okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7f46672a4
main
1// metal/tests/moe_mm_parity.cpp - the prompt-chunk routed experts (moe_mm.metal): plan, gate/up GEMM, down GEMM, 2// combine, against a CPU reference that rounds the activations and weights to fp16 as the kernels do (the matrix 3// units' operands) - and against the exact float reference for the size of that rounding; then the speed. 4// 5// moe_mm_parity [--gu Q2_0] [--dn Q2_0] [--T 256] [--tile 32,64,64,4] parity (64 experts) 6// moe_mm_parity --bench [--gu ..] [--dn ..] [--T 2048] [--tile ..] per-layer time, 512 experts 7#include "coop_probe.h" 8#include "mtl_rt.h" 9#include "ref_quant.h" 10#include "engine/geo.h" 11 12#include <algorithm> 13#include <cmath> 14#include <cstdio> 15#include <cstdlib> 16#include <cstring> 17#include <set> 18#include <string> 19#include <vector> 20 21namespace { 22int 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) 23constexpr int TOPK = strata_metal::geo::TOPK ; 24struct MmPlanArgs {uint32_t n_ent ,topk ,n_expert ,tm ,n_blocks ; }; 25struct MmArgs {uint64_t gate_off ,up_off ,down_off ,gu_stride ,d_stride ;uint32_t gu_row ,d_row ,n_embd ,n_ff ; }; 26double median (std::vector < double > v ) { std::sort (v .begin (),v .end ());return v [v .size () /2 ]; } 27int type_of (const std::string & s ) { 28for (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 }) 29if (s == ref::type_name (t ))return t ; 30 std::exit (2 ); 31} 32float h16 (float v ) {return ref::f16_to_f32 (ref::f32_to_f16 (v )); } 33}// namespace 34 35int main (int argc ,char ** argv ) { 36int gu = ref::Q2_0 ,dn = ref::Q2_0 ,T = 256 ,TM = 16 ,TN = 64 ,TK = 64 ,SG = 2 ,DTN = -1 ,DTK = -1 ,DSG = -1 ; 37bool bench = false,v2 = false,v3 = false,v4 = false,v5 = false,v6 = false; 38int MS = 1 ; 39for (int i = 1 ;i < argc ;++ i ) { 40 std::string a = argv [i ]; 41if (a == "--gu" )gu = type_of (argv [++ i ]); 42else if (a == "--dn" )dn = type_of (argv [++ i ]); 43else if (a == "--T" )T = std::atoi (argv [++ i ]); 44else if (a == "--ff" )N_FF = std::atoi (argv [++ i ]); 45else if (a == "--embd" )N_EMBD = std::atoi (argv [++ i ]); 46else if (a == "--tile" ) std::sscanf (argv [++ i ],"%d,%d,%d,%d" ,& TM ,& TN ,& TK ,& SG ); 47else if (a == "--dtile" ) std::sscanf (argv [++ i ],"%d,%d,%d" ,& DTN ,& DTK ,& DSG );// the down kernel's TN,TK,SG 48else if (a == "--bench" )bench = true; 49else if (a == "--v2" )v2 = true; 50else if (a == "--v3" )v2 = v3 = true;// v2's gather + the register-operand GEMMs (TN per simdgroup) 51else if (a == "--v4" ) {v2 = v3 = v4 = true;MS = std::atoi (argv [++ i ]); }// mm_gu4 with MS 16-row subtiles 52else if (a == "--v6" ) {v2 = v3 = true;v6 = true;MS = std::atoi (argv [++ i ]); }// mm_gu6 / mm_down6 / mm_scan6: groups of MS 16-row subtiles 53else if (a == "--v5" ) {v2 = v3 = true;v5 = true; }// mm_gu5 (weight blocks staged in threadgroup memory) 54 } 55if (bench && T == 256 )T = 2048 ; 56// v1 (mm_gu / mm_down) is the first-generation test kernel: the engine only ever dispatches mm_gu2 / mm_gu3 (window.cpp, prompt_chain.inc). 57// It has no IQ4_XS gate/up, so that type runs the v2 path here instead of failing at the pipeline lookup. 58if (!v2 && gu == ref::IQ4_XS ) {v2 = true; std::printf ("note: IQ4_XS gate/up has no v1 kernel (the engine does not use v1): running v2\n" ); } 59if (v4 )TM = 16 * MS ;// the plan's tile height; mm_gu4's name carries MS instead 60if (v6 )TM = 16 ;// ragged tiles: the padding is 16 rows, the group size is MS 61 mtl::Context cx ; 62// the host defines STRATA_KQ_DOWN only for a model whose downs are K-quant / IQ4_XS / IQ3_S (window.cpp kq_down_prelude) 63const 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 ; 64const int lib = cx .compile ({"quant.metal" ,"units.metal" ,"mma.metal" ,"moe_mm.metal" },kq_dn ?"#define STRATA_KQ_DOWN 1\n" :"" ); 65const int NE = bench ?512 :64 ,LAYERS = bench ?4 :1 ; 66const size_t gu_row = ref::row_bytes (gu ,N_EMBD ),d_row = ref::row_bytes (dn ,N_FF ); 67const size_t up_off = (size_t )N_FF * gu_row ,down_off = 2 * up_off ,blob = down_off + (size_t )N_EMBD * d_row ; 68 std::printf ("device %s; %s/%s, T %d, %d experts, tile TM %d TN %d TK %d SG %d\n" ,cx .device_name ().c_str (), 69 ref::type_name (gu ), ref::type_name (dn ),T ,NE ,TM ,TN ,TK ,SG ); 70 mtl::Buffer W = cx .alloc (blob * NE * LAYERS ); 71 { 72 std::vector < uint8_t > tmp (blob * 16 ); 73for (int e = 0 ;e < 16 ;++ e ) { 74 ref::random_blocks (gu ,tmp .data ()+ e * blob ,2 * N_FF ,N_EMBD ,100 + e ,0.02f ); 75 ref::random_blocks (dn ,tmp .data ()+ e * blob + down_off ,N_EMBD ,N_FF ,200 + e ,0.02f ); 76 } 77for (size_t e = 0 ;e < (size_t )NE * LAYERS ;++ e ) std::memcpy (W .as < uint8_t > ()+ e * blob ,tmp .data ()+ (e %16 )* blob ,blob ); 78 } 79const int nent = T * TOPK ,nblk = (nent + 1023 ) /1024 ; 80const int maxrows = nent + NE * TM ; 81 mtl::Buffer x = cx .alloc (4 * (size_t )T * N_EMBD ),ids = cx .alloc (4 * nent ),w = cx .alloc (4 * nent ), 82bcnt = cx .alloc (4 * (size_t )nblk * NE ),boff = cx .alloc (4 * (size_t )nblk * NE ),eoff = cx .alloc (4 * NE ), 83tiles = cx .alloc (8 * (size_t )(maxrows /TM + 1 )),meta = cx .alloc (64 ),stok = cx .alloc (4 * (size_t )maxrows ), 84sw = cx .alloc (4 * (size_t )maxrows ),pos = cx .alloc (4 * nent ),H = cx .alloc (4 * (size_t )maxrows * N_FF ), 85YE = cx .alloc (4 * (size_t )maxrows * N_EMBD ),y = cx .alloc (4 * (size_t )T * N_EMBD ), 86XS = cx .alloc (2 * (size_t )maxrows * N_EMBD ),HS = cx .alloc (2 * (size_t )maxrows * N_FF ); 87 ref::Rng r (7 ); 88for (size_t i = 0 ;i < (size_t )T * N_EMBD ;++ i )x .as < float > ()[i ]= r .sym (); 89for (int t = 0 ;t < T ;++ t ) { 90 std::set < int > used ; 91float s = 0 ; 92for (int k = 0 ;k < TOPK ;++ k ) { 93int e ; 94do e = (int )(r .next () %NE );while (used .count (e )); 95used .insert (e ); 96ids .as < int > ()[t * TOPK + k ]= e ; 97s += (w .as < float > ()[t * TOPK + k ]= 0.2f + r .uni ()); 98 } 99for (int k = 0 ;k < TOPK ;++ k )w .as < float > ()[t * TOPK + k ] /=s ; 100 } 101 mtl::Pipeline phist = cx .pipeline (lib ,"mm_hist" ),pscan = cx .pipeline (lib ,v6 ?"mm_scan6" :"mm_scan" ),pplace = cx .pipeline (lib ,"mm_place" ), 102pclear = cx .pipeline (lib ,"mm_clear" ),pcomb = cx .pipeline (lib ,"mm_combine" ); 103if (DTN < 0 ) {DTN = TN ;DTK = TK ;DSG = SG ; } 104if ((dn == ref::IQ4_NL || dn == ref::Q5_0 )&& DTK < 32 )DTK = 32 ;// 32-value units (the v2 / v3 down tiles of IQ4_NL / Q5_0 need TK >= 32) 105const std::string tl = std::to_string (TM )+ "_" + std::to_string (TN )+ "_" + std::to_string (TK )+ "_" + std::to_string (SG ); 106const std::string dtl = std::to_string (TM )+ "_" + std::to_string (DTN )+ "_" + std::to_string (DTK )+ "_" + std::to_string (DSG ); 107 std::string v6_gu ,v6_dn ; 108 mtl::Constants probe ; 109probe .i (5 , std::getenv ("MM_PROBE" ) ? std::atoi (std::getenv ("MM_PROBE" )) :0 ); 110const bool k4 = coop_k4 (cx ); 111if (v3 ) std::printf ("right-input layout: %s\n" ,k4 ?"runs of 4 k" :"other (per-element decode)" ); 112if (v6 ) {// the ragged-tile kernels: names carry MS, TN, TK, SG (TM is the plan's 16-row padding) 113const std::string tl6 = std::to_string (MS )+ "_" + std::to_string (TN )+ "_" + std::to_string (TK )+ "_" + std::to_string (SG ); 114const std::string dtl6 = std::to_string (MS )+ "_" + std::to_string (DTN )+ "_" + std::to_string (DTK )+ "_" + std::to_string (DSG ); 115v6_gu = "mm_gu6_" + std::to_string (gu )+ "_" + tl6 ; 116v6_dn = "mm_down6_" + std::to_string (dn )+ "_" + dtl6 ; 117 } 118 mtl::Pipeline pgu = v6 ?cx .pipeline (lib ,v6_gu , mtl::Constants ().b (7 ,k4 )) :v5 ?cx .pipeline (lib ,"mm_gu5_" + std::to_string (gu )+ "_" + std::to_string (TN )+ "_" + std::to_string (SG ), 119 mtl::Constants ().b (7 ,k4 )) 120 :v4 ?cx .pipeline (lib ,"mm_gu4_" + std::to_string (gu )+ "_" + std::to_string (MS )+ tl .substr (tl .find ('_' )), 121 mtl::Constants ().b (7 ,k4 ).i (5 , std::getenv ("MM_PROBE" ) ? std::atoi (std::getenv ("MM_PROBE" )) :0 )) 122 :v3 ?cx .pipeline (lib ,"mm_gu3_" + std::to_string (gu )+ "_" + tl , mtl::Constants ().b (7 ,k4 ).i (5 , std::getenv ("MM_PROBE" ) ? std::atoi (std::getenv ("MM_PROBE" )) :0 ).b (23 , std::getenv ("QUANT_CTAB" )!= nullptr )) 123 :cx .pipeline (lib , (v2 ?"mm_gu2_" :"mm_gu_" )+ std::to_string (gu )+ "_" + tl ,probe ), 124pdn = v6 ?cx .pipeline (lib ,v6_dn , mtl::Constants ().b (7 ,k4 )) :v3 ?cx .pipeline (lib ,"mm_down3_" + std::to_string (dn )+ "_" + dtl , mtl::Constants ().b (7 ,k4 )) 125 :cx .pipeline (lib , (v2 ?"mm_down2_" :"mm_down_" )+ std::to_string (dn )+ "_" + (v2 ?dtl :tl )), 126pgat = cx .pipeline (lib ,"mm_gather" ); 127MmPlanArgs pa {(uint32_t )nent ,TOPK , (uint32_t )NE , (uint32_t )(v6 ?MS :TM ), (uint32_t )nblk }; 128auto encode = [& ](int layer , std::vector < mtl::Dispatch >& ds ,bool plan ,bool gemm ) { 129if (plan ) { 130const uint32_t nclr = maxrows ; 131 mtl::Dispatch c ;c .p = & pclear ;c .args = {mtl::Arg ::B (stok ), mtl::Arg ::V (nclr )};c .grid [0 ]= (maxrows + 255 ) /256 ;c .tg [0 ]= 256 ;ds .push_back (c ); 132 mtl::Dispatch h ;h .p = & phist ;h .args = {mtl::Arg ::B (ids ), mtl::Arg ::B (bcnt ), mtl::Arg ::V (pa )};h .grid [0 ]= nblk ;h .tg [0 ]= 1024 ;ds .push_back (h ); 133meta .as < uint32_t > ()[2 ]= N_FF /TN ; 134 mtl::Dispatch sc ;sc .p = & pscan ;sc .args = {mtl::Arg ::B (bcnt ), mtl::Arg ::B (boff ), mtl::Arg ::B (eoff ), mtl::Arg ::B (tiles ), mtl::Arg ::B (meta ), mtl::Arg ::V (pa )};sc .tg [0 ]= NE ;ds .push_back (sc ); 135 mtl::Dispatch pl ;pl .p = & pplace ;pl .args = {mtl::Arg ::B (ids ), mtl::Arg ::B (w ), mtl::Arg ::B (boff ), mtl::Arg ::B (eoff ), mtl::Arg ::B (stok ), mtl::Arg ::B (sw ), mtl::Arg ::B (pos ), mtl::Arg ::V (pa )};pl .grid [0 ]= nblk ;pl .tg [0 ]= 1024 ;ds .push_back (pl ); 136 } 137if (gemm ) { 138MmArgs ma {(uint64_t )layer * NE * blob , (uint64_t )layer * NE * blob + up_off , (uint64_t )layer * NE * blob + down_off , 139blob ,blob , (uint32_t )gu_row , (uint32_t )d_row , (uint32_t )N_EMBD , (uint32_t )N_FF }; 140if (v2 || v3 ) {// v3 is v2's gather plus the register-operand GEMMs 141const uint32_t ne = N_EMBD ; 142 mtl::Dispatch ga ;ga .p = & pgat ;ga .args = {mtl::Arg ::B (x ), mtl::Arg ::B (stok ), mtl::Arg ::B (XS ), mtl::Arg ::V (ne )}; 143ga .grid [0 ]= meta .as < uint32_t > ()[1 ];ga .tg [0 ]= 256 ;ds .push_back (ga ); 144 } 145 mtl::Dispatch g ;g .p = & pgu ; 146if (v2 || v3 )g .args = {mtl::Arg ::B (W ), mtl::Arg ::B (XS ), mtl::Arg ::B (HS ), mtl::Arg ::B (tiles ), mtl::Arg ::V (ma )}; 147else g .args = {mtl::Arg ::B (W ), mtl::Arg ::B (x ), mtl::Arg ::B (H ), mtl::Arg ::B (stok ), mtl::Arg ::B (tiles ), mtl::Arg ::V (ma )}; 148g .grid [0 ]= N_FF / (v3 ?TN * SG :TN );g .grid [1 ]= meta .as < uint32_t > ()[0 ];g .tg [0 ]= 32 * SG ;ds .push_back (g ); 149 mtl::Dispatch d ;d .p = & pdn ;d .args = {mtl::Arg ::B (W ), mtl::Arg ::B (v2 || v3 ?HS :H ), mtl::Arg ::B (YE ), mtl::Arg ::B (tiles ), mtl::Arg ::V (ma )}; 150d .grid [0 ]= N_EMBD / (v3 ?DTN * DSG :v2 ?DTN :TN );d .grid [1 ]= meta .as < uint32_t > ()[0 ];d .tg [0 ]= 32 * ((v2 || v3 ) ?DSG :SG );ds .push_back (d ); 151const uint32_t ca [4 ]= {(uint32_t )T , (uint32_t )N_EMBD ,TOPK ,0 }; 152 mtl::Dispatch cb ;cb .p = & pcomb ;cb .args = {mtl::Arg ::B (YE ), mtl::Arg ::B (pos ), mtl::Arg ::B (sw ), mtl::Arg ::B (y ), mtl::Arg ::V (ca )}; 153cb .grid [0 ]= (T * N_EMBD + 255 ) /256 ;cb .tg [0 ]= 256 ;ds .push_back (cb ); 154 } 155 }; 156 { 157 std::vector < mtl::Dispatch > ds ; 158encode (0 ,ds , true, false); 159cx .run (ds );// the plan first: the GEMMs' grid is the tile count 160 } 161const uint32_t ntiles = meta .as < uint32_t > ()[0 ]; 162 std::printf ("plan: %u tiles of %d, %u padded rows for %d entries\n" ,ntiles ,TM ,meta .as < uint32_t > ()[1 ],nent ); 163if (!bench ) { 164// the plan: every entry placed once, rows of an expert contiguous and in entry order 165bool ok_plan = true; 166 std::vector < int > seen (maxrows ,0 ); 167for (int i = 0 ;i < nent ;++ i ) { 168const int row = pos .as < int > ()[i ]; 169if (row < 0 || row >= (int )meta .as < uint32_t > ()[1 ]|| stok .as < int > ()[row ]!= i /TOPK )ok_plan = false; 170else seen [row ]++ ; 171 } 172for (int i = 0 ;i < maxrows ;++ i )if (seen [i ]> 1 )ok_plan = false; 173 std::vector < mtl::Dispatch > ds ; 174encode (0 ,ds , false, true); 175cx .run (ds ); 176// reference: fp16 operands (x, weights, h), fp32+ accumulation; and the exact one 177double se16 = 0 ,se = 0 ,sr = 0 ; 178 std::vector < float > wg ((size_t )N_FF * N_EMBD ),wu (wg .size ()),wd ((size_t )N_EMBD * N_FF ); 179 std::vector < double > yr16 ((size_t )T * N_EMBD ,0.0 ),yr ((size_t )T * N_EMBD ,0.0 ); 180for (int e = 0 ;e < NE ;++ e ) { 181const uint8_t * b = W .as < uint8_t > ()+ e * blob ; 182bool any = false; 183for (int i = 0 ;i < nent && !any ;++ i )any = ids .as < int > ()[i ]== e ; 184if (!any )continue ; 185 ref::dequant (gu ,b ,wg .data (),wg .size ()); 186 ref::dequant (gu ,b + up_off ,wu .data (),wu .size ()); 187 ref::dequant (dn ,b + down_off ,wd .data (),wd .size ()); 188for (int i = 0 ;i < nent ;++ i ) { 189if (ids .as < int > ()[i ]!= e )continue ; 190const int t = i /TOPK ; 191const float * xt = x .as < float > ()+ (size_t )t * N_EMBD ; 192 std::vector < double > h16v (N_FF ),hv (N_FF ); 193for (int f = 0 ;f < N_FF ;++ f ) { 194double g = 0 ,u = 0 ,g16 = 0 ,u16 = 0 ; 195for (int k = 0 ;k < N_EMBD ;++ k ) { 196const float xk = xt [k ],xh = h16 (xk ); 197g += (double )wg [(size_t )f * N_EMBD + k ]* xk ; 198u += (double )wu [(size_t )f * N_EMBD + k ]* xk ; 199g16 += (double )h16 (wg [(size_t )f * N_EMBD + k ])* xh ; 200u16 += (double )h16 (wu [(size_t )f * N_EMBD + k ])* xh ; 201 } 202hv [f ]= g / (1 + std::exp (- g ))* u ; 203h16v [f ]= h16 ((float )(g16 / (1 + std::exp (- g16 ))* u16 )); 204 } 205const double wt = w .as < float > ()[i ]; 206for (int d = 0 ;d < N_EMBD ;++ d ) { 207double s = 0 ,s16 = 0 ; 208for (int f = 0 ;f < N_FF ;++ f ) { 209s += (double )wd [(size_t )d * N_FF + f ]* hv [f ]; 210s16 += (double )h16 (wd [(size_t )d * N_FF + f ])* h16v [f ]; 211 } 212yr [(size_t )t * N_EMBD + d ]+= wt * s ; 213yr16 [(size_t )t * N_EMBD + d ]+= wt * s16 ; 214 } 215 } 216 } 217for (size_t i = 0 ;i < yr .size ();++ i ) { 218const double g = y .as < float > ()[i ]; 219se16 += (g - yr16 [i ])* (g - yr16 [i ]); 220se += (g - yr [i ])* (g - yr [i ]); 221sr += yr [i ]* yr [i ]; 222 } 223uint64_t yh = 14695981039346656037ull ;// FNV-1a over y's bits: two runs (v3 TM 16, v6 groups) must print the same hash 224for (size_t i = 0 ;i < yr .size ();++ i ) {uint32_t u ; std::memcpy (& u ,y .as < float > ()+ i ,4 );yh = (yh ^u )* 1099511628211ull ; } 225 std::printf ("yhash %016llx\n" , (unsigned long long )yh ); 226const double rel16 = std::sqrt (se16 /sr ),rel = std::sqrt (se /sr ); 227const bool ok = ok_plan && rel16 < 2e-4 ; 228 std::printf ("parity: plan %s; y vs fp16-operand reference rel L2 %.2e, vs exact float reference %.2e %s\n" , 229ok_plan ?"ok" :"WRONG" ,rel16 ,rel ,ok ?"PASS" :"FAIL" ); 230return ok ?0 :1 ; 231 } 232// bench: the plan, the two GEMMs and the combine, LAYERS distinct weight sets rotated 233double flops = 0 ; 234 { 235const double rows = meta .as < uint32_t > ()[1 ]; 236flops = 2.0 * nent * (2.0 * N_FF * N_EMBD + (double )N_EMBD * N_FF ); 237 std::printf ("useful GFLOP per layer %.1f (padded rows %.0f = %.2fx entries)\n" ,flops /1e9 ,rows ,rows /nent ); 238 } 239auto timeit = [& ](bool plan ,bool gemm ,int part ) { 240 std::vector < mtl::Dispatch > ds ; 241for (int l = 0 ;l < 8 ;++ l ) { 242 std::vector < mtl::Dispatch > one ; 243encode (l %LAYERS ,one ,plan ,gemm ); 244if (part >=0 && gemm ) {ds .push_back (one [part ]);continue ; } 245for (auto & d :one )ds .push_back (d ); 246 } 247cx .warm (ds ,0.3 ); 248 std::vector < double > t ; 249for (int i = 0 ;i < 5 ;++ i )t .push_back (cx .run (ds ) /8 ); 250return median (t ); 251 }; 252const int o = v2 ?1 :0 ; 253const double tp = timeit (true, false,-1 ),tg = timeit (false, true,o ),td = timeit (false, true,o + 1 ), 254tc = timeit (false, true,o + 2 ),ta = timeit (false, true,-1 ); 255if (v2 ) std::printf ("gather %.1f us\n" ,timeit (false, true,0 )* 1e6 ); 256const double fgu = 2.0 * nent * 2.0 * N_FF * N_EMBD ,fdn = 2.0 * nent * N_EMBD * N_FF ; 257 std::printf ("per layer: plan %.1f us, gate/up %.1f us (%.1f TFLOP/s useful), down %.1f us (%.1f TFLOP/s), combine %.1f us;" 258" GEMMs + combine %.1f us = %.1f TFLOP/s; %.1f us per token per layer -> 48 layers: %.0f tok/s (experts only)\n" , 259tp * 1e6 ,tg * 1e6 ,fgu /tg /1e12 ,td * 1e6 ,fdn /td /1e12 ,tc * 1e6 ,ta * 1e6 ,flops /ta /1e12 , 260 (ta + tp ) /T * 1e6 ,T / (48 * (ta + tp ))); 261return 0 ; 262}