okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
62db0bf10
main
1// src/kernels/expdec_bench.cpp - the VRAM experts of a decode verify window: the default grouped kernels against 2// EXPDEC (STRATA_EXPDEC=1, docs/EXPERTDEC.md), bit for bit and in microseconds, per card, per T, per format pair. 3// 4// build/expdec_bench [reps = 300] [device = -1 (all)] [groups = 20] [pairs = all] [choices = def,dec,dec:r2,dec:b4,dec:r2:b4] [shape = real] 5// 6// The model's routed expert formats at its geometry (n_embd 2560, n_ff 640): gate/up IQ2_XXS (16), IQ2_XS (17), IQ3_XXS 7// (18), IQ3_S (21), IQ2_S (22); down IQ4_NL (20), Q2_0 (42). `pairs` is a comma list of gu/down type ids ("21/20,16/42") 8// or "all" (the 10 pairs). `choices` is a comma list of kernel choices: 9// def the default kernels (STRATA_EXPDEC off); the reference for the bitwise check 10// dec[:r<n>][:d<n>][:b<n>][:w<n>][:x<n>][:g<n>][:h<n>][:m<n>] 11// EXPDEC with r = gate/up rows per lane (1, 2), d = down rows per lane (1, 2, 4), b = the 12// gate/up kernel's min blocks per SM (2 | 4), w = 1 EXPDEC for the down too (the engine's 13// default is the gate/up only), x = 1 also for the IQ4_NL down, g / h = gate/up / down rows 14// per block (0 = auto), m = the auto rule's minimum blocks; a missing field takes the 15// engine's value (the environment's STRATA_EXPDEC_* or its default) 16// `shape`: real = every token picks 10 experts out of `groups` distinct ones (as fp_expert_bench: T=1 10 groups x 1 17// entry, T=2 20 x 1, T=4 20 groups with 40 entries); single = 10 T groups of one entry each (the same entries as `real` 18// spread over distinct experts); both = the two, plus the decomposition at the end: per-expert cost a = (single T=4 - 19// real T=2) / 20 and per-entry cost b = (real T=4 - real T=2) / 20, in us, for every choice (groups = 20 only). 20// 21// Per (device, pair, T, shape, choice): the output buffer against `def`'s, bit for bit (memcmp), and the median of 22// 5 rounds of `reps` back-to-back `native_expert_grouped` calls with CUDA events: the whole call (gate/up + SwiGLU + 23// q8_1 + down), then the gate/up phase and the down phase alone (native_expert_set_mode's phase, 3 rounds each). 24// The experts rotate over a pool of >= 96 MB of distinct synthetic blobs (random bytes, sane fp16 block scales), so 25// every call reads its weights cold from DRAM as the decode does each layer. 26// 27// One line per cell: dev T shape gu/d choice all_us gu_us down_us GB/s pct identical|DIFFERENT (GB/s = groups x blob 28// bytes / all_us; pct = of the peak DRAM bandwidth 2 x memory clock x bus width / 8). Lines starting with '#' are 29// context. Exit code 1 if any choice differs or a CUDA error occurred. GPU time only. 30#include "strata/kernels/iq_kernels.hpp" 31 32#include <cuda_runtime.h> 33 34#include <algorithm> 35#include <array> 36#include <cmath> 37#include <cstdint> 38#include <cstdio> 39#include <cstdlib> 40#include <cstring> 41#include <map> 42#include <random> 43#include <string> 44#include <tuple> 45#include <vector> 46 47namespace K = strata::kernels; 48 49namespace { 50 51constexpr int kEmbd = 2560 ,kFf = 640 ,kTop = 10 ,kMaxT = 4 ; 52constexpr int kMaxEntries = kMaxT * kTop ; 53 54struct Pair {int gu ,d ; }; 55const Pair kModelPairs []= { {16 ,20 }, {17 ,20 }, {18 ,20 }, {21 ,20 }, {22 ,20 }, {16 ,42 }, {17 ,42 }, {18 ,42 }, {21 ,42 }, {22 ,42 } }; 56 57const char * type_name (int t ) { 58switch (t ) { 59case 16 :return "IQ2_XXS" ;case 17 :return "IQ2_XS" ;case 18 :return "IQ3_XXS" ;case 21 :return "IQ3_S" ; 60case 22 :return "IQ2_S" ;case 20 :return "IQ4_NL" ;case 42 :return "Q2_0" ;default :return "?" ; 61 } 62} 63int qk_of (int t ) {return t == 20 ?32 :t == 42 ?64 :256 ; } 64 65struct Choice { 66 std::string name ; 67bool dec = false; 68K ::NativeExpertExpdecParams p ;// only explicitly specified fields set; unspecified fields keep their sentinels 69}; 70 71K ::NativeExpertExpdecParams resolve_choice_params (const K ::NativeExpertExpdecParams & base ,const Choice & c ) { 72K ::NativeExpertExpdecParams p = base ; 73if (c .p .gu_rows_per_lane > 0 )p .gu_rows_per_lane = c .p .gu_rows_per_lane ; 74if (c .p .down_rows_per_lane > 0 )p .down_rows_per_lane = c .p .down_rows_per_lane ; 75if (c .p .gu_min_blocks_per_sm > 0 )p .gu_min_blocks_per_sm = c .p .gu_min_blocks_per_sm ; 76if (c .p .down_iq4_nl >=0 )p .down_iq4_nl = c .p .down_iq4_nl ; 77if (c .p .down >=0 )p .down = c .p .down ; 78if (c .p .gu_rows_per_block >=0 )p .gu_rows_per_block = c .p .gu_rows_per_block ; 79if (c .p .down_rows_per_block >=0 )p .down_rows_per_block = c .p .down_rows_per_block ; 80if (c .p .min_blocks > 0 )p .min_blocks = c .p .min_blocks ; 81return p ; 82} 83 84// "def" | "dec[:r<n>][:d<n>][:b<n>][:x<n>][:g<n>][:h<n>][:m<n>]"; false on anything else 85bool parse_choice (const std::string & s ,Choice & c ) { 86c = Choice {}; 87c .name = s ; 88if (s == "def" )return true; 89if (s .rfind ("dec" ,0 )!= 0 )return false; 90c .dec = true; 91size_t i = 3 ; 92while (i < s .size ()) { 93if (s [i ]!= ':' )return false; 94size_t j = s .find (':' ,i + 1 ); 95if (j == std::string::npos )j = s .size (); 96if (j < i + 3 )return false; 97const char key = s [i + 1 ]; 98const int v = std::atoi (s .substr (i + 2 ,j - i - 2 ).c_str ()); 99switch (key ) { 100case 'r' :if (v != 1 && v != 2 )return false;c .p .gu_rows_per_lane = v ;break ; 101case 'd' :if (v != 1 && v != 2 && v != 4 )return false;c .p .down_rows_per_lane = v ;break ; 102case 'b' :if (v != 2 && v != 4 )return false;c .p .gu_min_blocks_per_sm = v ;break ; 103case 'x' :if (v != 0 && v != 1 )return false;c .p .down_iq4_nl = v ;break ; 104case 'w' :if (v != 0 && v != 1 )return false;c .p .down = v ;break ;// EXPDEC for the down (device default when omitted) 105case 'g' :if (v < 0 )return false;c .p .gu_rows_per_block = v ;break ; 106case 'h' :if (v < 0 )return false;c .p .down_rows_per_block = v ;break ; 107case 'm' :if (v <=0 )return false;c .p .min_blocks = v ;break ; 108default :return false; 109 } 110i = j ; 111 } 112return true; 113} 114 115void apply_choice (const K ::NativeExpertExpdecParams & base ,const Choice & c ) { 116K ::native_expert_set_expdec (c .dec ?1 :0 ); 117K ::native_expert_set_expdec_params (resolve_choice_params (base ,c )); 118} 119 120bool g_cuda_error = false; 121 122bool ck (cudaError_t e ,const char * what ) { 123if (e == cudaSuccess )return true; 124 std::printf ("CUDA: %s: %s\n" ,what ,cudaGetErrorString (e )); 125g_cuda_error = true; 126return false; 127} 128 129uint16_t sane_half (std::mt19937 & rng ) {// a finite fp16 of magnitude ~2^-10 .. 2^-6 130const uint32_t r = rng (); 131return (uint16_t ) (((r >>31 ) <<15 ) | ((5u + (r >>10 ) %5u ) <<10 ) | (r & 0x3ffu )); 132} 133 134// One expert blob [gate rows | up rows | down rows]: random bytes (any qs / qh / signs / scales nibble / grid index / 135// IQ4_NL nibble / Q2_0 pair is a valid code) with a sane fp16 `d` in every block (offset 0 of every format's block). 136void fill_blob (uint8_t * b ,const K ::NativeExpertLayout & L , std::mt19937 & rng ) { 137for (size_t i = 0 ;i + 4 <=L .bytes ;i += 4 ) { 138const uint32_t r = rng (); 139 std::memcpy (b + i ,& r ,4 ); 140 } 141const size_t gu_block = K ::iq_row_bytes (L .gu_type ,qk_of (L .gu_type )),d_block = K ::iq_row_bytes (L .d_type ,qk_of (L .d_type )); 142const size_t gu_blocks = (size_t )2 * (size_t )L .n_ff * (size_t ) (L .n_embd /qk_of (L .gu_type )); 143for (size_t k = 0 ;k < gu_blocks ;++ k ) { 144const uint16_t h = sane_half (rng ); 145 std::memcpy (b + k * gu_block ,& h ,2 ); 146 } 147const size_t d_blocks = (size_t )L .n_embd * (size_t ) (L .n_ff /qk_of (L .d_type )); 148for (size_t k = 0 ;k < d_blocks ;++ k ) { 149const uint16_t h = sane_half (rng ); 150 std::memcpy (b + L .down_off + k * d_block ,& h ,2 ); 151 } 152} 153 154struct Window { 155int groups = 0 ,entries = 0 ; 156 std::vector < int32_t > start ,tok ,dst ;// group g: entries [start[g], start[g + 1]); tok = token, dst = out row 157}; 158 159// real: T tokens, kTop experts each, `groups_req` distinct experts in all (capped at kTop * T, floored at kTop). 160// Expert j is forced onto token j % T so that every group has at least one entry; the rest of each token's picks are 161// random. 162Window build_real (int T ,int groups_req , std::mt19937 & rng ) { 163Window w ; 164const int G = std::min (std::max (groups_req ,kTop ),kTop * T ); 165 std::vector < std::vector < int >> picks ((size_t )G ); 166for (int k = 0 ;k < T ;++ k ) { 167 std::vector < char > in ((size_t )G ,0 ); 168int cnt = 0 ; 169for (int j = k ;j < G ;j += T ) {in [(size_t )j ]= 1 ;++ cnt ; } 170 std::vector < int > rest ; 171for (int j = 0 ;j < G ;++ j ) 172if (!in [(size_t )j ])rest .push_back (j ); 173 std::shuffle (rest .begin (),rest .end (),rng ); 174for (size_t i = 0 ;cnt < kTop ;++ i ,++ cnt )in [(size_t )rest [i ]]= 1 ; 175for (int j = 0 ;j < G ;++ j ) 176if (in [(size_t )j ])picks [(size_t )j ].push_back (k ); 177 } 178w .groups = G ; 179w .start .push_back (0 ); 180for (int g = 0 ;g < G ;++ g ) { 181for (int k :picks [(size_t )g ]) { 182w .tok .push_back (k ); 183w .dst .push_back ((int32_t )w .dst .size ()); 184 } 185w .start .push_back ((int32_t )w .dst .size ()); 186 } 187w .entries = (int )w .dst .size (); 188return w ; 189} 190// single: kTop T groups of one entry each (token g % T) 191Window build_single (int T ) { 192Window w ; 193w .groups = kTop * T ; 194w .start .push_back (0 ); 195for (int g = 0 ;g < w .groups ;++ g ) { 196w .tok .push_back (g %T ); 197w .dst .push_back (g ); 198w .start .push_back (g + 1 ); 199 } 200w .entries = w .groups ; 201return w ; 202} 203 204struct DevMem { 205 std::vector < void *> ptrs ; 206 ~DevMem () {for (void * p :ptrs )cudaFree (p ); } 207void * alloc (size_t n ) { 208void * p = nullptr ; 209if (!ck (cudaMalloc (& p ,n ),"malloc" ))return nullptr ; 210ptrs .push_back (p ); 211return p ; 212 } 213}; 214 215struct StreamEvents { 216cudaStream_t s = nullptr ; 217cudaEvent_t a = nullptr ,b = nullptr ; 218 ~StreamEvents () { 219if (a )cudaEventDestroy (a ); 220if (b )cudaEventDestroy (b ); 221if (s )cudaStreamDestroy (s ); 222 } 223}; 224 225// (device, pair gu, pair d, T, shape, choice) -> {all, gu, down} us 226using Key = std::tuple < int ,int ,int ,int , std::string , std::string > ; 227std::map < Key , std::array < double ,3 >> g_times ; 228 229bool run_device (int dev ,const K ::NativeExpertExpdecParams & dev_params ,int reps ,int groups_req , 230const std::vector < uint8_t >& pool ,size_t P ,size_t stride ,const std::vector < float >& xh , 231const K ::NativeExpertLayout & L ,const Pair & pair ,const std::vector < Choice >& choices , 232const std::vector < std::string >& shapes ,long long & bad ) { 233if (!ck (cudaSetDevice (dev ),"set device" ))return false; 234cudaDeviceProp pr {}; 235cudaGetDeviceProperties (& pr ,dev ); 236 std::printf ("# device %d: %s (sm_%d%d, %d SMs, L2 %d KB), %d reps x 5 rounds, <= %d groups, pool %d blobs x %.2f MB\n" ,dev , 237pr .name ,pr .major ,pr .minor ,pr .multiProcessorCount ,pr .l2CacheSize /1024 ,reps ,groups_req , (int )P , 238 (double )L .bytes /1e6 ); 239int mclk_khz = 0 ,bus_bits = 0 ; 240cudaDeviceGetAttribute (& mclk_khz ,cudaDevAttrMemoryClockRate ,dev ); 241cudaDeviceGetAttribute (& bus_bits ,cudaDevAttrGlobalMemoryBusWidth ,dev ); 242const double peak = 2.0 * (double )mclk_khz * 1e3 * (double )bus_bits /8.0 ;// bytes / s 243 std::printf ("# device %d peak DRAM bandwidth %.1f GB/s (memory clock %d kHz, bus %d bit)\n" ,dev ,peak /1e9 ,mclk_khz ,bus_bits ); 244const int gmax = kMaxEntries ; 245DevMem mem ; 246auto * dpool = (uint8_t * )mem .alloc (pool .size ()); 247auto * dx = (float * )mem .alloc (xh .size ()* sizeof (float )); 248void * dxq = mem .alloc ((size_t )kMaxT * kEmbd /32 * 36 ); 249void * dscr = mem .alloc (K ::native_expert_scratch_bytes (kMaxEntries ,kFf )); 250auto * dout = (float * )mem .alloc ((size_t )kMaxEntries * kEmbd * sizeof (float )); 251auto * dptr = (unsigned long long * )mem .alloc (P * (size_t )gmax * sizeof (unsigned long long )); 252auto * dstart = (int32_t * )mem .alloc ((size_t ) (gmax + 1 )* sizeof (int32_t )); 253auto * dn = (int32_t * )mem .alloc (sizeof (int32_t )); 254auto * ddst = (int32_t * )mem .alloc ((size_t )kMaxEntries * sizeof (int32_t )); 255auto * dtok = (int32_t * )mem .alloc ((size_t )kMaxEntries * sizeof (int32_t )); 256if (!dpool || !dx || !dxq || !dscr || !dout || !dptr || !dstart || !dn || !ddst || !dtok )return false; 257StreamEvents se ; 258if (!ck (cudaStreamCreate (& se .s ),"stream" )|| !ck (cudaEventCreate (& se .a ),"event" )|| 259 !ck (cudaEventCreate (& se .b ),"event" )) 260return false; 261void * stream = (void * )se .s ; 262if (!ck (cudaMemcpy (dpool ,pool .data (),pool .size (),cudaMemcpyHostToDevice ),"copy pool" )|| 263 !ck (cudaMemcpy (dx ,xh .data (),xh .size ()* sizeof (float ),cudaMemcpyHostToDevice ),"copy x" )) 264return false; 265K ::quantize_q8_1_rows (dx ,kMaxT ,kEmbd ,dxq ,stream ); 266if (!ck (cudaStreamSynchronize (se .s ),"quantize" ))return false; 267 268 std::mt19937 rng (20261012u ); 269bool ok = true; 270for (int T = 1 ;T <=kMaxT && ok ;++ T ) { 271for (const std::string & shape :shapes ) { 272if (!ok )break ; 273const Window w = shape == "single" ?build_single (T ) :build_real (T ,groups_req ,rng ); 274const int G = w .groups ,NE = w .entries ; 275// call i reads G experts starting at blob (i * G) % P: a fresh set until the pool wraps (>= 96 MB later) 276 std::vector < unsigned long long > hp (P * (size_t )G ); 277for (size_t i = 0 ;i < P ;++ i ) 278for (int g = 0 ;g < G ;++ g ) 279hp [i * (size_t )G + (size_t )g ]= (unsigned long long ) (dpool + ((i * (size_t )G + (size_t )g ) %P )* stride ); 280ok = ck (cudaMemcpy (dptr ,hp .data (),hp .size ()* sizeof (unsigned long long ),cudaMemcpyHostToDevice ),"copy ptrs" )&& 281ck (cudaMemcpy (dstart ,w .start .data (),w .start .size ()* sizeof (int32_t ),cudaMemcpyHostToDevice ),"copy start" )&& 282ck (cudaMemcpy (dn ,& G ,sizeof (int32_t ),cudaMemcpyHostToDevice ),"copy n" )&& 283ck (cudaMemcpy (ddst ,w .dst .data (),w .dst .size ()* sizeof (int32_t ),cudaMemcpyHostToDevice ),"copy dst" )&& 284ck (cudaMemcpy (dtok ,w .tok .data (),w .tok .size ()* sizeof (int32_t ),cudaMemcpyHostToDevice ),"copy tok" ); 285if (!ok )break ; 286 std::printf ("# T=%d %s: %d groups, %d entries, %.1f MB of weights per call\n" ,T ,shape .c_str (),G ,NE , 287 (double )G * (double )L .bytes /1e6 ); 288auto call = [& ](size_t i ) { 289K ::native_expert_grouped (L ,dptr + (i %P )* (size_t )G ,dstart ,dn ,ddst ,dtok ,G ,NE ,dxq ,dscr ,dout ,stream ,0 ); 290 }; 291auto timed = [& ](int phase ,int rounds ,double & out_us ) { 292K ::native_expert_set_mode (-1 ,phase ); 293for (size_t i = 0 ;i < (phase == 0 ?100u :20u );++ i )call (i ); 294 std::vector < double > rs ((size_t )rounds ); 295for (double & r :rs ) { 296cudaEventRecord (se .a ,se .s ); 297for (int i = 0 ;i < reps ;++ i )call ((size_t )i ); 298cudaEventRecord (se .b ,se .s ); 299cudaEventSynchronize (se .b ); 300float ms = 0.0f ; 301ok = ok && ck (cudaEventElapsedTime (& ms ,se .a ,se .b ),"elapsed" )&& ck (cudaGetLastError (),"kernel" ); 302r = 1000.0 * (double )ms /reps ; 303 } 304 std::sort (rs .begin (),rs .end ()); 305out_us = rs [(size_t )rounds /2 ]; 306K ::native_expert_set_mode (-1 ,0 ); 307 }; 308 std::vector < float > ref ,res ((size_t )NE * kEmbd ); 309for (size_t vi = 0 ;vi < choices .size ()&& ok ;++ vi ) { 310const Choice & c = choices [vi ]; 311apply_choice (dev_params ,c ); 312K ::native_expert_set_mode (-1 ,0 ); 313ok = ck (cudaMemset (dout ,0 , (size_t )NE * kEmbd * sizeof (float )),"memset out" ); 314call (0 ); 315ok = ok && ck (cudaStreamSynchronize (se .s ),"run" )&& ck (cudaGetLastError (),"kernel" )&& 316ck (cudaMemcpy (res .data (),dout ,res .size ()* sizeof (float ),cudaMemcpyDeviceToHost ),"copy out" ); 317if (!ok )break ; 318bool same = true; 319if (vi == 0 ) { 320ref = res ; 321long long nonfinite = 0 ; 322for (float f :ref )nonfinite += std::isfinite (f ) ?0 :1 ; 323if (nonfinite ) std::printf ("# T=%d: %s output has %lld non-finite values\n" ,T ,c .name .c_str (),nonfinite ); 324 }else { 325same = std::memcmp (ref .data (),res .data (),ref .size ()* sizeof (float ))== 0 ; 326 } 327double us [3 ]= {0.0 ,0.0 ,0.0 }; 328timed (0 ,5 ,us [0 ]); 329timed (1 ,3 ,us [1 ]); 330timed (2 ,3 ,us [2 ]); 331const double gbps = (double )G * (double )L .bytes / (us [0 ]* 1e-6 ) /1e9 ; 332 std::printf ("%d %d %s %d/%d %s %.1f %.1f %.1f %.1f %.1f%% %s\n" ,dev ,T ,shape .c_str (),L .gu_type ,L .d_type , 333c .name .c_str (),us [0 ],us [1 ],us [2 ],gbps ,peak > 0.0 ?100.0 * gbps * 1e9 /peak :0.0 , 334same ?"identical" :"DIFFERENT" ); 335g_times [Key (dev ,L .gu_type ,L .d_type ,T ,shape ,c .name )]= {us [0 ],us [1 ],us [2 ]}; 336if (!same )++ bad ; 337 } 338 } 339 } 340Choice off ; 341apply_choice (dev_params ,off ); 342K ::native_expert_set_mode (-1 ,0 ); 343return ok ; 344} 345 346// "gu/d,gu/d,..." -> pairs; false on a malformed item 347bool parse_pairs (const std::string & spec , std::vector < Pair >& out ) { 348size_t i = 0 ; 349while (i < spec .size ()) { 350size_t j = spec .find (',' ,i ); 351if (j == std::string::npos )j = spec .size (); 352const std::string item = spec .substr (i ,j - i ); 353i = j + 1 ; 354if (item .empty ())continue ; 355const size_t s = item .find ('/' ); 356if (s == std::string::npos || s == 0 || s + 1 >=item .size ())return false; 357Pair p ; 358p .gu = std::atoi (item .substr (0 ,s ).c_str ()); 359p .d = std::atoi (item .substr (s + 1 ).c_str ()); 360if (p .gu <=0 || p .d <=0 )return false; 361out .push_back (p ); 362 } 363return !out .empty (); 364} 365 366std::vector < std::string > split_commas (const std::string & s ) { 367 std::vector < std::string > out ; 368size_t i = 0 ; 369while (i <=s .size ()) { 370size_t j = s .find (',' ,i ); 371if (j == std::string::npos )j = s .size (); 372if (j > i )out .push_back (s .substr (i ,j - i )); 373i = j + 1 ; 374 } 375return out ; 376} 377 378}// namespace 379 380int main (int argc ,char ** argv ) { 381setvbuf (stdout ,nullptr ,_IONBF ,0 ); 382const int reps = argc > 1 ? std::max (20 , std::atoi (argv [1 ])) :300 ; 383const int only = argc > 2 ? std::atoi (argv [2 ]) :-1 ; 384const int groups_req = argc > 3 ? std::min (kMaxEntries , std::max (kTop , std::atoi (argv [3 ]))) :20 ; 385 std::vector < Pair > pairs ; 386if (argc > 4 && std::string (argv [4 ])!= "all" ) { 387if (!parse_pairs (argv [4 ],pairs )) { 388 std::printf ("expdec_bench: pairs '%s' is not a comma list of gu/down ggml type ids\n" ,argv [4 ]); 389return 1 ; 390 } 391 }else { 392pairs .assign (std::begin (kModelPairs ), std::end (kModelPairs )); 393 } 394 std::vector < Choice > choices ; 395for (const std::string & s :split_commas (argc > 5 ?argv [5 ] :"def,dec,dec:r2,dec:b4,dec:r2:b4" )) { 396Choice c ; 397if (!parse_choice (s ,c )) { 398 std::printf ("expdec_bench: choice '%s' is not def or dec[:r<1|2>][:d<1|2|4>][:b<2|4>][:x<0|1>][:g<n>][:h<n>][:m<n>]\n" ,s .c_str ()); 399return 1 ; 400 } 401choices .push_back (c ); 402 } 403if (choices .empty ()|| choices [0 ].dec ) { 404Choice d ; 405parse_choice ("def" ,d ); 406choices .insert (choices .begin (),d );// the reference first 407 } 408 std::vector < std::string > shapes ; 409 { 410const std::string sh = argc > 6 ?argv [6 ] :"real" ; 411if (sh == "both" )shapes = {"real" ,"single" }; 412else if (sh == "real" || sh == "single" )shapes = {sh }; 413else { std::printf ("expdec_bench: shape '%s' is not real, single or both\n" ,sh .c_str ());return 1 ; } 414 } 415int n_dev = 0 ; 416if (!ck (cudaGetDeviceCount (& n_dev ),"device count" )|| n_dev == 0 ) { 417 std::printf ("expdec_bench: no CUDA device\n" ); 418return 1 ; 419 } 420if (only >=n_dev ) { 421 std::printf ("expdec_bench: device %d, only %d present\n" ,only ,n_dev ); 422return 1 ; 423 } 424// Snapshot each device's startup defaults before any choice overrides the process-wide EXPDEC parameters. 425 std::vector < K ::NativeExpertExpdecParams > dev_params ((size_t )n_dev ); 426for (int d = 0 ;d < n_dev ;++ d ) { 427if (only >=0 && d != only )continue ; 428if (!ck (cudaSetDevice (d ),"set device" ))return 1 ; 429dev_params [(size_t )d ]= K ::native_expert_expdec_params (); 430 } 431const K ::NativeExpertExpdecParams banner_params = dev_params [(size_t ) (only >=0 ?only :0 )]; 432for (const Pair & p :pairs ) { 433if (!K ::native_expert_supported (p .gu ,p .d ,kEmbd ,kFf )) { 434 std::printf ("expdec_bench: native_expert_supported(%d, %d, %d, %d) is false\n" ,p .gu ,p .d ,kEmbd ,kFf ); 435return 1 ; 436 } 437const K ::NativeExpertLayout L = K ::native_expert_layout (p .gu ,p .d ,kEmbd ,kFf ); 438bool gu = false,down = false; 439K ::native_expert_expdec_takes (L ,gu ,down ); 440if (!gu || !down ) std::printf ("# warning: EXPDEC has no %s kernel for pair %d/%d: that phase runs the default\n" , 441 !gu ?"gate/up" :"down" ,p .gu ,p .d ); 442 } 443for (const char * name : {"STRATA_NO_SUB16_GU" ,"STRATA_EXPERT_V2" ,"STRATA_OLD_IQ_MMVQ" ,"STRATA_EXP_MODE" }) { 444const char * v = std::getenv (name ); 445if (v != nullptr && v [0 ]!= '\0' && v [0 ]!= '0' ) std::printf ("# warning: %s is set, the kernel choice is bypassed\n" ,name ); 446 } 447K ::iq_set_old_kernels (false); 448 std::printf ("# n_embd %d, n_ff %d, %d pair(s), choices:" ,kEmbd ,kFf , (int )pairs .size ()); 449for (const Choice & c :choices ) { 450if (c .dec ) { 451const K ::NativeExpertExpdecParams cp = resolve_choice_params (banner_params ,c ); 452 std::printf (" %s(gu R %d minb %d, down %d R %d iq4_nl %d, rb %d drb %d, min blocks %d)" ,c .name .c_str (), 453cp .gu_rows_per_lane ,cp .gu_min_blocks_per_sm ,cp .down ,cp .down_rows_per_lane ,cp .down_iq4_nl , 454cp .gu_rows_per_block ,cp .down_rows_per_block ,cp .min_blocks ); 455 }else { 456 std::printf (" %s" ,c .name .c_str ()); 457 } 458 } 459 std::printf ("\n# dev T shape gu/d choice all_us gu_us down_us GB/s pct identical|DIFFERENT\n" ); 460long long bad = 0 ; 461bool ok = true; 462for (const Pair & p :pairs ) { 463if (!ok )break ; 464const K ::NativeExpertLayout L = K ::native_expert_layout (p .gu ,p .d ,kEmbd ,kFf ); 465const size_t stride = (L .bytes + 255 ) /256 * 256 ; 466const size_t P = std::max < size_t > ((size_t ) (96u <<20 ) /stride + 1 , (size_t )2 * (size_t )kMaxEntries ); 467 std::printf ("# pair %d/%d: gate/up %s, down %s: blob %.2f MB (gu_row %d, d_row %d), pool %.0f MB\n" ,p .gu ,p .d , 468type_name (p .gu ),type_name (p .d ), (double )L .bytes /1e6 , (int )L .gu_row , (int )L .d_row , 469 (double ) (P * stride ) /1e6 ); 470 std::mt19937 rng (77u + (unsigned ) (p .gu * 131 + p .d )); 471 std::vector < uint8_t > pool (P * stride ,0 ); 472for (size_t i = 0 ;i < P ;++ i )fill_blob (pool .data ()+ i * stride ,L ,rng ); 473 std::vector < float > xh ((size_t )kMaxT * kEmbd ); 474 std::normal_distribution < float > nd (0.0f ,1.0f ); 475for (float & v :xh )v = nd (rng ); 476for (int dev = 0 ;dev < n_dev ;++ dev ) { 477if (only >=0 && dev != only )continue ; 478ok = run_device (dev ,dev_params [(size_t )dev ],reps ,groups_req ,pool ,P ,stride ,xh ,L ,p ,choices ,shapes ,bad )&& ok ; 479 } 480 } 481if (shapes .size ()== 2 && groups_req == 20 ) { 482 std::printf ("\n# decomposition (us per layer call): a = per expert = (single T=4 - real T=2) / 20, b = per entry = (real T=4 - real T=2) / 20\n" ); 483 std::printf ("# dev gu/d choice a_all a_gu a_down b_all b_gu b_down\n" ); 484for (int dev = 0 ;dev < n_dev ;++ dev ) { 485if (only >=0 && dev != only )continue ; 486for (const Pair & p :pairs ) 487for (const Choice & c :choices ) { 488auto f2 = g_times .find (Key (dev ,p .gu ,p .d ,2 ,"real" ,c .name )); 489auto f4 = g_times .find (Key (dev ,p .gu ,p .d ,4 ,"real" ,c .name )); 490auto s4 = g_times .find (Key (dev ,p .gu ,p .d ,4 ,"single" ,c .name )); 491if (f2 == g_times .end ()|| f4 == g_times .end ()|| s4 == g_times .end ())continue ; 492 std::printf ("%d %d/%d %s" ,dev ,p .gu ,p .d ,c .name .c_str ()); 493for (int k = 0 ;k < 3 ;++ k ) std::printf (" %.2f" , (s4 -> second [k ]- f2 -> second [k ]) /20.0 ); 494for (int k = 0 ;k < 3 ;++ k ) std::printf (" %.2f" , (f4 -> second [k ]- f2 -> second [k ]) /20.0 ); 495 std::printf ("\n" ); 496 } 497 } 498 } 499 std::printf ("\nexpdec_bench: %s (%lld choice comparisons differ%s)\n" , (bad || !ok || g_cuda_error ) ?"FAILED" :"ok" ,bad , 500 (!ok || g_cuda_error ) ?", CUDA error" :"" ); 501return (bad || !ok || g_cuda_error ) ?1 :0 ; 502}