okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ffb3d9b31
main
1// src/kernels/router_top10_parity.cpp - P2.S2's parity test for the MoE router. 2// 3// The reference here is a HOST implementation of `ref/moe.py::router` written from the same specification the 4// kernel was written from - so this checks the kernel against the spec independently of the kernel, which is 5// the strongest thing available without running llama.cpp. It is NOT a check against llama.cpp itself, and 6// that gap is stated rather than implied. 7// 8// WHAT THE TEST CAN AND CANNOT SEE. It compares expert IDs exactly and weights to a tolerance, on several 9// logit distributions including ties (where the "smallest index wins" rule is the only thing that decides) and 10// near-ties (where a float difference decides). It also asserts that the 2**-14 CLAMP CANNOT TRIGGER for this 11// model's geometry - see below - so the absence of a clamp test is a proven fact rather than an omission. 12#define DPCT_PROFILING_ENABLED 13#include <sycl/sycl.hpp> 14#include <dpct/dpct.hpp> 15#include "strata/kernels/router_top10.hpp" 16 17#include <algorithm> 18#include <cmath> 19#include <cstdio> 20#include <cstdlib> 21#include <numeric> 22#include <random> 23#include <vector> 24 25namespace { 26 27void check (dpct::err0 e ,const char * what ) { 28} 29 30constexpr double RENORM_CLAMP = 6.103515625e-05 ;// 2**-14 31 32// The host reference: softmax over all experts, stable descending argsort, gather, clamp, renormalise. 33void reference (const float * logits ,int n_expert ,int k ,int * ids ,float * w ) { 34double mx = logits [0 ]; 35for (int e = 1 ;e < n_expert ;++ e )mx = std::max (mx , (double )logits [e ]); 36double sum = 0 ; 37 std::vector < double > p ((size_t )n_expert ); 38for (int e = 0 ;e < n_expert ;++ e ) { 39p [(size_t )e ]= std::exp ((double )logits [e ]- mx ); 40sum += p [(size_t )e ]; 41 } 42for (int e = 0 ;e < n_expert ;++ e )p [(size_t )e ] /=sum ; 43 44// stable descending: std::stable_sort with a strict greater-than keeps equal elements in index order 45 std::vector < int > idx ((size_t )n_expert ); 46 std::iota (idx .begin (),idx .end (),0 ); 47 std::stable_sort (idx .begin (),idx .end (), 48 [& ](int a ,int b ) {return p [(size_t )a ]> p [(size_t )b ]; }); 49double s = 0 ; 50for (int i = 0 ;i < k ;++ i ) { 51ids [i ]= idx [(size_t )i ]; 52w [i ]= (float )p [(size_t )idx [(size_t )i ]]; 53s += p [(size_t )idx [(size_t )i ]]; 54 } 55s = std::max (s ,RENORM_CLAMP ); 56for (int i = 0 ;i < k ;++ i )w [i ]= (float ) ((double )w [i ] /s ); 57} 58 59int run_case (const char * name ,const std::vector < float >& logits ,int n_tokens ,int n_expert ,int k , 60double tol ) { 61 std::vector < int > h_ids ((size_t )n_tokens * k ); 62 std::vector < float > h_w ((size_t )n_tokens * k ); 63 std::vector < int > r_ids ((size_t )n_tokens * k ); 64 std::vector < float > r_w ((size_t )n_tokens * k ); 65for (int t = 0 ;t < n_tokens ;++ t ) { 66reference (& logits [(size_t )t * n_expert ],n_expert ,k ,& r_ids [(size_t )t * k ],& r_w [(size_t )t * k ]); 67 } 68 69float * d_l = nullptr ; 70int * d_ids = nullptr ; 71float * d_w = nullptr ; 72check (DPCT_CHECK_ERROR (d_l = sycl::malloc_device < float > ( 73logits .size (), dpct::get_in_order_queue ())), 74"malloc logits" ); 75check (DPCT_CHECK_ERROR (d_ids = sycl::malloc_device < int > ( 76h_ids .size (), dpct::get_in_order_queue ())), 77"malloc ids" ); 78check (DPCT_CHECK_ERROR (d_w = sycl::malloc_device < float > ( 79h_w .size (), dpct::get_in_order_queue ())), 80"malloc w" ); 81/* 82DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming 83in the original code the source host memory is pageable memory. If the 84memory is not pageable, call wait() on event return by memcpy API to ensure 85synchronization behavior. 86*/ 87check (DPCT_CHECK_ERROR ((dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()).memcpy ( 88d_l ,logits .data (),logits .size ()* sizeof (float )).wait ()), 89"copy" ); 90 strata::kernels::router_top10 (d_l ,n_tokens ,n_expert ,k ,d_ids ,d_w ,nullptr ); 91check (DPCT_CHECK_ERROR ( 92 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 93 .memcpy (h_ids .data (),d_ids ,h_ids .size ()* sizeof (int )) 94 .wait ()), 95"back ids" ); 96check (DPCT_CHECK_ERROR ( 97 (dpct::get_current_device ().queues_wait_and_throw (), dpct::get_in_order_queue ()) 98 .memcpy (h_w .data (),d_w ,h_w .size ()* sizeof (float )) 99 .wait ()), 100"back w" ); 101 102long long id_bad = 0 ,w_bad = 0 ; 103double worst = 0 ; 104for (size_t i = 0 ;i < h_ids .size ();++ i ) { 105if (h_ids [i ]!= r_ids [i ])++ id_bad ; 106const double rel = std::fabs ((double )h_w [i ]- (double )r_w [i ]) / 107 (std::fabs ((double )r_w [i ])> 1e-30 ? std::fabs ((double )r_w [i ]) :1e-30 ); 108worst = std::max (worst ,rel ); 109if (!(rel <=tol ))++ w_bad ; 110 } 111// every token's weights must sum to 1 unless the clamp replaced the sum 112double worst_sum = 0 ; 113for (int t = 0 ;t < n_tokens ;++ t ) { 114double s = 0 ; 115for (int i = 0 ;i < k ;++ i )s += (double )h_w [(size_t )t * k + i ]; 116double raw = 0 ; 117for (int i = 0 ;i < k ;++ i )raw += (double )r_w [(size_t )t * k + i ]; 118// both sides divide by the same clamped scale, so the ratios agree; check the kernel's own sum 119worst_sum = std::max (worst_sum , std::fabs (s - 1.0 )); 120 } 121 std::printf (" %-26s ids %s (%lld bad) weights worst rel %.3e (%lld over tol) |sum-1| %.1e\n" ,name , 122id_bad ?"*** WRONG ***" :"exact" ,id_bad ,worst ,w_bad ,worst_sum ); 123 sycl::free (d_l , dpct::get_in_order_queue ()); 124 sycl::free (d_ids , dpct::get_in_order_queue ()); 125 sycl::free (d_w , dpct::get_in_order_queue ()); 126return (int ) (id_bad + w_bad ); 127} 128 129// The fp32 router (variant 3, the one a card without fp64 runs) against the double kernel (variant 0) on the SAME inputs: ids that differ 130// and the largest relative weight difference. Needs a device that runs double (a card with fp64, or an Arc under IGC_EnableDPEmulation=1 131// OverrideDefaultFP64Settings=1); without one it says so and is skipped (the reference check above then covers the fp32 path). 132int f32_vs_double (const char * name ,const std::vector < float >& logits ,int n_tokens ,int n_expert ,int k ) { 133auto & q = dpct::get_in_order_queue (); 134if (!q .get_device ().has (sycl::aspect::fp64 )) { 135 std::printf (" %-26s fp32 vs double: skipped (this device runs no double)\n" ,name ); 136return 0 ; 137 } 138float * d_l = sycl::malloc_device < float > (logits .size (),q ); 139int * d_i [2 ]= {sycl::malloc_device < int > ((size_t )n_tokens * k ,q ), sycl::malloc_device < int > ((size_t )n_tokens * k ,q )}; 140float * d_w [2 ]= {sycl::malloc_device < float > ((size_t )n_tokens * k ,q ), sycl::malloc_device < float > ((size_t )n_tokens * k ,q )}; 141q .memcpy (d_l ,logits .data (),logits .size ()* sizeof (float )).wait (); 142 std::vector < int > ids [2 ]; 143 std::vector < float > w [2 ]; 144const int variants [2 ]= {0 ,3 }; 145for (int v = 0 ;v < 2 ;++ v ) { 146if (!strata::kernels::router_top10_variant (d_l ,n_tokens ,n_expert ,k ,d_i [v ],d_w [v ],nullptr ,variants [v ])) { 147 std::printf (" %-26s fp32 vs double: variant %d not available\n" ,name ,variants [v ]); 148return 1 ; 149 } 150q .wait (); 151ids [v ].resize ((size_t )n_tokens * k ); 152w [v ].resize ((size_t )n_tokens * k ); 153q .memcpy (ids [v ].data (),d_i [v ],ids [v ].size ()* sizeof (int )).wait (); 154q .memcpy (w [v ].data (),d_w [v ],w [v ].size ()* sizeof (float )).wait (); 155 } 156long long id_diff = 0 ; 157double worst = 0 ,worst_abs = 0 ; 158for (size_t i = 0 ;i < ids [0 ].size ();++ i ) { 159if (ids [0 ][i ]!= ids [1 ][i ]) {++ id_diff ;continue ; } 160const double a = w [0 ][i ],b = w [1 ][i ]; 161worst_abs = std::max (worst_abs , std::fabs (a - b )); 162worst = std::max (worst , std::fabs (a - b ) / (std::fabs (a )> 1e-30 ? std::fabs (a ) :1e-30 )); 163 } 164 std::printf (" %-26s fp32 vs double: ids differ %lld of %zu weights max rel %.3e max abs %.3e\n" ,name ,id_diff ,ids [0 ].size (),worst ,worst_abs ); 165 sycl::free (d_l ,q ); 166for (int v = 0 ;v < 2 ;++ v ) { sycl::free (d_i [v ],q ); sycl::free (d_w [v ],q ); } 167return id_diff ?1 :0 ; 168} 169 170}// namespace 171 172int main (int argc ,char ** argv ) { 173bool selftest = false; 174for (int i = 1 ;i < argc ;++ i ) { 175if (std::string (argv [i ])== "--selftest" )selftest = true; 176else { std::fprintf (stderr ,"usage: router_top10_parity [--selftest]\n" );return 2 ; } 177 } 178 179const int NE = 512 ;// the real n_expert 180const int K = 10 ;// the real top-k 181const int NT = 64 ; 182 std::mt19937 rng (2024 ); 183 std::normal_distribution < float > gauss (0.0f ,1.0f ); 184int bad = 0 ; 185 186// ---- random logits 187 std::vector < float > a ((size_t )NT * NE ); 188for (auto & v :a )v = gauss (rng ); 189bad += run_case ("random normal" ,a ,NT ,NE ,K ,1e-5 ); 190 191// ---- ALL-EQUAL logits: every expert ties, so the "smallest index wins" rule is the ONLY thing deciding 192// the ids. An unstable sort or a >= comparison in the maximum scan fails this and passes everything else. 193 std::vector < float > b ((size_t )NT * NE ,0.5f ); 194bad += run_case ("all equal (ties)" ,b ,NT ,NE ,K ,1e-5 ); 195 196// ---- a few exact ties among otherwise distinct values 197 std::vector < float > c ((size_t )NT * NE ); 198for (int t = 0 ;t < NT ;++ t ) { 199for (int e = 0 ;e < NE ;++ e )c [(size_t )t * NE + e ]= (e < 12 ) ?2.0f :gauss (rng ); 200 } 201bad += run_case ("12-way exact tie" ,c ,NT ,NE ,K ,1e-5 ); 202 203// ---- one dominant expert: the top-1 must be that expert and its weight must dominate 204 std::vector < float > d ((size_t )NT * NE ,0.0f ); 205for (int t = 0 ;t < NT ;++ t )d [(size_t )t * NE + (t %NE )]= 20.0f ; 206bad += run_case ("dominant expert" ,d ,NT ,NE ,K ,1e-5 ); 207 208// ---- THE CLAMP CANNOT TRIGGER, and that is provable rather than untested. 209// The sum of the top k of a probability vector over n outcomes is at least k/n (the minimum is the uniform 210// distribution). Here k/n = 10/512 = 0.01953125, which is 320x the 2**-14 = 6.1035e-05 clamp, so no input 211// whatsoever can make this model's renormalisation clamp - not an extreme one, not an adversarial one. 212// Asserting the bound is worth more than a test that cannot reach it. 213const double min_possible = (double )K / (double )NE ; 214 std::printf (" %-26s top-%d sum >= k/n = %.5f, clamp is %.3e -> margin %.0fx %s\n" ,"clamp reachability" , 215K ,min_possible ,RENORM_CLAMP ,min_possible /RENORM_CLAMP , 216min_possible > RENORM_CLAMP ?"(CLAMP IS UNREACHABLE, asserted)" :"*** REACHABLE ***" ); 217if (min_possible <=RENORM_CLAMP ) { 218 std::fprintf (stderr ,"the clamp CAN trigger, so it needs a test\n" ); 219++ bad ; 220 } 221 222 std::printf ("\nrouter_top10: %d failures over 4 distributions x %d tokens x %d experts, top-%d\n" ,bad ,NT ,NE , 223K ); 224 225// ---- the Qwen4 shapes (Q4-READY): 256 experts top-8 (q4_lite), 512 top-8, 256 top-10, and the fp32 router against the double one 226// on the same inputs at each (variant 3 vs variant 0; skipped on a device that runs no double) 227const int shapes [][2 ]= {{256 ,8 }, {512 ,8 }, {256 ,10 }, {512 ,10 }}; 228for (const auto & sh :shapes ) { 229const int ne = sh [0 ],kk = sh [1 ]; 230char label [64 ]; 231 std::vector < float > r ((size_t )NT * ne ); 232for (auto & v :r )v = gauss (rng ); 233 std::snprintf (label ,sizeof label ,"random %dx top-%d" ,ne ,kk ); 234bad += run_case (label ,r ,NT ,ne ,kk ,1e-5 ); 235bad += f32_vs_double (label ,r ,NT ,ne ,kk ); 236 std::vector < float > tie ((size_t )NT * ne ); 237for (int t = 0 ;t < NT ;++ t ) 238for (int e = 0 ;e < ne ;++ e )tie [(size_t )t * ne + e ]= (e < 12 ) ?2.0f :gauss (rng ); 239 std::snprintf (label ,sizeof label ,"12-way tie %dx top-%d" ,ne ,kk ); 240bad += run_case (label ,tie ,NT ,ne ,kk ,1e-5 ); 241bad += f32_vs_double (label ,tie ,NT ,ne ,kk ); 242 std::vector < float > wide ((size_t )NT * ne ); 243for (auto & v :wide )v = 6.0f * gauss (rng );// a peaked router (large logit spread) 244 std::snprintf (label ,sizeof label ,"wide %dx top-%d" ,ne ,kk ); 245bad += run_case (label ,wide ,NT ,ne ,kk ,1e-5 ); 246bad += f32_vs_double (label ,wide ,NT ,ne ,kk ); 247 } 248 std::printf ("router_top10 (with the Qwen4 shapes): %d failures\n" ,bad ); 249if (bad )return 1 ; 250if (selftest ) std::printf ("router_top10_parity OK\n" ); 251return 0 ; 252}