okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
62db0bf10
main
1// src/kernels/s2_expert_grouped_parity.cpp - the rewritten expert kernels against the previous ones, 2// BITWISE (GPU, synthetic, no model). 3// 4// build/s2_expert_grouped_parity the checks below; exit 1 on any difference 5// build/s2_expert_grouped_parity --bench previous vs new kernel timings on engine-like shapes 6// 7// Random Q2_0 expert blobs (random codes, fp16 scales in a realistic range) and random Q8_0 activations. Every entry 8// point of `s2_expert_grouped.hpp` that gained a new kernel runs twice from identical inputs and sentinel-filled 9// outputs - `moe_grouped_select_old(1)`, then `(0)` - and the two runs are compared byte for byte: 10// 1. `moe_hit_grouped_s2` per hit, host count; with fp32 activation scales and with the blocks' fp16 `d` 11// 2. `moe_hit_grouped_s2_dev` device count below the capacity (the rows past it must stay untouched) 12// 3. `moe_hit_grouped_s2_multi` verify window: each hit reads its own token's activation row 13// 4. `moe_grouped_s2` host-built groups of 1..8 entries, one of them a mapped HOST blob (the PCIe 14// share), and more group capacity than groups 15// 5. `moe_group_resident` + `moe_grouped_s2` the MTP layer's shape, with and without fp32 scales 16// 6. an activation row that is only 2-byte aligned: the new path must fall back to the previous kernels 17// 7. a slot stride that is not a multiple of 8 (BLOB + 4), and 8. an arena 4 bytes past an aligned address: the 18// per-hit path must fall back as well (its codes are read as uint2) 19// Every run asks `moe_grouped_last_path` which kernels it launched, so a new path that silently declined cannot pass 20// as "the previous kernels against themselves": forced new must report the new kernels, and 6-8 the previous ones. 21// (A misaligned scratch is not exercised: the previous kernels store floats there, so it is not a legal input.) 22// The output AND the scratch (gate/up, the quantized intermediate and its scales) are compared, so a failure names 23// the projection. Bitwise equality with the previous kernels is the contract; on top of it a double-precision 24// host reference of every up row and every down row checks that the fixture computes an expert at all - two 25// kernels agreeing on garbage would otherwise pass. 26#include "strata/kernels/f16_bits.hpp" 27#include "strata/kernels/s2_expert_grouped.hpp" 28 29#include <cuda_runtime.h> 30 31#include <algorithm> 32#include <cmath> 33#include <cstdint> 34#include <cstdio> 35#include <cstdlib> 36#include <cstring> 37#include <functional> 38#include <numeric> 39#include <random> 40#include <string> 41#include <vector> 42 43namespace k= strata::kernels; 44 45namespace { 46// The blob geometry, `cpu/expert.hpp`'s (restated as in the kernel). 47constexpr int H = 2560 ,FF = 640 ,NCH_GU = H /32 ,NCH_D = FF /32 ; 48constexpr size_t ROW_GU = H /4 ,ROW_D = FF /4 ,SC_GU = H /64 ,SC_D = FF /64 ; 49constexpr size_t O_D_CODES = 2ull * FF * ROW_GU ; 50constexpr size_t O_GU_SCALES = O_D_CODES + (size_t )H * ROW_D ; 51constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2 ; 52constexpr size_t BLOB = O_D_SCALES + (size_t )H * SC_D * 2 ; 53static_assert(BLOB == 1382400 ,"the Q2_0 expert blob is 1,382,400 bytes" ); 54constexpr size_t XROW = (size_t )NCH_GU * 34 ;// one token's activation row of block_q8_0 55 56int g_fail = 0 ; 57 58void ck (cudaError_t e ,const char * w ) { 59if (e != cudaSuccess ) { std::fprintf (stderr ,"%s: %s\n" ,w ,cudaGetErrorString (e )); std::exit (2 ); } 60} 61template < typename T > T * dalloc (size_t n ) { 62T * p = nullptr ; 63ck (cudaMalloc (& p ,n * sizeof (T )+ 256 ),"malloc" ); 64ck (cudaMemset (p ,0 ,n * sizeof (T )+ 256 ),"memset" ); 65return p ; 66} 67template < typename T > void up (T * d ,const std::vector < T >& h ) { 68ck (cudaMemcpy (d ,h .data (),h .size ()* sizeof (T ),cudaMemcpyHostToDevice ),"h2d" ); 69} 70template < typename T > std::vector < T > down (const T * d ,size_t n ) { 71 std::vector < T > h (n ); 72ck (cudaMemcpy (h .data (),d ,n * sizeof (T ),cudaMemcpyDeviceToHost ),"d2h" ); 73return h ; 74} 75 76float f16f (const uint8_t * p ) {return k::f32_from_f16 ((uint16_t ) (p [0 ] | (p [1 ] <<8 ))); } 77void put16 (uint8_t * p ,float f ) { 78const uint16_t h = k::f16_from_f32 (f ); 79p [0 ]= (uint8_t )h ; 80p [1 ]= (uint8_t ) (h >>8 ); 81} 82 83// Random codes; fp16 scales of either sign in [1e-3, 3e-2] (a real pack's range, so no overflow downstream). 84void fill_blob (uint8_t * b , std::mt19937 & rng ) { 85for (size_t i = 0 ;i < O_GU_SCALES ;++ i )b [i ]= (uint8_t )rng (); 86 std::uniform_real_distribution < float > mag (1e-3f ,3e-2f ); 87for (size_t i = O_GU_SCALES ;i < BLOB ;i += 2 )put16 (b + i , (rng ()& 1 ?-1.0f :1.0f )* mag (rng )); 88} 89 90// `n_tok` activation rows: per 32-chunk an fp16 `d` then 32 int8 in [-127, 127] (what `quantize_q8_0` writes), 91// plus the fp32 scales `quantize_q8_0_scaled` would pass alongside. Some chunks are saturated on purpose. 92void fill_x (std::vector < uint8_t >& x , std::vector < float >& xs ,int n_tok , std::mt19937 & rng ) { 93x .assign ((size_t )n_tok * XROW ,0 ); 94xs .assign ((size_t )n_tok * NCH_GU ,0.0f ); 95 std::uniform_real_distribution < float > sc (2e-3f ,5e-2f ); 96for (size_t c = 0 ;c < (size_t )n_tok * NCH_GU ;++ c ) { 97uint8_t * b = x .data ()+ c * 34 ; 98xs [c ]= sc (rng ); 99put16 (b ,xs [c ]); 100const int mode = (int ) (rng () %16 ); 101for (int j = 0 ;j < 32 ;++ j ) { 102const int v = mode == 0 ?127 :mode == 1 ?-127 : (int ) (rng () %255 )- 127 ; 103b [2 + j ]= (uint8_t ) (int8_t )v ; 104 } 105 } 106} 107 108// Double-precision reference of one row against one activation row: sum_c dw * dx * sum_e (code_e - 1) * x_e. 109// `mag` receives sum |term|, the scale the tolerance is relative to. 110double row_ref (const uint8_t * codes ,const uint8_t * scales ,const uint8_t * xrow ,const float * xs ,int n_chunks , 111double * mag ) { 112double acc = 0.0 ,a = 0.0 ; 113for (int c = 0 ;c < n_chunks ;++ c ) { 114const uint8_t * xb = xrow + (size_t )c * 34 ; 115const double dx = xs ? (double )xs [c ] : (double )f16f (xb ); 116const double dw = (double )f16f (scales + (size_t ) (c >>1 )* 2 ); 117int s = 0 ; 118for (int e = 0 ;e < 32 ;++ e ) { 119const int code = (codes [(size_t )c * 8 + e /4 ] >> (2 * (e %4 )))& 3 ; 120s += (code - 1 )* (int ) (int8_t )xb [2 + e ]; 121 } 122const double t = dw * dx * (double )s ; 123acc += t ; 124a += std::fabs (t ); 125 } 126* mag = a ; 127return acc ; 128} 129 130bool close_to (float got ,double ref ,double mag ) { 131return std::isfinite (got )&& std::fabs ((double )got - ref ) <=4e-5 * mag + 1e-30 ; 132} 133 134struct Scratch { 135void * p = nullptr ; 136uint64_t bytes = 0 ; 137int64_t cap = 0 ; 138uint64_t gu_bytes ()const {return ((uint64_t )cap * 2 * FF * 4 + 15 )& ~15ull ; } 139uint64_t q8_bytes ()const {return ((uint64_t )cap * NCH_D * 34 + 15 )& ~15ull ; } 140}; 141 142// One entry point, run with the previous kernels then with the new ones from identical sentinel-filled buffers; 143// every differing float of the output and byte of the scratch is counted. `keep` receives the new run. 144struct Run { 145 std::vector < float > out ; 146 std::vector < uint8_t > scratch ; 147}; 148 149bool twice (const char * name ,float * d_out ,size_t out_floats ,const Scratch & s , 150const std::function < void ()>& call ,Run * keep ,bool expect_new = true) { 151Run r [2 ]; 152for (int old = 1 ;old >=0 ;-- old ) { 153ck (cudaMemset (d_out ,0xA5 ,out_floats * 4 ),"sentinel out" ); 154ck (cudaMemset (s .p ,0x5A ,s .bytes ),"sentinel scratch" ); 155 k::moe_grouped_select_old (old ); 156 (void ) k::moe_grouped_last_path ();// clear 157call (); 158const int path = k::moe_grouped_last_path (); 159const int want = old ?0 : (expect_new ?1 :0 ); 160if (path != want ) { 161 std::printf (" %-44s forced %s: launched %s kernels, expected %s\n" ,name ,old ?"previous" :"new" , 162path == 1 ?"the new" :path == 0 ?"the previous" :"no" ,want ?"the new" :"the previous" ); 163++ g_fail ; 164 } 165ck (cudaGetLastError (),name ); 166ck (cudaDeviceSynchronize (),name ); 167Run & x = r [old ?0 :1 ]; 168x .out = down (d_out ,out_floats ); 169x .scratch = down ((const uint8_t * )s .p , (size_t )s .bytes ); 170 } 171 k::moe_grouped_select_old (-1 ); 172const uint64_t gu = s .gu_bytes (),q8 = s .q8_bytes (); 173size_t diff_out = 0 ,diff_gu = 0 ,diff_q8 = 0 ,diff_hs = 0 ; 174for (size_t i = 0 ;i < out_floats ;++ i ) 175diff_out += std::memcmp (& r [0 ].out [i ],& r [1 ].out [i ],4 )!= 0 ; 176for (size_t i = 0 ;i < (size_t )s .bytes ;++ i ) { 177if (r [0 ].scratch [i ]== r [1 ].scratch [i ])continue ; 178if (i < gu )++ diff_gu ; 179else if (i < gu + q8 )++ diff_q8 ; 180else ++ diff_hs ; 181 } 182const bool ok = diff_out + diff_gu + diff_q8 + diff_hs == 0 ; 183 std::printf (" %-44s %s" ,name ,ok ?"bitwise identical" :"DIFFERS" ); 184if (!ok ) 185 std::printf (" (out %zu floats, gate/up %zu B, intermediate %zu B, its scales %zu B)" ,diff_out ,diff_gu , 186diff_q8 ,diff_hs ); 187 std::printf ("\n" ); 188if (!ok )++ g_fail ; 189if (keep )* keep = std::move (r [1 ]); 190return ok ; 191} 192 193// The host reference on a finished run: every up row (the second half of gate/up, which the swiglu leaves alone) 194// against the activation row it read, and every written down row against the intermediate the run produced. 195struct Entry { 196const uint8_t * blob ;// host copy of the entry's blob 197int tok ;// activation row it reads 198int dst ;// output row it writes 199}; 200void reference (const char * name ,const Run & r ,const Scratch & s ,const std::vector < Entry >& ent , 201const std::vector < uint8_t >& x ,const std::vector < float >* xs ) { 202const float * gu = (const float * )r .scratch .data (); 203const uint8_t * hq = r .scratch .data ()+ s .gu_bytes (); 204const float * hs = (const float * ) (r .scratch .data ()+ s .gu_bytes ()+ s .q8_bytes ()); 205long checked = 0 ,bad = 0 ; 206double worst = 0.0 ; 207for (size_t e = 0 ;e < ent .size ();++ e ) { 208const uint8_t * b = ent [e ].blob ; 209const uint8_t * xrow = x .data ()+ (size_t )ent [e ].tok * XROW ; 210const float * xsr = xs ?xs -> data ()+ (size_t )ent [e ].tok * NCH_GU :nullptr ; 211for (int rr = 0 ;rr < FF ;rr += 7 ) {// up row rr = row-slot 2rr + 1 212double mag ; 213const double ref = row_ref (b + (size_t ) (2 * rr + 1 )* ROW_GU ,b + O_GU_SCALES + (size_t ) (2 * rr + 1 )* SC_GU * 2 , 214xrow ,xsr ,NCH_GU ,& mag ); 215const float got = gu [(size_t )s .cap * FF + e * FF + (size_t )rr ]; 216++ checked ; 217if (!close_to (got ,ref ,mag ))++ bad ; 218if (mag > 0 )worst = std::max (worst , std::fabs ((double )got - ref ) /mag ); 219 } 220const uint8_t * hrow = hq + e * (size_t )NCH_D * 34 ; 221const float * hsr = xs ?hs + e * (size_t )NCH_D :nullptr ; 222for (int rr = 0 ;rr < H ;rr += 13 ) { 223double mag ; 224const double ref = row_ref (b + O_D_CODES + (size_t )rr * ROW_D ,b + O_D_SCALES + (size_t )rr * SC_D * 2 , 225hrow ,hsr ,NCH_D ,& mag ); 226const float got = r .out [(size_t )ent [e ].dst * H + (size_t )rr ]; 227++ checked ; 228if (!close_to (got ,ref ,mag ))++ bad ; 229if (mag > 0 )worst = std::max (worst , std::fabs ((double )got - ref ) /mag ); 230 } 231 } 232 std::printf (" %-44s host reference: %ld rows, %ld outside tolerance, worst %.2e of sum|term|\n" ,name ,checked , 233bad ,worst ); 234if (bad || checked == 0 )++ g_fail ; 235} 236 237struct Fixture { 238int nb = 0 ; 239 std::vector < uint8_t > h ;// nb blobs 240uint8_t * d = nullptr ; 241const uint8_t * hb (int i )const {return h .data ()+ (size_t )i * BLOB ; } 242}; 243 244Fixture make_blobs (int nb , std::mt19937 & rng ) { 245Fixture f ; 246f .nb = nb ; 247f .h .resize ((size_t )nb * BLOB ); 248for (int i = 0 ;i < nb ;++ i )fill_blob (f .h .data ()+ (size_t )i * BLOB ,rng ); 249f .d = dalloc < uint8_t > ((size_t )nb * BLOB ); 250up (f .d ,f .h ); 251return f ; 252} 253 254Scratch make_scratch (int64_t cap ) { 255Scratch s ; 256s .cap = cap ; 257s .bytes = k::moe_hit_grouped_scratch_bytes (cap ,H ,FF ); 258s .p = dalloc < uint8_t > (s .bytes ); 259return s ; 260} 261 262// ---------------------------------------------------------------- the checks 263void check_all () { 264 std::mt19937 rng (20260928 ); 265const Fixture fx = make_blobs (12 ,rng ); 266constexpr int K = 10 ; 267 268// Activations for up to 8 tokens, device copies with and without the fp32 scales. 269 std::vector < uint8_t > x ; 270 std::vector < float > xs ; 271fill_x (x ,xs ,8 ,rng ); 272uint8_t * d_x = dalloc < uint8_t > (x .size ()); 273float * d_xs = dalloc < float > (xs .size ()); 274up (d_x ,x ); 275up (d_xs ,xs ); 276 277// ---- 1. moe_hit_grouped_s2: 9 hits of 10 routed rows, slots and destinations shuffled 278 { 279const int n_hits = 9 ; 280 std::vector < int32_t > slot (n_hits ),dst (K ); 281for (int i = 0 ;i < n_hits ;++ i )slot [i ]= (int32_t ) ((i * 5 + 3 ) %fx .nb ); 282 std::iota (dst .begin (),dst .end (),0 ); 283 std::shuffle (dst .begin (),dst .end (),rng ); 284dst .resize (n_hits ); 285int32_t * d_slot = dalloc < int32_t > (n_hits ); 286int32_t * d_dst = dalloc < int32_t > (n_hits ); 287up (d_slot ,slot ); 288up (d_dst ,dst ); 289const Scratch s = make_scratch (n_hits ); 290float * d_out = dalloc < float > ((size_t )K * H ); 291 std::vector < Entry > ent ; 292for (int i = 0 ;i < n_hits ;++ i )ent .push_back ({fx .hb (slot [i ]),0 ,dst [i ]}); 293for (int scaled = 1 ;scaled >=0 ;-- scaled ) { 294Run r ; 295const std::string name = std::string ("moe_hit_grouped_s2" )+ (scaled ?" (fp32 scales)" :" (fp16 d)" ); 296twice (name .c_str (),d_out , (size_t )K * H ,s , [& ] { 297 k::moe_hit_grouped_s2 (fx .d ,d_slot ,d_dst ,n_hits , (int64_t )BLOB ,d_x ,s .p ,d_out ,nullptr , 298scaled ?d_xs :nullptr ); 299 },& r ); 300reference (name .c_str (),r ,s ,ent ,x ,scaled ?& xs :nullptr ); 301 } 302 } 303 304// ---- 2. moe_hit_grouped_s2_dev: capacity 10, device count 7 305 { 306const int cap = 10 ,count = 7 ; 307 std::vector < int32_t > slot (cap ),dst (cap ); 308for (int i = 0 ;i < cap ;++ i )slot [i ]= (int32_t ) ((i * 7 + 1 ) %fx .nb ); 309 std::iota (dst .begin (),dst .end (),0 ); 310 std::shuffle (dst .begin (),dst .end (),rng ); 311int32_t * d_slot = dalloc < int32_t > (cap ); 312int32_t * d_dst = dalloc < int32_t > (cap ); 313int32_t * d_count = dalloc < int32_t > (1 ); 314up (d_slot ,slot ); 315up (d_dst ,dst ); 316up (d_count , std::vector < int32_t > {count }); 317const Scratch s = make_scratch (cap ); 318float * d_out = dalloc < float > ((size_t )K * H ); 319 std::vector < Entry > ent ; 320for (int i = 0 ;i < count ;++ i )ent .push_back ({fx .hb (slot [i ]),0 ,dst [i ]}); 321Run r ; 322twice ("moe_hit_grouped_s2_dev (count 7 of 10)" ,d_out , (size_t )K * H ,s , [& ] { 323 k::moe_hit_grouped_s2_dev (fx .d ,d_slot ,d_dst ,d_count ,cap , (int64_t )BLOB ,d_x ,s .p ,d_out ,nullptr , 324d_xs ); 325 },& r ); 326reference ("moe_hit_grouped_s2_dev (count 7 of 10)" ,r ,s ,ent ,x ,& xs ); 327// the rows of the hits past the count keep the sentinel 328long touched = 0 ; 329for (int i = count ;i < cap ;++ i ) 330for (int c = 0 ;c < H ;++ c ) { 331uint32_t v ; 332 std::memcpy (& v ,& r .out [(size_t )dst [i ]* H + c ],4 ); 333touched += v != 0xA5A5A5A5u ; 334 } 335 std::printf (" %-44s rows past the count written: %ld\n" ,"moe_hit_grouped_s2_dev (count 7 of 10)" ,touched ); 336if (touched )++ g_fail ; 337 } 338 339// ---- 3. moe_hit_grouped_s2_multi: 4 tokens x 10 routed entries, 29 hits 340 { 341const int T = 4 ,n = T * K ,count = 29 ; 342 std::vector < int32_t > ent_ids (n ); 343 std::iota (ent_ids .begin (),ent_ids .end (),0 ); 344 std::shuffle (ent_ids .begin (),ent_ids .end (),rng ); 345 std::vector < int32_t > slot (n ),dst (n ); 346for (int i = 0 ;i < n ;++ i ) { 347dst [i ]= ent_ids [i ]; 348slot [i ]= (int32_t ) (rng () %fx .nb ); 349 } 350 std::sort (dst .begin (),dst .begin ()+ count );// hit order is routing order, as `moe_hit_select_multi` makes it 351int32_t * d_slot = dalloc < int32_t > (n ); 352int32_t * d_dst = dalloc < int32_t > (n ); 353int32_t * d_count = dalloc < int32_t > (1 ); 354up (d_slot ,slot ); 355up (d_dst ,dst ); 356up (d_count , std::vector < int32_t > {count }); 357const Scratch s = make_scratch (n ); 358float * d_out = dalloc < float > ((size_t )n * H ); 359 std::vector < Entry > ent ; 360for (int i = 0 ;i < count ;++ i )ent .push_back ({fx .hb (slot [i ]),dst [i ] /K ,dst [i ]}); 361Run r ; 362twice ("moe_hit_grouped_s2_multi (4 tokens, 29 hits)" ,d_out , (size_t )n * H ,s , [& ] { 363 k::moe_hit_grouped_s2_multi (fx .d ,d_slot ,d_dst ,d_count ,n , (int64_t )BLOB ,d_x ,d_xs ,K ,s .p ,d_out , 364nullptr ); 365 },& r ); 366reference ("moe_hit_grouped_s2_multi (4 tokens, 29 hits)" ,r ,s ,ent ,x ,& xs ); 367 } 368 369// ---- 4. moe_grouped_s2: 8 tokens x 10 entries in groups of 1..8, one group on a mapped host blob 370 { 371const int T = 8 ,n = T * K ; 372uint8_t * h_host = nullptr ; 373uint8_t * d_host = nullptr ; 374ck (cudaHostAlloc ((void ** )& h_host ,BLOB ,cudaHostAllocMapped ),"host blob" ); 375 std::memcpy (h_host ,fx .hb (fx .nb - 1 ),BLOB ); 376ck (cudaHostGetDevicePointer ((void ** )& d_host ,h_host ,0 ),"host blob ptr" ); 377// group sizes: 8, 1, 5, 2, 7, 3, 1, 6, 4, ... up to n entries 378const int sizes []= {8 ,1 ,5 ,2 ,7 ,3 ,1 ,6 ,4 ,8 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,1 ,1 ,5 }; 379 std::vector < int32_t > order (n );// the output rows, in group order 380 std::iota (order .begin (),order .end (),0 ); 381 std::shuffle (order .begin (),order .end (),rng ); 382 std::vector < unsigned long long > gptr ; 383 std::vector < int32_t > gstart {0 },edst ,etok ; 384 std::vector < Entry > ent ; 385int at = 0 ,gi = 0 ; 386while (at < n ) { 387const int sz = std::min (sizes [gi %20 ],n - at ); 388const bool host = gi == 3 ; 389const int b = gi % (fx .nb - 1 ); 390gptr .push_back ((unsigned long long ) (host ?d_host :fx .d + (size_t )b * BLOB )); 391for (int j = 0 ;j < sz ;++ j ,++ at ) { 392edst .push_back (order [at ]); 393etok .push_back (order [at ] /K ); 394ent .push_back ({host ?h_host :fx .hb (b ),order [at ] /K ,order [at ]}); 395 } 396gstart .push_back (at ); 397++ gi ; 398 } 399const int n_groups = gi ,cap_groups = n_groups + 3 ; 400gstart .resize ((size_t )cap_groups + 1 ,at ); 401gptr .resize ((size_t )cap_groups ,gptr [0 ]); 402unsigned long long * d_gptr = dalloc < unsigned long long > (gptr .size ()); 403int32_t * d_gstart = dalloc < int32_t > (gstart .size ()); 404int32_t * d_ng = dalloc < int32_t > (1 ); 405int32_t * d_edst = dalloc < int32_t > (n ); 406int32_t * d_etok = dalloc < int32_t > (n ); 407up (d_gptr ,gptr ); 408up (d_gstart ,gstart ); 409up (d_ng , std::vector < int32_t > {n_groups }); 410up (d_edst ,edst ); 411up (d_etok ,etok ); 412const Scratch s = make_scratch (n ); 413float * d_out = dalloc < float > ((size_t )n * H ); 414for (int scaled = 1 ;scaled >=0 ;-- scaled ) { 415Run r ; 416const std::string name = std::string ("moe_grouped_s2 (" )+ std::to_string (n_groups )+ " groups" + 417 (scaled ?", fp32 scales)" :", fp16 d)" ); 418twice (name .c_str (),d_out , (size_t )n * H ,s , [& ] { 419 k::moe_grouped_s2 (d_gptr ,d_gstart ,d_ng ,d_edst ,d_etok ,cap_groups ,n ,d_x ,scaled ?d_xs :nullptr , 420s .p ,d_out ,nullptr ); 421 },& r ); 422reference (name .c_str (),r ,s ,ent ,x ,scaled ?& xs :nullptr ); 423 } 424ck (cudaFreeHost (h_host ),"free host blob" ); 425 } 426 427// ---- 5. moe_group_resident + moe_grouped_s2: the MTP layer (experts resident at base + id * BLOB), T=1 and T=5 428for (const int T : {1 ,5 }) { 429const int n = T * K ; 430 std::vector < int32_t > ids (n ); 431for (int t = 0 ;t < T ;++ t ) {// distinct within a token, shared across tokens 432 std::vector < int32_t > pick (fx .nb ); 433 std::iota (pick .begin (),pick .end (),0 ); 434 std::shuffle (pick .begin (),pick .end (),rng ); 435for (int j = 0 ;j < K ;++ j )ids [(size_t )t * K + j ]= pick [j ]; 436 } 437int32_t * d_ids = dalloc < int32_t > (n ); 438up (d_ids ,ids ); 439unsigned long long * d_gptr = dalloc < unsigned long long > (n ); 440int32_t * d_gstart = dalloc < int32_t > (n + 1 ); 441int32_t * d_counts = dalloc < int32_t > (2 ); 442int32_t * d_edst = dalloc < int32_t > (n ); 443int32_t * d_etok = dalloc < int32_t > (n ); 444 k::moe_group_resident (d_ids ,n ,K ,fx .d , (int64_t )BLOB ,d_gptr ,d_gstart ,d_counts ,d_edst ,d_etok ,nullptr ); 445ck (cudaDeviceSynchronize (),"group_resident" ); 446const std::vector < int32_t > edst = down (d_edst ,n ),etok = down (d_etok ,n ); 447 std::vector < Entry > ent (n );// entry e: dst = routing index, blob = its expert 448for (int e = 0 ;e < n ;++ e )ent [e ]= {fx .hb (ids [(size_t )edst [e ]]),etok [e ],edst [e ]}; 449const Scratch s = make_scratch (n ); 450float * d_out = dalloc < float > ((size_t )n * H ); 451for (int scaled = 1 ;scaled >=0 ;-- scaled ) { 452Run r ; 453const std::string name = std::string ("moe_group_resident + moe_grouped_s2 T=" )+ std::to_string (T )+ 454 (scaled ?" (fp32)" :" (fp16)" ); 455twice (name .c_str (),d_out , (size_t )n * H ,s , [& ] { 456 k::moe_grouped_s2 (d_gptr ,d_gstart ,d_counts ,d_edst ,d_etok ,n ,n ,d_x ,scaled ?d_xs :nullptr ,s .p , 457d_out ,nullptr ); 458 },& r ); 459reference (name .c_str (),r ,s ,ent ,x ,scaled ?& xs :nullptr ); 460 } 461 } 462 463// ---- 6. a 2-byte aligned activation row: the new path must decline and the previous kernels run 464 { 465uint8_t * d_x2 = dalloc < uint8_t > (x .size ()+ 2 ); 466ck (cudaMemcpy (d_x2 + 2 ,x .data (),XROW ,cudaMemcpyHostToDevice ),"x2" ); 467const int n_hits = 3 ; 468 std::vector < int32_t > slot {2 ,5 ,7 },dst {4 ,0 ,9 }; 469int32_t * d_slot = dalloc < int32_t > (n_hits ); 470int32_t * d_dst = dalloc < int32_t > (n_hits ); 471up (d_slot ,slot ); 472up (d_dst ,dst ); 473const Scratch s = make_scratch (n_hits ); 474float * d_out = dalloc < float > ((size_t )K * H ); 475 std::vector < Entry > ent ; 476for (int i = 0 ;i < n_hits ;++ i )ent .push_back ({fx .hb (slot [i ]),0 ,dst [i ]}); 477Run r ; 478twice ("moe_hit_grouped_s2 (2-byte aligned x)" ,d_out , (size_t )K * H ,s , [& ] { 479 k::moe_hit_grouped_s2 (fx .d ,d_slot ,d_dst ,n_hits , (int64_t )BLOB ,d_x2 + 2 ,s .p ,d_out ,nullptr ,d_xs ); 480 },& r ,/*expect_new=*/ false); 481reference ("moe_hit_grouped_s2 (2-byte aligned x)" ,r ,s ,ent ,x ,& xs ); 482 } 483 484// ---- 7. slots BLOB + 4 bytes apart, and 8. an arena at an address that is 4 mod 8: per-hit fallback 485 { 486constexpr size_t STRIDE = BLOB + 4 ; 487 static_assert(STRIDE %8 != 0 ,"the stride must defeat the uint2 code loads" ); 488const int nb = 8 ; 489uint8_t * d_arena = dalloc < uint8_t > ((size_t )nb * STRIDE + 8 ); 490const int n_hits = 4 ; 491 std::vector < int32_t > slot {6 ,1 ,3 ,0 },dst {2 ,7 ,5 ,8 }; 492int32_t * d_slot = dalloc < int32_t > (n_hits ); 493int32_t * d_dst = dalloc < int32_t > (n_hits ); 494up (d_slot ,slot ); 495up (d_dst ,dst ); 496const Scratch s = make_scratch (n_hits ); 497float * d_out = dalloc < float > ((size_t )K * H ); 498 std::vector < Entry > ent ; 499for (int i = 0 ;i < n_hits ;++ i )ent .push_back ({fx .hb (slot [i ]),0 ,dst [i ]}); 500// One allocation for both layouts: the BLOB + 4 strided copies first, then the same blobs BLOB apart from 501// `d_arena + 4` over them. 502for (int i = 0 ;i < nb ;++ i ) 503ck (cudaMemcpy (d_arena + (size_t )i * STRIDE ,fx .hb (i ),BLOB ,cudaMemcpyHostToDevice ),"arena" ); 504 { 505Run r ; 506twice ("moe_hit_grouped_s2 (slot stride BLOB + 4)" ,d_out , (size_t )K * H ,s , [& ] { 507 k::moe_hit_grouped_s2 (d_arena ,d_slot ,d_dst ,n_hits , (int64_t )STRIDE ,d_x ,s .p ,d_out ,nullptr , 508d_xs ); 509 },& r ,/*expect_new=*/ false); 510reference ("moe_hit_grouped_s2 (slot stride BLOB + 4)" ,r ,s ,ent ,x ,& xs ); 511 } 512for (int i = 0 ;i < nb ;++ i ) 513ck (cudaMemcpy (d_arena + 4 + (size_t )i * BLOB ,fx .hb (i ),BLOB ,cudaMemcpyHostToDevice ),"arena" ); 514 { 515Run r ; 516twice ("moe_hit_grouped_s2 (arena 4 mod 8)" ,d_out , (size_t )K * H ,s , [& ] { 517 k::moe_hit_grouped_s2 (d_arena + 4 ,d_slot ,d_dst ,n_hits , (int64_t )BLOB ,d_x ,s .p ,d_out ,nullptr , 518d_xs ); 519 },& r ,/*expect_new=*/ false); 520reference ("moe_hit_grouped_s2 (arena 4 mod 8)" ,r ,s ,ent ,x ,& xs ); 521 } 522 } 523} 524 525// ---------------------------------------------------------------- --bench 526// Engine-like shapes with the blobs cycled through a set larger than the L2, so each call reads its codes from 527// DRAM as the engine's do. Reports microseconds per call and the codes' effective bandwidth. 528void bench () { 529int dev = 0 ; 530cudaDeviceProp prop {}; 531ck (cudaGetDevice (& dev ),"dev" ); 532ck (cudaGetDeviceProperties (& prop ,dev ),"props" ); 533const int nb = std::max (48 , (int ) (3ull * (size_t )prop .l2CacheSize /BLOB )+ 8 ); 534 std::printf ("bench: %s, L2 %d MB, %d blobs (%.0f MB) cycled\n" ,prop .name ,prop .l2CacheSize >>20 ,nb , 535nb * (double )BLOB /1e6 ); 536 std::mt19937 rng (7 ); 537Fixture fx ; 538fx .nb = nb ; 539fx .d = dalloc < uint8_t > ((size_t )nb * BLOB ); 540 { 541 std::vector < uint8_t > b (BLOB ); 542for (int i = 0 ;i < nb ;++ i ) { 543fill_blob (b .data (),rng ); 544ck (cudaMemcpy (fx .d + (size_t )i * BLOB ,b .data (),BLOB ,cudaMemcpyHostToDevice ),"blob" ); 545 } 546 } 547 std::vector < uint8_t > x ; 548 std::vector < float > xs ; 549fill_x (x ,xs ,8 ,rng ); 550uint8_t * d_x = dalloc < uint8_t > (x .size ()); 551float * d_xs = dalloc < float > (xs .size ()); 552up (d_x ,x ); 553up (d_xs ,xs ); 554constexpr int K = 10 ,ITERS = 200 ,SETS = 16 ; 555cudaEvent_t e0 ,e1 ; 556ck (cudaEventCreate (& e0 ),"ev" ); 557ck (cudaEventCreate (& e1 ),"ev" ); 558auto time = [& ](const std::function < void (int )>& call ) { 559call (0 ); 560ck (cudaDeviceSynchronize (),"warm" ); 561ck (cudaEventRecord (e0 ),"rec" ); 562for (int i = 0 ;i < ITERS ;++ i )call (i %SETS ); 563ck (cudaEventRecord (e1 ),"rec" ); 564ck (cudaEventSynchronize (e1 ),"sync" ); 565float ms = 0 ; 566ck (cudaEventElapsedTime (& ms ,e0 ,e1 ),"elapsed" ); 567return 1000.0 * ms /ITERS ; 568 }; 569auto ab = [& ](const char * name ,double blobs_per_call ,const std::function < void (int )>& call ) { 570double us [2 ]; 571for (int old = 1 ;old >=0 ;-- old ) { 572 k::moe_grouped_select_old (old ); 573us [old ?0 :1 ]= time (call ); 574 } 575 k::moe_grouped_select_old (-1 ); 576const double gb = blobs_per_call * (double )BLOB /1e3 ;// bytes / us = MB/s ... / 1e3 -> GB/s 577 std::printf (" %-40s previous %8.1f us (%6.0f GB/s) new %8.1f us (%6.0f GB/s) x%.2f\n" ,name ,us [0 ], 578gb /us [0 ],us [1 ],gb /us [1 ],us [0 ] /us [1 ]); 579 }; 580 581// per-hit path, decode: 9 hits of 10 (5090-like residency), 5 of 10, and the low-residency 1-3 hits, where the 582// new kernels' grid (80 gate/up blocks per hit) is below one block per SM - see `STRATA_GROUPED_PAIR_MIN_HITS` 583for (const int n_hits : {9 ,5 ,3 ,2 ,1 }) { 584 std::vector < int32_t > slots ((size_t )SETS * n_hits ),dst (K ); 585for (auto & v :slots )v = (int32_t ) (rng () %nb ); 586 std::iota (dst .begin (),dst .end (),0 ); 587int32_t * d_slots = dalloc < int32_t > (slots .size ()); 588int32_t * d_dst = dalloc < int32_t > (K ); 589up (d_slots ,slots ); 590up (d_dst ,dst ); 591const Scratch s = make_scratch (n_hits ); 592float * d_out = dalloc < float > ((size_t )K * H ); 593const std::string name = "moe_hit_grouped_s2, " + std::to_string (n_hits )+ " hits" ; 594ab (name .c_str (),n_hits , [& ](int set ) { 595 k::moe_hit_grouped_s2 (fx .d ,d_slots + (size_t )set * n_hits ,d_dst ,n_hits , (int64_t )BLOB ,d_x ,s .p , 596d_out ,nullptr ,d_xs ); 597 }); 598 } 599// grouped path, verify window: T tokens x 10, routed with `share` = the chance an entry reuses an expert already 600// routed by an earlier token of the window 601struct Shape {int T ;double share ;const char * what ; }; 602for (const Shape sh : {Shape {1 ,0.0 ,"1 token, MTP shape" }, 603Shape {4 ,0.0 ,"4 tokens, no sharing" },Shape {4 ,0.3 ,"4 tokens, 30% shared" }, 604Shape {8 ,0.3 ,"8 tokens, 30% shared" },Shape {8 ,1.0 ,"8 tokens, all shared (ne 8)" }}) { 605const int n = sh .T * K ; 606 std::vector < unsigned long long > gptr ((size_t )SETS * n ); 607 std::vector < int32_t > gstart ((size_t )SETS * (n + 1 )),ng (SETS ),edst ((size_t )SETS * n ),etok ((size_t )SETS * n ); 608double groups = 0 ; 609 std::uniform_real_distribution < double > u (0 ,1 ); 610for (int set = 0 ;set < SETS ;++ set ) { 611 std::vector < std::vector < int >> g ;// per group: routing indices 612 std::vector < int > gexp ;// per group: blob 613for (int t = 0 ;t < sh .T ;++ t ) { 614 std::vector < char > used (g .size (),0 ); 615for (int j = 0 ;j < K ;++ j ) { 616int pick = -1 ; 617if (t > 0 && u (rng )< sh .share ) 618for (size_t q = 0 ;q < g .size ();++ q ) 619if (!used [q ]&& (int )g [q ].size ()< 8 ) {pick = (int )q ;break ; } 620if (pick < 0 ) { 621pick = (int )g .size (); 622g .emplace_back (); 623gexp .push_back ((int ) (rng () %nb )); 624used .push_back (0 ); 625 } 626used [(size_t )pick ]= 1 ; 627g [(size_t )pick ].push_back (t * K + j ); 628 } 629 } 630int at = 0 ; 631for (size_t q = 0 ;q < g .size ();++ q ) { 632gptr [(size_t )set * n + q ]= (unsigned long long ) (fx .d + (size_t )gexp [q ]* BLOB ); 633gstart [(size_t )set * (n + 1 )+ q ]= at ; 634for (int e :g [q ]) { 635edst [(size_t )set * n + at ]= e ; 636etok [(size_t )set * n + at ]= e /K ; 637++ at ; 638 } 639 } 640for (size_t q = g .size ();q <= (size_t )n ;++ q )gstart [(size_t )set * (n + 1 )+ q ]= at ; 641ng [set ]= (int32_t )g .size (); 642groups += (double )g .size () /SETS ; 643 } 644unsigned long long * d_gptr = dalloc < unsigned long long > (gptr .size ()); 645int32_t * d_gstart = dalloc < int32_t > (gstart .size ()); 646int32_t * d_ng = dalloc < int32_t > (SETS ); 647int32_t * d_edst = dalloc < int32_t > (edst .size ()); 648int32_t * d_etok = dalloc < int32_t > (etok .size ()); 649up (d_gptr ,gptr ); 650up (d_gstart ,gstart ); 651up (d_ng ,ng ); 652up (d_edst ,edst ); 653up (d_etok ,etok ); 654const Scratch s = make_scratch (n ); 655float * d_out = dalloc < float > ((size_t )n * H ); 656char name [96 ]; 657 std::snprintf (name ,sizeof name ,"moe_grouped_s2, %s (%.0f groups)" ,sh .what ,groups ); 658ab (name ,groups , [& ](int set ) { 659 k::moe_grouped_s2 (d_gptr + (size_t )set * n ,d_gstart + (size_t )set * (n + 1 ),d_ng + set , 660d_edst + (size_t )set * n ,d_etok + (size_t )set * n ,n ,n ,d_x ,d_xs ,s .p ,d_out , 661nullptr ); 662 }); 663 } 664} 665}// namespace 666 667int main (int argc ,char ** argv ) { 668bool do_bench = false; 669for (int i = 1 ;i < argc ;++ i ) { 670if (std::strcmp (argv [i ],"--bench" )== 0 )do_bench = true; 671else if (std::strcmp (argv [i ],"--selftest" )!= 0 ) { 672 std::fprintf (stderr ,"usage: s2_expert_grouped_parity [--selftest] [--bench]\n" ); 673return 2 ; 674 } 675 } 676 std::printf ("s2_expert_grouped_parity: new expert kernels vs the previous ones, bitwise\n" ); 677check_all (); 678if (do_bench )bench (); 679 std::printf ("s2_expert_grouped_parity: %d failures\n%s\n" ,g_fail ,g_fail ?"FAIL" :"PASS" ); 680return g_fail ?1 :0 ; 681}