okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
db137d917
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#define DPCT_PROFILING_ENABLED 27#include <sycl/sycl.hpp> 28#include <dpct/dpct.hpp> 29#include "strata/kernels/f16_bits.hpp" 30#include "strata/kernels/s2_expert_grouped.hpp" 31#include "strata/core/geometry.hpp" 32 33#include <algorithm> 34#include <cmath> 35#include <cstdint> 36#include <cstdio> 37#include <cstdlib> 38#include <cstring> 39#include <functional> 40#include <numeric> 41#include <random> 42#include <string> 43#include <vector> 44 45namespace k= strata::kernels; 46 47namespace { 48// The blob geometry, `cpu/expert.hpp`'s (restated as in the kernel). 49constexpr int H = strata::core::kCompiledGeometry .n_embd ,FF = strata::core::kCompiledGeometry .n_ff ,NCH_GU = H /32 ,NCH_D = FF /32 ;// the compiled shape (Q4-SYCL; Flash-Next 2560 x 640) 50constexpr size_t ROW_GU = H /4 ,ROW_D = FF /4 ,SC_GU = H /64 ,SC_D = FF /64 ; 51constexpr size_t O_D_CODES = 2ull * FF * ROW_GU ; 52constexpr size_t O_GU_SCALES = O_D_CODES + (size_t )H * ROW_D ; 53constexpr size_t O_D_SCALES = O_GU_SCALES + 2ull * FF * SC_GU * 2 ; 54constexpr size_t BLOB = O_D_SCALES + (size_t )H * SC_D * 2 ; 55static_assert(H != 2560 || FF != 640 || BLOB == 1382400 ,"the Q2_0 expert blob of Flash-Next's 2560 x 640 is 1,382,400 bytes" ); 56constexpr size_t XROW = (size_t )NCH_GU * 34 ;// one token's activation row of block_q8_0 57 58int g_fail = 0 ; 59 60void ck (dpct::err0 e ,const char * w ) { 61/* 62DPCT1009: SYCL reports errors using exceptions and does not use error 63codes. Please replace the "get_error_string_dummy(...)" with a real 64error-handling function. 65*/ 66} 67template < typename T > T * dalloc (size_t n ) { 68T * p = nullptr ; 69ck (DPCT_CHECK_ERROR (p = (T * )sycl::malloc_device ( 70n * sizeof (T )+ 256 , dpct::get_in_order_queue ())), 71"malloc" ); 72ck (DPCT_CHECK_ERROR ( 73 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memset (p ,0 ,n * sizeof (T )+ 256 ).wait ()), 74"memset" ); 75return p ; 76} 77template < typename T > void up (T * d ,const std::vector < T >& h ) { 78/* 79DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in 80the original code the source host memory is pageable memory. If the memory 81is not pageable, call wait() on event return by memcpy API to ensure 82synchronization behavior. 83*/ 84ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 85d ,h .data (),h .size ()* sizeof (T )).wait ()), 86"h2d" ); 87} 88template < typename T > std::vector < T > down (const T * d ,size_t n ) { 89 std::vector < T > h (n ); 90ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 91 .memcpy (h .data (),d ,n * sizeof (T )) 92 .wait ()), 93"d2h" ); 94return h ; 95} 96 97float f16f (const uint8_t * p ) {return k::f32_from_f16 ((uint16_t ) (p [0 ] | (p [1 ] <<8 ))); } 98void put16 (uint8_t * p ,float f ) { 99const uint16_t h = k::f16_from_f32 (f ); 100p [0 ]= (uint8_t )h ; 101p [1 ]= (uint8_t ) (h >>8 ); 102} 103 104// Random codes; fp16 scales of either sign in [1e-3, 3e-2] (a real pack's range, so no overflow downstream). 105void fill_blob (uint8_t * b , std::mt19937 & rng ) { 106for (size_t i = 0 ;i < O_GU_SCALES ;++ i )b [i ]= (uint8_t )rng (); 107 std::uniform_real_distribution < float > mag (1e-3f ,3e-2f ); 108for (size_t i = O_GU_SCALES ;i < BLOB ;i += 2 )put16 (b + i , (rng ()& 1 ?-1.0f :1.0f )* mag (rng )); 109} 110 111// `n_tok` activation rows: per 32-chunk an fp16 `d` then 32 int8 in [-127, 127] (what `quantize_q8_0` writes), 112// plus the fp32 scales `quantize_q8_0_scaled` would pass alongside. Some chunks are saturated on purpose. 113void fill_x (std::vector < uint8_t >& x , std::vector < float >& xs ,int n_tok , std::mt19937 & rng ) { 114x .assign ((size_t )n_tok * XROW ,0 ); 115xs .assign ((size_t )n_tok * NCH_GU ,0.0f ); 116 std::uniform_real_distribution < float > sc (2e-3f ,5e-2f ); 117for (size_t c = 0 ;c < (size_t )n_tok * NCH_GU ;++ c ) { 118uint8_t * b = x .data ()+ c * 34 ; 119xs [c ]= sc (rng ); 120put16 (b ,xs [c ]); 121const int mode = (int ) (rng () %16 ); 122for (int j = 0 ;j < 32 ;++ j ) { 123const int v = mode == 0 ?127 :mode == 1 ?-127 : (int ) (rng () %255 )- 127 ; 124b [2 + j ]= (uint8_t ) (int8_t )v ; 125 } 126 } 127} 128 129// Double-precision reference of one row against one activation row: sum_c dw * dx * sum_e (code_e - 1) * x_e. 130// `mag` receives sum |term|, the scale the tolerance is relative to. 131double row_ref (const uint8_t * codes ,const uint8_t * scales ,const uint8_t * xrow ,const float * xs ,int n_chunks , 132double * mag ) { 133double acc = 0.0 ,a = 0.0 ; 134for (int c = 0 ;c < n_chunks ;++ c ) { 135const uint8_t * xb = xrow + (size_t )c * 34 ; 136const double dx = xs ? (double )xs [c ] : (double )f16f (xb ); 137const double dw = (double )f16f (scales + (size_t ) (c >>1 )* 2 ); 138int s = 0 ; 139for (int e = 0 ;e < 32 ;++ e ) { 140const int code = (codes [(size_t )c * 8 + e /4 ] >> (2 * (e %4 )))& 3 ; 141s += (code - 1 )* (int ) (int8_t )xb [2 + e ]; 142 } 143const double t = dw * dx * (double )s ; 144acc += t ; 145a += std::fabs (t ); 146 } 147* mag = a ; 148return acc ; 149} 150 151bool close_to (float got ,double ref ,double mag ) { 152return std::isfinite (got )&& std::fabs ((double )got - ref ) <=4e-5 * mag + 1e-30 ; 153} 154 155struct Scratch { 156void * p = nullptr ; 157uint64_t bytes = 0 ; 158int64_t cap = 0 ; 159uint64_t gu_bytes ()const {return ((uint64_t )cap * 2 * FF * 4 + 15 )& ~15ull ; } 160uint64_t q8_bytes ()const {return ((uint64_t )cap * NCH_D * 34 + 15 )& ~15ull ; } 161}; 162 163// One entry point, run with the previous kernels then with the new ones from identical sentinel-filled buffers; 164// every differing float of the output and byte of the scratch is counted. `keep` receives the new run. 165struct Run { 166 std::vector < float > out ; 167 std::vector < uint8_t > scratch ; 168}; 169 170bool twice (const char * name ,float * d_out ,size_t out_floats ,const Scratch & s , 171const std::function < void ()>& call ,Run * keep ,bool expect_new = true) { 172Run r [2 ]; 173for (int old = 1 ;old >=0 ;-- old ) { 174ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 175 .memset (d_out ,0xA5 ,out_floats * 4 ) 176 .wait ()), 177"sentinel out" ); 178ck (DPCT_CHECK_ERROR ( 179 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memset (s .p ,0x5A ,s .bytes ).wait ()), 180"sentinel scratch" ); 181 k::moe_grouped_select_old (old ); 182 (void ) k::moe_grouped_last_path ();// clear 183call (); 184const int path = k::moe_grouped_last_path (); 185const int want = old ?0 : (expect_new ?1 :0 ); 186if (path != want ) { 187 std::printf (" %-44s forced %s: launched %s kernels, expected %s\n" ,name ,old ?"previous" :"new" , 188path == 1 ?"the new" :path == 0 ?"the previous" :"no" ,want ?"the new" :"the previous" ); 189++ g_fail ; 190 } 191/* 192DPCT1010: SYCL uses exceptions to report errors and does not use the 193error codes. The cudaGetLastError function call was replaced with 0. You 194need to rewrite this code. 195*/ 196ck (0 ,name ); 197ck (DPCT_CHECK_ERROR (dpct::get_current_device ().queues_wait_and_throw ()), 198name ); 199Run & x = r [old ?0 :1 ]; 200x .out = down (d_out ,out_floats ); 201x .scratch = down ((const uint8_t * )s .p , (size_t )s .bytes ); 202 } 203 k::moe_grouped_select_old (-1 ); 204const uint64_t gu = s .gu_bytes (),q8 = s .q8_bytes (); 205size_t diff_out = 0 ,diff_gu = 0 ,diff_q8 = 0 ,diff_hs = 0 ; 206for (size_t i = 0 ;i < out_floats ;++ i ) 207diff_out += std::memcmp (& r [0 ].out [i ],& r [1 ].out [i ],4 )!= 0 ; 208for (size_t i = 0 ;i < (size_t )s .bytes ;++ i ) { 209if (r [0 ].scratch [i ]== r [1 ].scratch [i ])continue ; 210if (i < gu )++ diff_gu ; 211else if (i < gu + q8 )++ diff_q8 ; 212else ++ diff_hs ; 213 } 214const bool ok = diff_out + diff_gu + diff_q8 + diff_hs == 0 ; 215 std::printf (" %-44s %s" ,name ,ok ?"bitwise identical" :"DIFFERS" ); 216if (!ok ) 217 std::printf (" (out %zu floats, gate/up %zu B, intermediate %zu B, its scales %zu B)" ,diff_out ,diff_gu , 218diff_q8 ,diff_hs ); 219 std::printf ("\n" ); 220if (!ok )++ g_fail ; 221if (keep )* keep = std::move (r [1 ]); 222return ok ; 223} 224 225// The host reference on a finished run: every up row (the second half of gate/up, which the swiglu leaves alone) 226// against the activation row it read, and every written down row against the intermediate the run produced. 227struct Entry { 228const uint8_t * blob ;// host copy of the entry's blob 229int tok ;// activation row it reads 230int dst ;// output row it writes 231}; 232void reference (const char * name ,const Run & r ,const Scratch & s ,const std::vector < Entry >& ent , 233const std::vector < uint8_t >& x ,const std::vector < float >* xs ) { 234const float * gu = (const float * )r .scratch .data (); 235const uint8_t * hq = r .scratch .data ()+ s .gu_bytes (); 236const float * hs = (const float * ) (r .scratch .data ()+ s .gu_bytes ()+ s .q8_bytes ()); 237long checked = 0 ,bad = 0 ; 238double worst = 0.0 ; 239for (size_t e = 0 ;e < ent .size ();++ e ) { 240const uint8_t * b = ent [e ].blob ; 241const uint8_t * xrow = x .data ()+ (size_t )ent [e ].tok * XROW ; 242const float * xsr = xs ?xs -> data ()+ (size_t )ent [e ].tok * NCH_GU :nullptr ; 243for (int rr = 0 ;rr < FF ;rr += 7 ) {// up row rr = row-slot 2rr + 1 244double mag ; 245const double ref = row_ref (b + (size_t ) (2 * rr + 1 )* ROW_GU ,b + O_GU_SCALES + (size_t ) (2 * rr + 1 )* SC_GU * 2 , 246xrow ,xsr ,NCH_GU ,& mag ); 247const float got = gu [(size_t )s .cap * FF + e * FF + (size_t )rr ]; 248++ checked ; 249if (!close_to (got ,ref ,mag ))++ bad ; 250if (mag > 0 )worst = std::max (worst , std::fabs ((double )got - ref ) /mag ); 251 } 252const uint8_t * hrow = hq + e * (size_t )NCH_D * 34 ; 253const float * hsr = xs ?hs + e * (size_t )NCH_D :nullptr ; 254for (int rr = 0 ;rr < H ;rr += 13 ) { 255double mag ; 256const double ref = row_ref (b + O_D_CODES + (size_t )rr * ROW_D ,b + O_D_SCALES + (size_t )rr * SC_D * 2 , 257hrow ,hsr ,NCH_D ,& mag ); 258const float got = r .out [(size_t )ent [e ].dst * H + (size_t )rr ]; 259++ checked ; 260if (!close_to (got ,ref ,mag ))++ bad ; 261if (mag > 0 )worst = std::max (worst , std::fabs ((double )got - ref ) /mag ); 262 } 263 } 264 std::printf (" %-44s host reference: %ld rows, %ld outside tolerance, worst %.2e of sum|term|\n" ,name ,checked , 265bad ,worst ); 266if (bad || checked == 0 )++ g_fail ; 267} 268 269struct Fixture { 270int nb = 0 ; 271 std::vector < uint8_t > h ;// nb blobs 272uint8_t * d = nullptr ; 273const uint8_t * hb (int i )const {return h .data ()+ (size_t )i * BLOB ; } 274}; 275 276Fixture make_blobs (int nb , std::mt19937 & rng ) { 277Fixture f ; 278f .nb = nb ; 279f .h .resize ((size_t )nb * BLOB ); 280for (int i = 0 ;i < nb ;++ i )fill_blob (f .h .data ()+ (size_t )i * BLOB ,rng ); 281f .d = dalloc < uint8_t > ((size_t )nb * BLOB ); 282up (f .d ,f .h ); 283return f ; 284} 285 286Scratch make_scratch (int64_t cap ) { 287Scratch s ; 288s .cap = cap ; 289s .bytes = k::moe_hit_grouped_scratch_bytes (cap ,H ,FF ); 290s .p = dalloc < uint8_t > (s .bytes ); 291return s ; 292} 293 294// ---------------------------------------------------------------- the checks 295void check_all () { 296 std::mt19937 rng (20260928 ); 297const Fixture fx = make_blobs (12 ,rng ); 298constexpr int K = 10 ; 299 300// Activations for up to 8 tokens, device copies with and without the fp32 scales. 301 std::vector < uint8_t > x ; 302 std::vector < float > xs ; 303fill_x (x ,xs ,8 ,rng ); 304uint8_t * d_x = dalloc < uint8_t > (x .size ()); 305float * d_xs = dalloc < float > (xs .size ()); 306up (d_x ,x ); 307up (d_xs ,xs ); 308 309// ---- 1. moe_hit_grouped_s2: 9 hits of 10 routed rows, slots and destinations shuffled 310 { 311const int n_hits = 9 ; 312 std::vector < int32_t > slot (n_hits ),dst (K ); 313for (int i = 0 ;i < n_hits ;++ i )slot [i ]= (int32_t ) ((i * 5 + 3 ) %fx .nb ); 314 std::iota (dst .begin (),dst .end (),0 ); 315 std::shuffle (dst .begin (),dst .end (),rng ); 316dst .resize (n_hits ); 317int32_t * d_slot = dalloc < int32_t > (n_hits ); 318int32_t * d_dst = dalloc < int32_t > (n_hits ); 319up (d_slot ,slot ); 320up (d_dst ,dst ); 321const Scratch s = make_scratch (n_hits ); 322float * d_out = dalloc < float > ((size_t )K * H ); 323 std::vector < Entry > ent ; 324for (int i = 0 ;i < n_hits ;++ i )ent .push_back ({fx .hb (slot [i ]),0 ,dst [i ]}); 325for (int scaled = 1 ;scaled >=0 ;-- scaled ) { 326Run r ; 327const std::string name = std::string ("moe_hit_grouped_s2" )+ (scaled ?" (fp32 scales)" :" (fp16 d)" ); 328twice (name .c_str (),d_out , (size_t )K * H ,s , [& ] { 329 k::moe_hit_grouped_s2 (fx .d ,d_slot ,d_dst ,n_hits , (int64_t )BLOB ,d_x ,s .p ,d_out ,nullptr , 330scaled ?d_xs :nullptr ); 331 },& r ); 332reference (name .c_str (),r ,s ,ent ,x ,scaled ?& xs :nullptr ); 333 } 334 } 335 336// ---- 2. moe_hit_grouped_s2_dev: capacity 10, device count 7 337 { 338const int cap = 10 ,count = 7 ; 339 std::vector < int32_t > slot (cap ),dst (cap ); 340for (int i = 0 ;i < cap ;++ i )slot [i ]= (int32_t ) ((i * 7 + 1 ) %fx .nb ); 341 std::iota (dst .begin (),dst .end (),0 ); 342 std::shuffle (dst .begin (),dst .end (),rng ); 343int32_t * d_slot = dalloc < int32_t > (cap ); 344int32_t * d_dst = dalloc < int32_t > (cap ); 345int32_t * d_count = dalloc < int32_t > (1 ); 346up (d_slot ,slot ); 347up (d_dst ,dst ); 348up (d_count , std::vector < int32_t > {count }); 349const Scratch s = make_scratch (cap ); 350float * d_out = dalloc < float > ((size_t )K * H ); 351 std::vector < Entry > ent ; 352for (int i = 0 ;i < count ;++ i )ent .push_back ({fx .hb (slot [i ]),0 ,dst [i ]}); 353Run r ; 354twice ("moe_hit_grouped_s2_dev (count 7 of 10)" ,d_out , (size_t )K * H ,s , [& ] { 355 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 , 356d_xs ); 357 },& r ); 358reference ("moe_hit_grouped_s2_dev (count 7 of 10)" ,r ,s ,ent ,x ,& xs ); 359// the rows of the hits past the count keep the sentinel 360long touched = 0 ; 361for (int i = count ;i < cap ;++ i ) 362for (int c = 0 ;c < H ;++ c ) { 363uint32_t v ; 364 std::memcpy (& v ,& r .out [(size_t )dst [i ]* H + c ],4 ); 365touched += v != 0xA5A5A5A5u ; 366 } 367 std::printf (" %-44s rows past the count written: %ld\n" ,"moe_hit_grouped_s2_dev (count 7 of 10)" ,touched ); 368if (touched )++ g_fail ; 369 } 370 371// ---- 3. moe_hit_grouped_s2_multi: 4 tokens x 10 routed entries, 29 hits 372 { 373const int T = 4 ,n = T * K ,count = 29 ; 374 std::vector < int32_t > ent_ids (n ); 375 std::iota (ent_ids .begin (),ent_ids .end (),0 ); 376 std::shuffle (ent_ids .begin (),ent_ids .end (),rng ); 377 std::vector < int32_t > slot (n ),dst (n ); 378for (int i = 0 ;i < n ;++ i ) { 379dst [i ]= ent_ids [i ]; 380slot [i ]= (int32_t ) (rng () %fx .nb ); 381 } 382 std::sort (dst .begin (),dst .begin ()+ count );// hit order is routing order, as `moe_hit_select_multi` makes it 383int32_t * d_slot = dalloc < int32_t > (n ); 384int32_t * d_dst = dalloc < int32_t > (n ); 385int32_t * d_count = dalloc < int32_t > (1 ); 386up (d_slot ,slot ); 387up (d_dst ,dst ); 388up (d_count , std::vector < int32_t > {count }); 389const Scratch s = make_scratch (n ); 390float * d_out = dalloc < float > ((size_t )n * H ); 391 std::vector < Entry > ent ; 392for (int i = 0 ;i < count ;++ i )ent .push_back ({fx .hb (slot [i ]),dst [i ] /K ,dst [i ]}); 393Run r ; 394twice ("moe_hit_grouped_s2_multi (4 tokens, 29 hits)" ,d_out , (size_t )n * H ,s , [& ] { 395 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 , 396nullptr ); 397 },& r ); 398reference ("moe_hit_grouped_s2_multi (4 tokens, 29 hits)" ,r ,s ,ent ,x ,& xs ); 399 } 400 401// ---- 4. moe_grouped_s2: 8 tokens x 10 entries in groups of 1..8, one group on a mapped host blob 402 { 403const int T = 8 ,n = T * K ; 404uint8_t * h_host = nullptr ; 405uint8_t * d_host = nullptr ; 406/* 407DPCT1048: The original value cudaHostAllocMapped is not meaningful in 408the migrated code and was removed or replaced with 0. You may need to 409check the migrated code. 410*/ 411ck (DPCT_CHECK_ERROR (h_host = (uint8_t * )sycl::malloc_host ( 412BLOB , dpct::get_in_order_queue ())), 413"host blob" ); 414 std::memcpy (h_host ,fx .hb (fx .nb - 1 ),BLOB ); 415ck (DPCT_CHECK_ERROR (* (void ** )& d_host = (uint8_t * )h_host ), 416"host blob ptr" ); 417// group sizes: 8, 1, 5, 2, 7, 3, 1, 6, 4, ... up to n entries 418const int sizes []= {8 ,1 ,5 ,2 ,7 ,3 ,1 ,6 ,4 ,8 ,1 ,2 ,3 ,4 ,5 ,6 ,7 ,1 ,1 ,5 }; 419 std::vector < int32_t > order (n );// the output rows, in group order 420 std::iota (order .begin (),order .end (),0 ); 421 std::shuffle (order .begin (),order .end (),rng ); 422 std::vector < unsigned long long > gptr ; 423 std::vector < int32_t > gstart {0 },edst ,etok ; 424 std::vector < Entry > ent ; 425int at = 0 ,gi = 0 ; 426while (at < n ) { 427const int sz = std::min (sizes [gi %20 ],n - at ); 428const bool host = gi == 3 ; 429const int b = gi % (fx .nb - 1 ); 430gptr .push_back ((unsigned long long ) (host ?d_host :fx .d + (size_t )b * BLOB )); 431for (int j = 0 ;j < sz ;++ j ,++ at ) { 432edst .push_back (order [at ]); 433etok .push_back (order [at ] /K ); 434ent .push_back ({host ?h_host :fx .hb (b ),order [at ] /K ,order [at ]}); 435 } 436gstart .push_back (at ); 437++ gi ; 438 } 439const int n_groups = gi ,cap_groups = n_groups + 3 ; 440gstart .resize ((size_t )cap_groups + 1 ,at ); 441gptr .resize ((size_t )cap_groups ,gptr [0 ]); 442unsigned long long * d_gptr = dalloc < unsigned long long > (gptr .size ()); 443int32_t * d_gstart = dalloc < int32_t > (gstart .size ()); 444int32_t * d_ng = dalloc < int32_t > (1 ); 445int32_t * d_edst = dalloc < int32_t > (n ); 446int32_t * d_etok = dalloc < int32_t > (n ); 447up (d_gptr ,gptr ); 448up (d_gstart ,gstart ); 449up (d_ng , std::vector < int32_t > {n_groups }); 450up (d_edst ,edst ); 451up (d_etok ,etok ); 452const Scratch s = make_scratch (n ); 453float * d_out = dalloc < float > ((size_t )n * H ); 454for (int scaled = 1 ;scaled >=0 ;-- scaled ) { 455Run r ; 456const std::string name = std::string ("moe_grouped_s2 (" )+ std::to_string (n_groups )+ " groups" + 457 (scaled ?", fp32 scales)" :", fp16 d)" ); 458twice (name .c_str (),d_out , (size_t )n * H ,s , [& ] { 459 k::moe_grouped_s2 (d_gptr ,d_gstart ,d_ng ,d_edst ,d_etok ,cap_groups ,n ,d_x ,scaled ?d_xs :nullptr , 460s .p ,d_out ,nullptr ); 461 },& r ); 462reference (name .c_str (),r ,s ,ent ,x ,scaled ?& xs :nullptr ); 463 } 464ck (DPCT_CHECK_ERROR (sycl::free (h_host , dpct::get_in_order_queue ())), 465"free host blob" ); 466 } 467 468// ---- 5. moe_group_resident + moe_grouped_s2: the MTP layer (experts resident at base + id * BLOB) 469 { 470const int T = 5 ,n = T * K ; 471 std::vector < int32_t > ids (n ); 472for (int t = 0 ;t < T ;++ t ) {// distinct within a token, shared across tokens 473 std::vector < int32_t > pick (fx .nb ); 474 std::iota (pick .begin (),pick .end (),0 ); 475 std::shuffle (pick .begin (),pick .end (),rng ); 476for (int j = 0 ;j < K ;++ j )ids [(size_t )t * K + j ]= pick [j ]; 477 } 478int32_t * d_ids = dalloc < int32_t > (n ); 479up (d_ids ,ids ); 480unsigned long long * d_gptr = dalloc < unsigned long long > (n ); 481int32_t * d_gstart = dalloc < int32_t > (n + 1 ); 482int32_t * d_counts = dalloc < int32_t > (2 ); 483int32_t * d_edst = dalloc < int32_t > (n ); 484int32_t * d_etok = dalloc < int32_t > (n ); 485 k::moe_group_resident (d_ids ,n ,K ,fx .d , (int64_t )BLOB ,d_gptr ,d_gstart ,d_counts ,d_edst ,d_etok ,nullptr ); 486ck (DPCT_CHECK_ERROR (dpct::get_current_device ().queues_wait_and_throw ()), 487"group_resident" ); 488const std::vector < int32_t > edst = down (d_edst ,n ),etok = down (d_etok ,n ); 489 std::vector < Entry > ent (n );// entry e: dst = routing index, blob = its expert 490for (int e = 0 ;e < n ;++ e )ent [e ]= {fx .hb (ids [(size_t )edst [e ]]),etok [e ],edst [e ]}; 491const Scratch s = make_scratch (n ); 492float * d_out = dalloc < float > ((size_t )n * H ); 493for (int scaled = 1 ;scaled >=0 ;-- scaled ) { 494Run r ; 495const std::string name = std::string ("moe_group_resident + moe_grouped_s2" )+ (scaled ?" (fp32)" :" (fp16)" ); 496twice (name .c_str (),d_out , (size_t )n * H ,s , [& ] { 497 k::moe_grouped_s2 (d_gptr ,d_gstart ,d_counts ,d_edst ,d_etok ,n ,n ,d_x ,scaled ?d_xs :nullptr ,s .p , 498d_out ,nullptr ); 499 },& r ); 500reference (name .c_str (),r ,s ,ent ,x ,scaled ?& xs :nullptr ); 501 } 502 } 503 504// ---- 6. a 2-byte aligned activation row: the new path must decline and the previous kernels run 505 { 506uint8_t * d_x2 = dalloc < uint8_t > (x .size ()+ 2 ); 507/* 508DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 509assuming in the original code the source host memory is pageable memory. 510If the memory is not pageable, call wait() on event return by memcpy API 511to ensure synchronization behavior. 512*/ 513ck (DPCT_CHECK_ERROR ( 514 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy (d_x2 + 2 ,x .data (),XROW ).wait ()), 515"x2" ); 516const int n_hits = 3 ; 517 std::vector < int32_t > slot {2 ,5 ,7 },dst {4 ,0 ,9 }; 518int32_t * d_slot = dalloc < int32_t > (n_hits ); 519int32_t * d_dst = dalloc < int32_t > (n_hits ); 520up (d_slot ,slot ); 521up (d_dst ,dst ); 522const Scratch s = make_scratch (n_hits ); 523float * d_out = dalloc < float > ((size_t )K * H ); 524 std::vector < Entry > ent ; 525for (int i = 0 ;i < n_hits ;++ i )ent .push_back ({fx .hb (slot [i ]),0 ,dst [i ]}); 526Run r ; 527twice ("moe_hit_grouped_s2 (2-byte aligned x)" ,d_out , (size_t )K * H ,s , [& ] { 528 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 ); 529 },& r ,/*expect_new=*/ false); 530reference ("moe_hit_grouped_s2 (2-byte aligned x)" ,r ,s ,ent ,x ,& xs ); 531 } 532 533// ---- 7. slots BLOB + 4 bytes apart, and 8. an arena at an address that is 4 mod 8: per-hit fallback 534 { 535constexpr size_t STRIDE = BLOB + 4 ; 536 static_assert(STRIDE %8 != 0 ,"the stride must defeat the uint2 code loads" ); 537const int nb = 8 ; 538uint8_t * d_arena = dalloc < uint8_t > ((size_t )nb * STRIDE + 8 ); 539const int n_hits = 4 ; 540 std::vector < int32_t > slot {6 ,1 ,3 ,0 },dst {2 ,7 ,5 ,8 }; 541int32_t * d_slot = dalloc < int32_t > (n_hits ); 542int32_t * d_dst = dalloc < int32_t > (n_hits ); 543up (d_slot ,slot ); 544up (d_dst ,dst ); 545const Scratch s = make_scratch (n_hits ); 546float * d_out = dalloc < float > ((size_t )K * H ); 547 std::vector < Entry > ent ; 548for (int i = 0 ;i < n_hits ;++ i )ent .push_back ({fx .hb (slot [i ]),0 ,dst [i ]}); 549// One allocation for both layouts: the BLOB + 4 strided copies first, then the same blobs BLOB apart from 550// `d_arena + 4` over them. 551for (int i = 0 ;i < nb ;++ i ) 552/* 553DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 554assuming in the original code the source host memory is pageable 555memory. If the memory is not pageable, call wait() on event return 556by memcpy API to ensure synchronization behavior. 557*/ 558ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 559d_arena + (size_t )i * STRIDE ,fx .hb (i ),BLOB ).wait ()), 560"arena" ); 561 { 562Run r ; 563twice ("moe_hit_grouped_s2 (slot stride BLOB + 4)" ,d_out , (size_t )K * H ,s , [& ] { 564 k::moe_hit_grouped_s2 (d_arena ,d_slot ,d_dst ,n_hits , (int64_t )STRIDE ,d_x ,s .p ,d_out ,nullptr , 565d_xs ); 566 },& r ,/*expect_new=*/ false); 567reference ("moe_hit_grouped_s2 (slot stride BLOB + 4)" ,r ,s ,ent ,x ,& xs ); 568 } 569for (int i = 0 ;i < nb ;++ i ) 570/* 571DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 572assuming in the original code the source host memory is pageable 573memory. If the memory is not pageable, call wait() on event return 574by memcpy API to ensure synchronization behavior. 575*/ 576ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 577d_arena + 4 + (size_t )i * BLOB ,fx .hb (i ),BLOB ).wait ()), 578"arena" ); 579 { 580Run r ; 581twice ("moe_hit_grouped_s2 (arena 4 mod 8)" ,d_out , (size_t )K * H ,s , [& ] { 582 k::moe_hit_grouped_s2 (d_arena + 4 ,d_slot ,d_dst ,n_hits , (int64_t )BLOB ,d_x ,s .p ,d_out ,nullptr , 583d_xs ); 584 },& r ,/*expect_new=*/ false); 585reference ("moe_hit_grouped_s2 (arena 4 mod 8)" ,r ,s ,ent ,x ,& xs ); 586 } 587 } 588} 589 590// ---------------------------------------------------------------- --bench 591// Engine-like shapes with the blobs cycled through a set larger than the L2, so each call reads its codes from 592// DRAM as the engine's do. Reports microseconds per call and the codes' effective bandwidth. 593void bench () { 594int dev = 0 ; 595 dpct::device_info prop {}; 596ck (DPCT_CHECK_ERROR (dev = dpct::get_current_device_id ()),"dev" ); 597ck (DPCT_CHECK_ERROR (dpct::get_device (dev ).get_device_info (prop )),"props" ); 598/* 599DPCT1051: SYCL does not support a device property functionally 600compatible with l2CacheSize. It was migrated to global_mem_cache_size. You 601may need to adjust the value of global_mem_cache_size for the specific 602device. 603*/ 604const int nb = std::max ( 60548 , (int )(3ull * (size_t )prop .get_global_mem_cache_size () /BLOB )+ 8 ); 606/* 607DPCT1051: SYCL does not support a device property functionally 608compatible with l2CacheSize. It was migrated to global_mem_cache_size. You 609may need to adjust the value of global_mem_cache_size for the specific 610device. 611*/ 612 std::printf ("bench: %s, L2 %d MB, %d blobs (%.0f MB) cycled\n" , 613prop .get_name (),prop .get_global_mem_cache_size () >>20 ,nb , 614nb * (double )BLOB /1e6 ); 615 std::mt19937 rng (7 ); 616Fixture fx ; 617fx .nb = nb ; 618fx .d = dalloc < uint8_t > ((size_t )nb * BLOB ); 619 { 620 std::vector < uint8_t > b (BLOB ); 621for (int i = 0 ;i < nb ;++ i ) { 622fill_blob (b .data (),rng ); 623/* 624DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, 625assuming in the original code the source host memory is pageable 626memory. If the memory is not pageable, call wait() on event return 627by memcpy API to ensure synchronization behavior. 628*/ 629ck (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 630fx .d + (size_t )i * BLOB ,b .data (),BLOB ).wait ()), 631"blob" ); 632 } 633 } 634 std::vector < uint8_t > x ; 635 std::vector < float > xs ; 636fill_x (x ,xs ,8 ,rng ); 637uint8_t * d_x = dalloc < uint8_t > (x .size ()); 638float * d_xs = dalloc < float > (xs .size ()); 639up (d_x ,x ); 640up (d_xs ,xs ); 641constexpr int K = 10 ,ITERS = 200 ,SETS = 16 ; 642 dpct::event_ptr e0 ,e1 ; 643ck (DPCT_CHECK_ERROR (e0 = new sycl::event ()),"ev" ); 644ck (DPCT_CHECK_ERROR (e1 = new sycl::event ()),"ev" ); 645auto time = [& ](const std::function < void (int )> & call ) { 646try { 647call (0 ); 648ck (DPCT_CHECK_ERROR (dpct::get_current_device ().queues_wait_and_throw ()), 649"warm" ); 650/* 651DPCT1024: The original code returned the error code that was further 652consumed by the program logic. This original code was replaced with 0. 653You may need to rewrite the program logic consuming the error code. 654*/ 655ck (DPCT_CHECK_ERROR (dpct::sync_barrier (e0 )),"rec" ); 656for (int i = 0 ;i < ITERS ;++ i )call (i %SETS ); 657/* 658DPCT1024: The original code returned the error code that was further 659consumed by the program logic. This original code was replaced with 0. 660You may need to rewrite the program logic consuming the error code. 661*/ 662ck (DPCT_CHECK_ERROR (dpct::sync_barrier (e1 )),"rec" ); 663ck (DPCT_CHECK_ERROR (e1 -> wait_and_throw ()),"sync" ); 664float ms = 0 ; 665ck (DPCT_CHECK_ERROR ( 666ms = (e1 -> get_profiling_info < 667 sycl::info::event_profiling::command_end > ()- 668e0 -> get_profiling_info < 669 sycl::info::event_profiling::command_start > ()) / 6701000000.0f ), 671"elapsed" ); 672return 1000.0 * ms /ITERS ; 673 } 674catch (sycl::exception const & exc ) { 675 std::cerr <<exc .what () <<"Exception caught at file:" <<__FILE__ 676 <<", line:" <<__LINE__ << std::endl ; 677 std::exit (1 ); 678 } 679 }; 680auto ab = [& ](const char * name ,double blobs_per_call ,const std::function < void (int )>& call ) { 681double us [2 ]; 682for (int old = 1 ;old >=0 ;-- old ) { 683 k::moe_grouped_select_old (old ); 684us [old ?0 :1 ]= time (call ); 685 } 686 k::moe_grouped_select_old (-1 ); 687const double gb = blobs_per_call * (double )BLOB /1e3 ;// bytes / us = MB/s ... / 1e3 -> GB/s 688 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 ], 689gb /us [0 ],us [1 ],gb /us [1 ],us [0 ] /us [1 ]); 690 }; 691 692// per-hit path, decode: 9 hits of 10 (5090-like residency), 5 of 10, and the low-residency 1-3 hits, where the 693// new kernels' grid (80 gate/up blocks per hit) is below one block per SM - see `STRATA_GROUPED_PAIR_MIN_HITS` 694for (const int n_hits : {9 ,5 ,3 ,2 ,1 }) { 695 std::vector < int32_t > slots ((size_t )SETS * n_hits ),dst (K ); 696for (auto & v :slots )v = (int32_t ) (rng () %nb ); 697 std::iota (dst .begin (),dst .end (),0 ); 698int32_t * d_slots = dalloc < int32_t > (slots .size ()); 699int32_t * d_dst = dalloc < int32_t > (K ); 700up (d_slots ,slots ); 701up (d_dst ,dst ); 702const Scratch s = make_scratch (n_hits ); 703float * d_out = dalloc < float > ((size_t )K * H ); 704const std::string name = "moe_hit_grouped_s2, " + std::to_string (n_hits )+ " hits" ; 705ab (name .c_str (),n_hits , [& ](int set ) { 706 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 , 707d_out ,nullptr ,d_xs ); 708 }); 709 } 710// grouped path, verify window: T tokens x 10, routed with `share` = the chance an entry reuses an expert already 711// routed by an earlier token of the window 712struct Shape {int T ;double share ;const char * what ; }; 713for (const Shape sh : {Shape {4 ,0.0 ,"4 tokens, no sharing" },Shape {4 ,0.3 ,"4 tokens, 30% shared" }, 714Shape {8 ,0.3 ,"8 tokens, 30% shared" },Shape {8 ,1.0 ,"8 tokens, all shared (ne 8)" }}) { 715const int n = sh .T * K ; 716 std::vector < unsigned long long > gptr ((size_t )SETS * n ); 717 std::vector < int32_t > gstart ((size_t )SETS * (n + 1 )),ng (SETS ),edst ((size_t )SETS * n ),etok ((size_t )SETS * n ); 718double groups = 0 ; 719 std::uniform_real_distribution < double > u (0 ,1 ); 720for (int set = 0 ;set < SETS ;++ set ) { 721 std::vector < std::vector < int >> g ;// per group: routing indices 722 std::vector < int > gexp ;// per group: blob 723for (int t = 0 ;t < sh .T ;++ t ) { 724 std::vector < char > used (g .size (),0 ); 725for (int j = 0 ;j < K ;++ j ) { 726int pick = -1 ; 727if (t > 0 && u (rng )< sh .share ) 728for (size_t q = 0 ;q < g .size ();++ q ) 729if (!used [q ]&& (int )g [q ].size ()< 8 ) {pick = (int )q ;break ; } 730if (pick < 0 ) { 731pick = (int )g .size (); 732g .emplace_back (); 733gexp .push_back ((int ) (rng () %nb )); 734used .push_back (0 ); 735 } 736used [(size_t )pick ]= 1 ; 737g [(size_t )pick ].push_back (t * K + j ); 738 } 739 } 740int at = 0 ; 741for (size_t q = 0 ;q < g .size ();++ q ) { 742gptr [(size_t )set * n + q ]= (unsigned long long ) (fx .d + (size_t )gexp [q ]* BLOB ); 743gstart [(size_t )set * (n + 1 )+ q ]= at ; 744for (int e :g [q ]) { 745edst [(size_t )set * n + at ]= e ; 746etok [(size_t )set * n + at ]= e /K ; 747++ at ; 748 } 749 } 750for (size_t q = g .size ();q <= (size_t )n ;++ q )gstart [(size_t )set * (n + 1 )+ q ]= at ; 751ng [set ]= (int32_t )g .size (); 752groups += (double )g .size () /SETS ; 753 } 754unsigned long long * d_gptr = dalloc < unsigned long long > (gptr .size ()); 755int32_t * d_gstart = dalloc < int32_t > (gstart .size ()); 756int32_t * d_ng = dalloc < int32_t > (SETS ); 757int32_t * d_edst = dalloc < int32_t > (edst .size ()); 758int32_t * d_etok = dalloc < int32_t > (etok .size ()); 759up (d_gptr ,gptr ); 760up (d_gstart ,gstart ); 761up (d_ng ,ng ); 762up (d_edst ,edst ); 763up (d_etok ,etok ); 764const Scratch s = make_scratch (n ); 765float * d_out = dalloc < float > ((size_t )n * H ); 766char name [96 ]; 767 std::snprintf (name ,sizeof name ,"moe_grouped_s2, %s (%.0f groups)" ,sh .what ,groups ); 768ab (name ,groups , [& ](int set ) { 769 k::moe_grouped_s2 (d_gptr + (size_t )set * n ,d_gstart + (size_t )set * (n + 1 ),d_ng + set , 770d_edst + (size_t )set * n ,d_etok + (size_t )set * n ,n ,n ,d_x ,d_xs ,s .p ,d_out , 771nullptr ); 772 }); 773 } 774} 775}// namespace 776 777int main (int argc ,char ** argv ) { 778bool do_bench = false; 779for (int i = 1 ;i < argc ;++ i ) { 780if (std::strcmp (argv [i ],"--bench" )== 0 )do_bench = true; 781else if (std::strcmp (argv [i ],"--selftest" )!= 0 ) { 782 std::fprintf (stderr ,"usage: s2_expert_grouped_parity [--selftest] [--bench]\n" ); 783return 2 ; 784 } 785 } 786 std::printf ("s2_expert_grouped_parity: new expert kernels vs the previous ones, bitwise\n" ); 787check_all (); 788if (do_bench )bench (); 789 std::printf ("s2_expert_grouped_parity: %d failures\n%s\n" ,g_fail ,g_fail ?"FAIL" :"PASS" ); 790return g_fail ?1 :0 ; 791}