okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f2b41fd29
main
1// prefill_fused_moe_test - #136: the fused int8 expert kernels of the prompt path (moe_fused.hpp, STRATA_PF_FUSED=1) 2// on random Strata Q2_0 expert blobs and random routing, against 3// - a double-precision reference: the dequantized weights times the FP32 activations (gate/up, SwiGLU, down), and 4// - the MMQ path in prefill.cpp's sequence (gather_strata_q2 into 16-expert groups, q8_1 of the slots' activations, 5// gate/up, SwiGLU, q8_1 of H, down). 6// Both round the activations and H to int8 per 32 values, differently, so this is not a bitwise test: the fused 7// path's error against the reference has to be comparable to MMQ's own (at most 1.5x its RMS and 2x its worst row). 8// Part 1 (reference): 256 tokens over 64 experts, skewed routing - experts with 0 rows, with one, with several 64-row 9// tiles - an all-zero token, per-expert blobs at unrelated addresses, three launches of different expert ranges. 10// Part 2 (timing): one layer at a real chunk (2048 tokens, 512 experts, top 10) on both paths, with their agreement. 11// Exit 77 without a CUDA device of sm_80 or newer. 12#include "strata/prefill/moe_fused.hpp" 13#include "strata/prefill/mmq_ids_margin.hpp" 14#include "strata/prefill/moe_mmq.hpp" 15 16#include "ggml.h" 17 18#include <cuda_runtime.h> 19 20#include <algorithm> 21#include <cmath> 22#include <cstdint> 23#include <cstdio> 24#include <cstring> 25#include <memory> 26#include <random> 27#include <stdexcept> 28#include <string> 29#include <thread> 30#include <vector> 31 32namespace { 33namespace mmq= strata::prefill::mmq; 34namespace fused= strata::prefill::fused; 35 36// The compiled geometry's widths and top-k (Flash-Next: 2560 x 640, top 10); the blob is the Strata Q2 layout at that shape 37// (Flash-Next: 1,382,400 B): gate/up codes [2 FF][N / 4 B], down codes [N][FF / 4 B], gate/up scales [2 FF][N / 64] f16, down scales [N][FF / 64] f16. 38constexpr int N = fused::kMoeEmbd ,FF = fused::kMoeFF ,FF2 = fused::kMoeGuRows ,K = (int ) strata::core::kCompiledGeometry .n_expert_used ,GROUP = 16 ,Q2 = 42 ;// GGML_TYPE_Q2_0 39constexpr int ROW_GU = N /4 ,ROW_D = FF /4 ,SC_GU = N /64 ,SC_D = FF /64 ; 40constexpr size_t O_D_CODES = (size_t )FF2 * ROW_GU ,O_GU_SC = O_D_CODES + (size_t )N * ROW_D ,O_D_SC = O_GU_SC + (size_t )FF2 * SC_GU * 2 , 41BLOB = O_D_SC + (size_t )N * SC_D * 2 ; 42 43void ck (cudaError_t e ,const char * what ) { 44if (e != cudaSuccess )throw std::runtime_error (std::string (what )+ ": " + cudaGetErrorString (e )); 45} 46 47struct Dev { 48void * p = nullptr ; 49explicit Dev (size_t n ) {ck (cudaMalloc (& p ,n ),"cudaMalloc" ); } 50 ~Dev () {cudaFree (p ); } 51Dev (const Dev & )= delete ; 52Dev & operator= (const Dev & )= delete ; 53template < typename T > T * as ()const {return (T * )p ; } 54}; 55 56// a Strata Q2_0 blob: random codes, scales in [0.004, 0.03] (a 2-bit expert's range) 57std::vector < uint8_t > make_blob (std::mt19937 & rng ) { 58 std::vector < uint8_t > b (BLOB ); 59 std::uniform_int_distribution < int > byte (0 ,255 ); 60 std::uniform_real_distribution < float > sc (0.004f ,0.03f ); 61for (size_t i = 0 ;i < O_GU_SC ;++ i )b [i ]= (uint8_t )byte (rng ); 62for (size_t i = O_GU_SC ;i < BLOB ;i += 2 ) { 63const ggml_fp16_t h = ggml_fp32_to_fp16 (sc (rng )); 64 std::memcpy (& b [i ],& h ,2 ); 65 } 66return b ; 67} 68 69// the blob's weights as floats: gate/up [2 FF][N] (interleaved rows), down [N][FF] 70void dequant (const std::vector < uint8_t >& b , std::vector < float >& gu , std::vector < float >& dn ) { 71auto row = [& ](size_t codes ,size_t ld ,size_t scales ,int nb ,int r ,float * out ) { 72for (int k = 0 ;k < nb * 64 ;++ k ) { 73ggml_fp16_t h ; 74 std::memcpy (& h ,& b [scales + ((size_t )r * nb + k /64 )* 2 ],2 ); 75const int q = (b [codes + (size_t )r * ld + k /4 ] >> (2 * (k %4 )))& 3 ; 76out [k ]= ggml_fp16_to_fp32 (h )* (float ) (q - 1 ); 77 } 78 }; 79gu .resize ((size_t )FF2 * N ); 80dn .resize ((size_t )N * FF ); 81for (int r = 0 ;r < FF2 ;++ r )row (0 ,ROW_GU ,O_GU_SC ,SC_GU ,r ,gu .data ()+ (size_t )r * N ); 82for (int r = 0 ;r < N ;++ r )row (O_D_CODES ,ROW_D ,O_D_SC ,SC_D ,r ,dn .data ()+ (size_t )r * FF ); 83} 84 85// activations: N(0, 1) with a few large values (the hidden state has outliers); token `zero` all zero 86std::vector < float > make_x (int T , std::mt19937 & rng ,int zero ) { 87 std::vector < float > x ((size_t )T * N ); 88 std::normal_distribution < float > nd (0.0f ,1.0f ); 89 std::uniform_int_distribution < int > pick (0 ,199 ); 90for (float & v :x )v = nd (rng )* (pick (rng )== 0 ?12.0f :1.0f ); 91if (zero >=0 ) std::fill (x .begin ()+ (size_t )zero * N ,x .begin ()+ (size_t ) (zero + 1 )* N ,0.0f ); 92return x ; 93} 94 95// K distinct experts per token; `hot` > 0 skews the first choices towards the lowest ids 96std::vector < int32_t > make_ids (int T ,int E , std::mt19937 & rng ,int hot ,int unused ) { 97 std::vector < int32_t > ids ((size_t )T * K ); 98 std::uniform_int_distribution < int > any (0 ,E - 1 - unused ); 99for (int t = 0 ;t < T ;++ t ) 100for (int k = 0 ;k < K ;++ k ) { 101int e ; 102bool dup ; 103do { 104e = (hot > 0 && k < 3 && (int ) (rng () %4 )!= 0 ) ? (int ) (rng () % (unsigned )hot ) :any (rng ); 105dup = false; 106for (int j = 0 ;j < k ;++ j )dup |=ids [(size_t )t * K + j ]== e ; 107 }while (dup ); 108ids [(size_t )t * K + k ]= e ; 109 } 110return ids ; 111} 112 113struct Routing { 114 std::vector < int32_t > cnt ,off ,src ;// per expert; sorted row -> token (rows in pair order within an expert) 115 std::vector < int32_t > row_of ;// pair -> sorted row 116}; 117Routing sort_rows (const std::vector < int32_t >& ids ,int E ) { 118Routing r ; 119r .cnt .assign ((size_t )E ,0 ); 120for (int32_t e :ids )++ r .cnt [(size_t )e ]; 121r .off .assign ((size_t )E + 1 ,0 ); 122for (int e = 0 ;e < E ;++ e )r .off [(size_t )e + 1 ]= r .off [(size_t )e ]+ r .cnt [(size_t )e ]; 123 std::vector < int32_t > fill (r .off .begin (),r .off .end ()- 1 ); 124r .src .resize (ids .size ()); 125r .row_of .resize (ids .size ()); 126for (size_t i = 0 ;i < ids .size ();++ i ) { 127const int32_t p = fill [(size_t )ids [i ]]++ ; 128r .row_of [i ]= p ; 129r .src [(size_t )p ]= (int32_t ) (i /K ); 130 } 131return r ; 132} 133 134// MMQ, as prefill.cpp runs it: per group of 16 routed experts a gather, gate/up, SwiGLU, q8_1 of H, down. Returns 135// Dm [rows][N] in sorted-row order. 136// llama.cpp's mul_mat_q and its stream-k fixup read the row-id table up to a J-column tile (J <= 128) past the last row, up to roundup(max_rows, J) from an 137// expert's first row: the table takes mmq_ids_table_rows(rows, max_rows) entries (mmq_ids_margin.hpp), the identity written over all of them. 138size_t ids_table_rows (int64_t rows ) {return (size_t ) mmq::mmq_ids_table_rows ((uint64_t )rows , (uint64_t ) (rows /K )); } 139struct MmqBufs { 140Dev xq ,gu ,h ,hq ,dm ,ident ,bounds ,grp_gu ,grp_d ; 141MmqBufs (int64_t rows ,int E ) 142 :xq (mmq::q8_bytes (rows ,N )),gu ((size_t )rows * FF2 * 4 ),h ((size_t )rows * FF * 4 ), 143hq (mmq::q8_bytes (rows ,FF )), 144dm ((size_t )rows * N * 4 ),ident (ids_table_rows (rows )* 4 ),bounds ((size_t ) (2 * (E + E /GROUP + 2 ))* 4 ), 145grp_gu (GROUP * mmq::matrix_bytes (Q2 ,FF2 ,N )+ 4096 ),grp_d (GROUP * mmq::matrix_bytes (Q2 ,N ,FF )+ 4096 ) {} 146}; 147void run_mmq (mmq::Context & ctx ,MmqBufs & b ,const Routing & r ,const float * x_dev ,const int32_t * src_dev , 148const std::vector < const uint8_t *>& blob ,int64_t rows ,cudaStream_t s ) { 149const size_t gub = mmq::matrix_bytes (Q2 ,FF2 ,N ),db = mmq::matrix_bytes (Q2 ,N ,FF ); 150const int E = (int )r .cnt .size (); 151 std::vector < int32_t > order ; 152for (int e = 0 ;e < E ;++ e )if (r .cnt [(size_t )e ]> 0 )order .push_back (e ); 153const size_t n = order .size (),ng = (n + GROUP - 1 ) /GROUP ; 154 std::vector < int32_t > bh (n + 1 + ng * (GROUP + 1 )); 155for (size_t j = 0 ;j < n ;++ j )bh [j ]= r .off [(size_t )order [j ]]; 156bh [n ]= (int32_t )rows ; 157for (size_t g = 0 ;g < ng ;++ g ) 158for (size_t i = 0 ;i <=GROUP ;++ i ) 159bh [n + 1 + g * (GROUP + 1 )+ i ]= bh [std::min (n ,g * GROUP + i )]- bh [g * GROUP ]; 160ck (cudaMemcpyAsync (b .bounds .p ,bh .data (),bh .size ()* 4 ,cudaMemcpyHostToDevice ,s ),"bounds" ); 161 mmq::iota (b .ident .as < int32_t > (), (int64_t )ids_table_rows (rows ),s ); 162 mmq::quantize (x_dev ,src_dev ,b .xq .p ,Q2 ,N ,N ,rows ,s ); 163for (size_t j = 0 ;j < n ;++ j ) { 164const size_t q = j %GROUP ; 165 mmq::gather_strata_q2 (blob [(size_t )order [j ]],b .grp_gu .as < uint8_t > ()+ q * gub ,b .grp_d .as < uint8_t > ()+ q * db , 166s ); 167if (q + 1 < GROUP && j + 1 < n )continue ; 168const size_t j0 = j - q ,g = j0 /GROUP ; 169const int ngx = (int ) (q + 1 ); 170const int64_t r0 = bh [j0 ],nr = bh [j + 1 ]- r0 ; 171int64_t maxr = 0 ; 172for (size_t i = j0 ;i <=j ;++ i )maxr = std::max < int64_t > (maxr ,r .cnt [(size_t )order [i ]]); 173ck (cudaMemsetAsync (b .grp_gu .as < uint8_t > ()+ (size_t )ngx * gub ,0 ,4096 ,s ),"tail" ); 174ck (cudaMemsetAsync (b .grp_d .as < uint8_t > ()+ (size_t )ngx * db ,0 ,4096 ,s ),"tail" ); 175 mmq::Product gu ; 176gu .w = b .grp_gu .p ;gu .type = Q2 ;gu .w_rows = FF2 ;gu .w_cols = N ;gu .expert_bytes = gub ; 177gu .n = ngx ;gu .xq = b .xq .p ;gu .bounds = b .bounds .as < int32_t > ()+ j0 ;gu .ids = b .ident .as < int32_t > (); 178gu .total_rows = rows ;gu .max_rows = maxr ;gu .dst = b .gu .as < float > ();gu .ld_dst = FF2 ; 179ctx .run (gu ,s ); 180 mmq::swiglu (b .gu .as < float > ()+ r0 * FF2 ,b .h .as < float > ()+ r0 * FF ,nr ,FF , true,s ); 181 mmq::quantize (b .h .as < float > ()+ r0 * FF ,nullptr ,b .hq .p ,Q2 ,FF ,FF ,nr ,s ); 182 mmq::Product dn ; 183dn .w = b .grp_d .p ;dn .type = Q2 ;dn .w_rows = N ;dn .w_cols = FF ;dn .expert_bytes = db ; 184dn .n = ngx ;dn .xq = b .hq .p ;dn .bounds = b .bounds .as < int32_t > ()+ n + 1 + g * (GROUP + 1 ); 185dn .ids = b .ident .as < int32_t > ();dn .total_rows = nr ;dn .max_rows = maxr ;dn .dst = b .dm .as < float > ()+ r0 * N ; 186dn .ld_dst = N ; 187ctx .run (dn ,s ); 188 } 189} 190 191// the fused path: quantize, group on the device, then launches over expert ranges `cuts` (e.g. {0, 20, 64}) 192struct FusedBufs { 193Dev xa ,ha ,dm ,scratch ,slot ,src ,ids ; 194FusedBufs (int T ,int64_t rows ,int E ) 195 :xa (fused::act_bytes (T ,N )),ha (fused::act_bytes (rows ,FF )),dm ((size_t )rows * N * 4 ), 196scratch (fused::group_bytes (rows ,E )),slot ((size_t )rows * 4 ),src ((size_t )rows * 4 ), 197ids ((size_t )rows * 4 ) {} 198}; 199void run_fused (FusedBufs & b ,const float * x_dev ,int T ,int E ,const std::vector < int >& cuts , 200const std::vector < const uint8_t *>& blob ,cudaStream_t s ) { 201const int64_t rows = (int64_t )T * K ; 202 fused::quantize_act (x_dev ,T ,N ,b .xa .p ,s ); 203 fused::group (b .ids .as < int32_t > (),rows ,K ,E ,b .scratch .p ,b .slot .as < int32_t > (),b .src .as < int32_t > (),s ); 204for (size_t c = 0 ;c + 1 < cuts .size ();++ c ) { 205for (int e0 = cuts [c ];e0 < cuts [c + 1 ];e0 += fused::kMaxBatch ) { 206 fused::Batch bt ; 207bt .e0 = e0 ; 208bt .e1 = std::min (cuts [c + 1 ],e0 + fused::kMaxBatch ); 209for (int e = bt .e0 ;e < bt .e1 ;++ e )bt .blob [e - bt .e0 ]= blob [(size_t )e ]; 210 fused::experts (bt ,E ,rows ,b .scratch .p ,b .xa .p ,b .src .as < int32_t > (),b .ha .p ,b .dm .as < float > (),s ); 211 } 212 } 213} 214 215struct Err { 216double rms = 0 ,worst = 0 ;// RMS error / RMS of the reference; the worst row's max |error| / its max |ref| 217}; 218// y_a[row_a(i)] against y_b[row_b(i)] for every pair i (rows of N values) 219template < typename RA ,typename RB > 220Err compare (const std::vector < float >& a ,RA row_a ,const std::vector < float >& b ,RB row_b ,size_t pairs ) { 221double e2 = 0 ,r2 = 0 ; 222Err out ; 223for (size_t i = 0 ;i < pairs ;++ i ) { 224const float * ya = a .data ()+ (size_t )row_a (i )* N ; 225const float * yb = b .data ()+ (size_t )row_b (i )* N ; 226double me = 0 ,mr = 0 ; 227for (int o = 0 ;o < N ;++ o ) { 228if (!std::isfinite (ya [o ]))throw std::runtime_error ("a non-finite output" ); 229const double d = (double )ya [o ]- yb [o ]; 230e2 += d * d ; 231r2 += (double )yb [o ]* yb [o ]; 232me = std::max (me , std::fabs (d )); 233mr = std::max (mr , (double ) std::fabs (yb [o ])); 234 } 235if (mr > 0 )out .worst = std::max (out .worst ,me /mr ); 236else if (me > 0 )out .worst = 1e30 ;// a zero row must stay exactly zero 237 } 238out .rms = r2 > 0 ? std::sqrt (e2 /r2 ) :0 ; 239return out ; 240} 241 242std::vector < float > download (const Dev & d ,size_t n ) { 243 std::vector < float > h (n ); 244ck (cudaMemcpy (h .data (),d .p ,n * 4 ,cudaMemcpyDeviceToHost ),"download" ); 245return h ; 246} 247std::vector < int32_t > download_i (const Dev & d ,size_t n ) { 248 std::vector < int32_t > h (n ); 249ck (cudaMemcpy (h .data (),d .p ,n * 4 ,cudaMemcpyDeviceToHost ),"download" ); 250return h ; 251} 252 253// part 1: against the double-precision reference 254void reference_part (cudaStream_t s ) { 255constexpr int T = 256 ,E = 64 ,ZERO = 77 ; 256 std::mt19937 rng (136 ); 257 std::vector < std::vector < uint8_t >> host ((size_t )E ); 258 std::vector < std::unique_ptr < Dev >> dev ; 259 std::vector < const uint8_t *> blob ((size_t )E ); 260for (int e = 0 ;e < E ;++ e ) { 261host [(size_t )e ]= make_blob (rng ); 262dev .push_back (std::make_unique < Dev > (BLOB + 4096 * (size_t ) (e %3 )));// unrelated addresses 263uint8_t * p = dev .back ()-> as < uint8_t > ()+ 256 * (size_t ) (e %3 );// 16-byte aligned, not 512 264ck (cudaMemcpy (p ,host [(size_t )e ].data (),BLOB ,cudaMemcpyHostToDevice ),"blob" ); 265blob [(size_t )e ]= p ; 266 } 267const std::vector < float > x = make_x (T ,rng ,ZERO ); 268const std::vector < int32_t > ids = make_ids (T ,E ,rng ,2 ,4 );// experts 0, 1 hot (several tiles), 60-63 unused 269const int64_t rows = (int64_t )T * K ; 270const Routing r = sort_rows (ids ,E ); 271 std::printf ("reference part: %d tokens, %d experts, rows per expert: max %d, experts without rows %d\n" ,T ,E , 272* std::max_element (r .cnt .begin (),r .cnt .end ()), (int ) std::count (r .cnt .begin (),r .cnt .end (),0 )); 273 274Dev x_dev (x .size ()* 4 ),src_dev ((size_t )rows * 4 ); 275ck (cudaMemcpy (x_dev .p ,x .data (),x .size ()* 4 ,cudaMemcpyHostToDevice ),"x" ); 276ck (cudaMemcpy (src_dev .p ,r .src .data (),r .src .size ()* 4 ,cudaMemcpyHostToDevice ),"src" ); 277 mmq::Context ctx ; 278MmqBufs mb (rows ,E ); 279// the uploads (legacy stream) must land before the non-blocking stream reads them (S20 found the kernels could run 280// on all-zero routing otherwise - every pair on one expert: fast and wrong) 281ck (cudaDeviceSynchronize (),"uploads" ); 282const bool mq = mmq::built ();// (P4-SPLIT: a build without MMQ checks the fused path against the reference alone) 283if (mq )run_mmq (ctx ,mb ,r ,x_dev .as < float > (),src_dev .as < int32_t > (),blob ,rows ,s ); 284FusedBufs fb (T ,rows ,E ); 285ck (cudaMemcpy (fb .ids .p ,ids .data (),ids .size ()* 4 ,cudaMemcpyHostToDevice ),"ids" ); 286ck (cudaMemset (fb .dm .p ,0xff , (size_t )rows * N * 4 ),"sentinel" );// an unwritten row is NaN 287ck (cudaDeviceSynchronize (),"uploads" ); 288run_fused (fb ,x_dev .as < float > (),T ,E , {0 ,1 ,20 ,E },blob ,s ); 289ck (cudaStreamSynchronize (s ),"sync" ); 290const std::vector < float > y_mmq = download (mb .dm , (size_t )rows * N ),y_f = download (fb .dm , (size_t )rows * N ); 291const std::vector < int32_t > slot = download_i (fb .slot , (size_t )rows ),fsrc = download_i (fb .src , (size_t )rows ); 292for (int64_t i = 0 ;i < rows ;++ i ) 293if (fsrc [(size_t )slot [(size_t )i ]]!= (int32_t ) (i /K ))throw std::runtime_error ("group: slot/src disagree" ); 294 295// the reference, an expert at a time on all cores 296 std::vector < float > ref ((size_t )rows * N ); 297 std::vector < std::thread > th ; 298const int nth = std::max (1 , std::min (16 , (int ) std::thread::hardware_concurrency ())); 299for (int w = 0 ;w < nth ;++ w ) 300th .emplace_back ([& ,w ] { 301 std::vector < float > gu ,dn ,h (FF ); 302for (int e = w ;e < E ;e += nth ) { 303if (r .cnt [(size_t )e ]== 0 )continue ; 304dequant (host [(size_t )e ],gu ,dn ); 305for (int64_t i = 0 ;i < rows ;++ i ) { 306if (ids [(size_t )i ]!= e )continue ; 307const float * xr = x .data ()+ (size_t ) (i /K )* N ; 308for (int f = 0 ;f < FF ;++ f ) { 309double gt = 0 ,up = 0 ; 310const float * wg = gu .data ()+ (size_t ) (2 * f )* N ,* wu = wg + N ; 311for (int k = 0 ;k < N ;++ k ) {gt += (double )wg [k ]* xr [k ];up += (double )wu [k ]* xr [k ]; } 312h [(size_t )f ]= (float ) (gt / (1.0 + std::exp (- gt ))* up ); 313 } 314for (int o = 0 ;o < N ;++ o ) { 315double a = 0 ; 316const float * wd = dn .data ()+ (size_t )o * FF ; 317for (int f = 0 ;f < FF ;++ f )a += (double )wd [f ]* h [(size_t )f ]; 318ref [(size_t )i * N + o ]= (float )a ; 319 } 320 } 321 } 322 }); 323for (auto & t :th )t .join (); 324 325auto pair = [](size_t i ) {return (int64_t )i ; }; 326auto mrow = [& ](size_t i ) {return (int64_t )r .row_of [i ]; }; 327auto frow = [& ](size_t i ) {return (int64_t )slot [i ]; }; 328const Err em = mq ?compare (y_mmq ,mrow ,ref ,pair , (size_t )rows ) :Err {}; 329const Err ef = compare (y_f ,frow ,ref ,pair , (size_t )rows ); 330const Err efm = mq ?compare (y_f ,frow ,y_mmq ,mrow , (size_t )rows ) :Err {}; 331if (mq ) std::printf (" MMQ vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n" ,em .rms ,em .worst ); 332 std::printf (" fused vs FP32 reference: rel RMS %.3e worst row max rel %.3e\n" ,ef .rms ,ef .worst ); 333if (mq ) std::printf (" fused vs MMQ : rel RMS %.3e worst row max rel %.3e\n" ,efm .rms ,efm .worst ); 334double zmax = 0 ; 335for (int k = 0 ;k < K ;++ k ) 336for (int o = 0 ;o < N ;++ o ) 337zmax = std::max (zmax , (double ) std::fabs (y_f [(size_t )slot [(size_t ) (ZERO * K + k )]* N + o ])); 338if (zmax != 0 )throw std::runtime_error ("the all-zero token's outputs are not zero" ); 339if (!mq ) {// no MMQ here: the int8 activations' own error, prefill_fused_iq_test's bound for the same case 340if (ef .rms > 0.03 || ef .worst > 0.25 )throw std::runtime_error ("the fused path's error against the reference is too large" ); 341return ; 342 } 343if (ef .rms > 1.5 * em .rms || ef .worst > 2.0 * em .worst ) 344throw std::runtime_error ("the fused path's error is not comparable to MMQ's" ); 345} 346 347// part 2: one layer at a real chunk, timed 348void timing_part (cudaStream_t s ) { 349constexpr int T = 2048 ,E = 512 ; 350 std::mt19937 rng (1360 ); 351const int64_t rows = (int64_t )T * K ; 352// 512 distinct blobs (708 MB) - the products read each once per tile, as the engine does 353Dev blobs ((size_t )E * BLOB ); 354 { 355 std::vector < uint8_t > b = make_blob (rng ); 356for (int e = 0 ;e < E ;++ e ) { 357b [(size_t )e * 7919 %O_GU_SC ] ^= (uint8_t )e ;// not all equal 358ck (cudaMemcpy (blobs .as < uint8_t > ()+ (size_t )e * BLOB ,b .data (),BLOB ,cudaMemcpyHostToDevice ),"blob" ); 359 } 360 } 361 std::vector < const uint8_t *> blob ((size_t )E ); 362for (int e = 0 ;e < E ;++ e )blob [(size_t )e ]= blobs .as < uint8_t > ()+ (size_t )e * BLOB ; 363const std::vector < float > x = make_x (T ,rng ,-1 ); 364const std::vector < int32_t > ids = make_ids (T ,E ,rng ,0 ,0 ); 365const Routing r = sort_rows (ids ,E ); 366Dev x_dev (x .size ()* 4 ),src_dev ((size_t )rows * 4 ); 367ck (cudaMemcpy (x_dev .p ,x .data (),x .size ()* 4 ,cudaMemcpyHostToDevice ),"x" ); 368ck (cudaMemcpy (src_dev .p ,r .src .data (),r .src .size ()* 4 ,cudaMemcpyHostToDevice ),"src" ); 369 mmq::Context ctx ; 370MmqBufs mb (rows ,E ); 371FusedBufs fb (T ,rows ,E ); 372ck (cudaMemcpy (fb .ids .p ,ids .data (),ids .size ()* 4 ,cudaMemcpyHostToDevice ),"ids" ); 373ck (cudaDeviceSynchronize (),"uploads" );// the legacy-stream uploads before the timed non-blocking stream 374cudaEvent_t a ,b ; 375ck (cudaEventCreate (& a ),"event" ); 376ck (cudaEventCreate (& b ),"event" ); 377auto time = [& ](auto && f ) { 378 std::vector < float > ms ; 379for (int rep = 0 ;rep < 6 ;++ rep ) { 380ck (cudaEventRecord (a ,s ),"record" ); 381f (); 382ck (cudaEventRecord (b ,s ),"record" ); 383ck (cudaEventSynchronize (b ),"sync" ); 384float t = 0 ; 385ck (cudaEventElapsedTime (& t ,a ,b ),"elapsed" ); 386if (rep > 0 )ms .push_back (t );// the first is the warm-up 387 } 388 std::sort (ms .begin (),ms .end ()); 389return ms [ms .size () /2 ]; 390 }; 391// the engine's batches: up to 128 experts per launch (the streamed ring decides; 4 launches here) 392const bool mq = mmq::built ();// (P4-SPLIT: without MMQ the fused times alone) 393const float t_mmq = mq ?time ([& ] {run_mmq (ctx ,mb ,r ,x_dev .as < float > (),src_dev .as < int32_t > (),blob ,rows ,s ); }) :0.0f ; 394const float t_f = time ([& ] {run_fused (fb ,x_dev .as < float > (),T ,E , {0 ,E },blob ,s ); }); 395const float t_f1 = time ([& ] {// one launch per 16 experts, MMQ's group size 396 std::vector < int > cuts ; 397for (int e = 0 ;e <=E ;e += 16 )cuts .push_back (e ); 398run_fused (fb ,x_dev .as < float > (),T ,E ,cuts ,blob ,s ); 399 }); 400const std::vector < float > y_mmq = download (mb .dm , (size_t )rows * N ),y_f = download (fb .dm , (size_t )rows * N ); 401const std::vector < int32_t > slot = download_i (fb .slot , (size_t )rows ); 402const Err efm = compare (y_f , [& ](size_t i ) {return (int64_t )slot [i ]; },y_mmq , 403 [& ](size_t i ) {return (int64_t )r .row_of [i ]; }, (size_t )rows ); 404 std::printf ("timing part: %d tokens x top %d over %d experts (%.1f rows per expert), one layer:\n" ,T ,K ,E , 405 (double )rows /E ); 406 std::printf (" MMQ path (gathers, q8_1, products, SwiGLU, 32 groups): %.3f ms\n" ,t_mmq ); 407 std::printf (" fused path (quantize, group, 4 launches of 128): %.3f ms (%.2fx)\n" ,t_f ,t_mmq /t_f ); 408 std::printf (" fused path, launches of 16 experts: %.3f ms\n" ,t_f1 ); 409 std::printf (" fused vs MMQ: rel RMS %.3e worst row max rel %.3e\n" ,efm .rms ,efm .worst ); 410cudaEventDestroy (a ); 411cudaEventDestroy (b ); 412if (mq && efm .rms > 0.05 )throw std::runtime_error ("the paths disagree at the real shape" ); 413} 414}// namespace 415 416int main (int argc ,char ** argv ) { 417try { 418int n = 0 ; 419if (cudaGetDeviceCount (& n )!= cudaSuccess || n == 0 ) { std::printf ("no CUDA device: skipped\n" );return 77 ; } 420if (!fused::available ()) { std::printf ("the fused kernels need sm_80 or newer: skipped\n" );return 77 ; } 421if (!mmq::built ()) std::printf ("no MMQ in this build: the fused path against the FP32 reference alone\n" ); 422cudaStream_t s = nullptr ; 423ck (cudaStreamCreateWithFlags (& s ,cudaStreamNonBlocking ),"stream" ); 424reference_part (s ); 425if (!(argc > 1 && std::strcmp (argv [1 ],"--no-timing" )== 0 ))timing_part (s ); 426ck (cudaStreamDestroy (s ),"destroy" ); 427 std::printf ("prefill fused MoE parity passed\n" ); 428return 0 ; 429 }catch (const std::exception & e ) { 430 std::fprintf (stderr ,"prefill fused MoE parity failed: %s\n" ,e .what ()); 431return 1 ; 432 } 433}