okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f2b41fd29
main
1// prefill_ws_parity_test - the weight-stationary expert products of PR #3752 (STRATA_MMQ_WS, GP100) against the per-group 2// MMQ they replace, byte for byte, on random experts (GPU, synthetic data, no model). 3// 4// A layer of E resident experts (random gate/up [1280 x 2560] and down [2560 x 640] blocks with sane fp16 scales, laid out 5// as the expert cache holds them: gate rows then up rows, the down matrix at down_off) gets random activations, quantized 6// as the prompt path does (mmq::quantize), and a routing of random row counts per expert (1 .. 300 rows, so u spans the 7// measured range, some experts with one row). The reference is mmq::Context::run per expert (gate/up, then 8// swiglu + quantize, then down), i.e. what Prefill does per 16-expert group; the candidate is ws::gate_up, ONE 9// mmq::swiglu_quant over all rows and ws::down. Compared: GU (floats), Hq (the q8_1 bytes) and Dm (floats) of every row. 10// The down is also run alone on the reference Hq, so a difference points at the product. For the IQ4_NL down the run 11// repeats with STRATA_WS_FAST on (ws::set_fast(1)); the same Dm is required. 12// 13// The kernels were written for GP100 (the integer sums are exact, the float epilogue follows MMQ's sm_60 SASS), so the 14// verdict is only given on a compute capability 6.0 card; on another card the kernels are run too (ws::set_mode(1)) 15// and the counts printed for information, with exit 77. Needs the CUDA build with STRATA_EXPERIMENTAL_SM60. 16// 17// prefill_ws_parity_test [--device N] [--any] exit 0: all identical (cc 6.0); 77: other card; 1: a difference 18#include "strata/prefill/mmq_ids_margin.hpp" 19#include "strata/prefill/moe_mmq.hpp" 20#include "strata/prefill/moe_ws.hpp" 21 22#include "ggml.h" 23 24#include <cuda_runtime.h> 25 26#include <algorithm> 27#include <cmath> 28#include <cstdint> 29#include <cstdio> 30#include <cstdlib> 31#include <cstring> 32#include <numeric> 33#include <random> 34#include <stdexcept> 35#include <string> 36#include <vector> 37 38namespace { 39namespace mmq= strata::prefill::mmq; 40namespace ws= strata::prefill::ws; 41 42void ck (cudaError_t e ,const char * what ) { 43if (e != cudaSuccess )throw std::runtime_error (std::string (what )+ ": " + cudaGetErrorString (e )); 44} 45 46struct Dev { 47void * p = nullptr ; 48size_t n = 0 ; 49explicit Dev (size_t bytes ) :n (bytes ) { 50ck (cudaMalloc (& p ,bytes + 256 ),"cudaMalloc" ); 51ck (cudaMemset (p ,0 ,bytes + 256 ),"cudaMemset" ); 52 } 53 ~Dev () {cudaFree (p ); } 54Dev (const Dev & )= delete ; 55Dev & operator= (const Dev & )= delete ; 56template < class T > T * as ()const {return (T * )p ; } 57template < class T > void up (const std::vector < T >& h ) {ck (cudaMemcpy (p ,h .data (),h .size ()* sizeof (T ),cudaMemcpyHostToDevice ),"upload" ); } 58template < class T > std::vector < T > down (size_t count )const { 59 std::vector < T > h (count ); 60ck (cudaMemcpy (h .data (),p ,count * sizeof (T ),cudaMemcpyDeviceToHost ),"download" ); 61return h ; 62 } 63}; 64 65constexpr int64_t kNEmbd = 2560 ,kNFF = 640 ,kGuRows = 1280 ; 66 67// random blocks of `type` for a [rows x cols] matrix; every block starts with its fp16 scale d: a finite value in 68// [2^-6, 2^-5) (all the formats used here put d first) 69std::vector < uint8_t > random_matrix (ggml_type type ,int64_t rows ,int64_t cols , std::mt19937 & rng ) { 70const size_t bytes = mmq::matrix_bytes ((int )type ,rows ,cols ); 71const size_t bs = ggml_type_size (type ); 72 std::vector < uint8_t > w (bytes ); 73for (auto & b :w )b = (uint8_t )rng (); 74for (size_t o = 0 ;o + bs <=bytes ;o += bs ) { 75const uint16_t d = (uint16_t ) ((9u <<10 ) | (rng ()& 0x3FFu )); 76 std::memcpy (& w [o ],& d ,2 ); 77 } 78return w ; 79} 80 81size_t count_diff (const std::vector < uint8_t >& a ,const std::vector < uint8_t >& b ,size_t n ) { 82size_t d = 0 ; 83for (size_t i = 0 ;i < n ;++ i )d += a [i ]!= b [i ]; 84return d ; 85} 86 87// the largest |a - b| over the largest |a|, both float arrays in byte form (how far apart two results are in rounding terms) 88double max_norm_err (const std::vector < uint8_t >& a ,const std::vector < uint8_t >& b ,size_t bytes ) { 89const float * x = (const float * )a .data (); 90const float * y = (const float * )b .data (); 91double mx = 0.0 ,err = 0.0 ; 92for (size_t i = 0 ;i < bytes /4 ;++ i ) { 93mx = std::max (mx , (double ) std::fabs (x [i ])); 94err = std::max (err , (double ) std::fabs (x [i ]- y [i ])); 95 } 96return mx > 0.0 ?err /mx :err ; 97} 98 99struct Result { 100size_t gu = 0 ,hq = 0 ,dm = 0 ,dm_ref_hq = 0 ,dm_fast = 0 ,fast_vs_default = 0 ; 101double e_gu = 0 ,e_dm = 0 ,e_dm_rh = 0 ;// normalized max errors against the reference 102bool ran = true; 103}; 104 105Result run_case (ggml_type gt ,ggml_type dt ,const std::vector < int32_t >& cnt ,uint32_t seed ,bool test_fast ) { 106 std::mt19937 rng (seed ); 107const int E = (int )cnt .size (); 108 std::vector < int32_t > bounds (E + 1 ,0 ); 109for (int j = 0 ;j < E ;++ j )bounds [j + 1 ]= bounds [j ]+ cnt [j ]; 110const int64_t rows = bounds [E ]; 111const size_t gub = mmq::matrix_bytes ((int )gt ,kGuRows ,kNEmbd ),db = mmq::matrix_bytes ((int )dt ,kNEmbd ,kNFF ); 112const size_t stride = (gub + db + 255 ) /256 * 256 ; 113// the layer's experts, "resident" in one buffer at 256-byte aligned offsets (the expert cache's slots) 114 std::vector < uint8_t > blob ((size_t )E * stride ,0 ); 115 std::vector < int64_t > xoff (E ); 116for (int j = 0 ;j < E ;++ j ) { 117xoff [j ]= (int64_t )j * (int64_t )stride ; 118const auto g = random_matrix (gt ,kGuRows ,kNEmbd ,rng ),d = random_matrix (dt ,kNEmbd ,kNFF ,rng ); 119 std::memcpy (& blob [(size_t )xoff [j ]],g .data (),gub ); 120 std::memcpy (& blob [(size_t )xoff [j ]+ gub ],d .data (),db ); 121 } 122 std::normal_distribution < float > nd (0.0f ,1.0f ); 123 std::vector < float > x ((size_t ) (rows * kNEmbd )); 124for (auto & v :x )v = nd (rng )* 0.7f ; 125 126const size_t xqb = mmq::q8_bytes (rows ,kNEmbd ),hqb = mmq::q8_bytes (rows ,kNFF ); 127Dev dblob (blob .size ()),dx (x .size ()* 4 ),dxq (xqb ),dbnd ((size_t ) (E + 1 )* 4 ),dxoff ((size_t )E * 8 ); 128const size_t ids_rows = (size_t ) mmq::mmq_ids_table_rows ((uint64_t )rows , (uint64_t )rows );// (mul_mat_q reads the row table past its last row: mmq_ids_margin.hpp) 129Dev dident (ids_rows * 4 ),dgu_ref ((size_t )rows * kGuRows * 4 ),dgu ((size_t )rows * kGuRows * 4 ); 130Dev dh ((size_t )rows * kNFF * 4 ),dhq_ref (hqb ),dhq (hqb ),ddm_ref ((size_t )rows * kNEmbd * 4 ),ddm ((size_t )rows * kNEmbd * 4 ), 131ddm_rh ((size_t )rows * kNEmbd * 4 ),ddm_fast ((size_t )rows * kNEmbd * 4 ); 132dblob .up (blob );dx .up (x );dbnd .up (bounds );dxoff .up (xoff ); 133 std::vector < int32_t > ident (ids_rows ); 134for (size_t i = 0 ;i < ids_rows ;++ i )ident [i ]= (int32_t )i ; 135dident .up (ident ); 136 mmq::quantize (dx .as < float > (),nullptr ,dxq .p , (int )gt ,kNEmbd ,kNEmbd ,rows ,nullptr ); 137 138// the reference: per expert, as a one-expert group (absolute rows) 139 mmq::Context ctx ; 140for (int j = 0 ;j < E ;++ j ) { 141 mmq::Product gu ; 142gu .w = dblob .as < uint8_t > ()+ xoff [j ];gu .type = (int )gt ;gu .w_rows = kGuRows ;gu .w_cols = kNEmbd ;gu .expert_bytes = gub ; 143gu .n = 1 ;gu .xq = dxq .p ;gu .bounds = dbnd .as < int32_t > ()+ j ;gu .ids = dident .as < int32_t > (); 144gu .total_rows = rows ;gu .max_rows = cnt [j ];gu .dst = dgu_ref .as < float > ();gu .ld_dst = kGuRows ; 145ctx .run (gu ,nullptr ); 146 } 147 mmq::swiglu (dgu_ref .as < float > (),dh .as < float > (),rows ,kNFF , false,nullptr ); 148 mmq::quantize (dh .as < float > (),nullptr ,dhq_ref .p , (int )dt ,kNFF ,kNFF ,rows ,nullptr ); 149for (int j = 0 ;j < E ;++ j ) { 150 mmq::Product dn ; 151dn .w = dblob .as < uint8_t > ()+ xoff [j ]+ gub ;dn .type = (int )dt ;dn .w_rows = kNEmbd ;dn .w_cols = kNFF ;dn .expert_bytes = db ; 152dn .n = 1 ;dn .xq = dhq_ref .p ;dn .bounds = dbnd .as < int32_t > ()+ j ;dn .ids = dident .as < int32_t > (); 153dn .total_rows = rows ;dn .max_rows = cnt [j ];dn .dst = ddm_ref .as < float > ();dn .ld_dst = kNEmbd ; 154ctx .run (dn ,nullptr ); 155 } 156ck (cudaDeviceSynchronize (),"reference" ); 157 158// the candidate 159 std::vector < int32_t > order (E ); 160for (int j = 0 ;j < E ;++ j )order [j ]= j ; 161 std::vector < ws::Chunk > chunks (ws::max_chunks (rows ,E )); 162const size_t nch = ws::chunks (order .data (), (size_t )E ,cnt .data (),bounds .data (),chunks .data ()); 163chunks .resize (nch ); 164Dev dch (std::max < size_t > (1 ,nch )* sizeof (ws::Chunk )); 165dch .up (chunks ); 166 ws::Layer L ; 167L .gu_type = (int )gt ;L .d_type = (int )dt ;L .w = dblob .p ;L .xoff = dxoff .as < int64_t > ();L .down_off = (int64_t )gub ; 168L .chunks = dch .as < ws::Chunk > ();L .nchunks = (int64_t )nch ;L .rows = rows ;L .n = E ;L .xq = dxq .p ;L .gu = dgu .as < float > (); 169L .hq = dhq .p ;L .dm = ddm .as < float > (); 170Result r ; 171if (!ws::gate_up (L ,nullptr )) {r .ran = false;return r ; } 172 mmq::swiglu_quant (dgu .as < float > (),dhq .p ,rows , false,nullptr ); 173 ws::down (L ,nullptr ); 174ck (cudaDeviceSynchronize (),"candidate" ); 175// the down alone on the reference H (a difference above this one is the gate/up's) 176 ws::Layer L2 = L ; 177L2 .hq = dhq_ref .p ;L2 .dm = ddm_rh .as < float > (); 178 ws::down (L2 ,nullptr ); 179if (test_fast ) { 180 ws::set_fast (1 ); 181 ws::Layer L3 = L ; 182L3 .dm = ddm_fast .as < float > (); 183 ws::down (L3 ,nullptr ); 184 ws::set_fast (-1 ); 185 } 186ck (cudaDeviceSynchronize (),"candidate (down alone, fast)" ); 187 188const size_t gun = (size_t )rows * kGuRows * 4 ,dmn = (size_t )rows * kNEmbd * 4 ; 189const auto gur = dgu_ref .down < uint8_t > (gun ),gun_c = dgu .down < uint8_t > (gun ); 190r .gu = count_diff (gur ,gun_c ,gun ); 191r .e_gu = max_norm_err (gur ,gun_c ,gun ); 192r .hq = count_diff (dhq_ref .down < uint8_t > (hqb ),dhq .down < uint8_t > (hqb ),hqb ); 193const auto dmr = ddm_ref .down < uint8_t > (dmn ); 194const auto dmc = ddm .down < uint8_t > (dmn ),dmh = ddm_rh .down < uint8_t > (dmn ); 195r .dm = count_diff (dmr ,dmc ,dmn ); 196r .dm_ref_hq = count_diff (dmr ,dmh ,dmn ); 197r .e_dm = max_norm_err (dmr ,dmc ,dmn ); 198r .e_dm_rh = max_norm_err (dmr ,dmh ,dmn ); 199if (test_fast ) { 200const auto dmf = ddm_fast .down < uint8_t > (dmn ); 201r .dm_fast = count_diff (dmr ,dmf ,dmn ); 202r .fast_vs_default = count_diff (dmc ,dmf ,dmn );// STRATA_WS_FAST: the same bits as the default kernel, on any card 203 } 204return r ; 205} 206 207std::vector < int32_t > counts (int E ,int lo ,int hi , std::mt19937 & rng ) { 208 std::vector < int32_t > c (E ); 209for (auto & v :c )v = lo + (int32_t ) (rng () % (uint32_t ) (hi - lo + 1 )); 210return c ; 211} 212}// namespace 213 214int main (int argc ,char ** argv ) { 215int device = 0 ; 216bool any = false; 217for (int i = 1 ;i < argc ;++ i ) { 218if (std::strcmp (argv [i ],"--device" )== 0 && i + 1 < argc )device = std::atoi (argv [++ i ]); 219else if (std::strcmp (argv [i ],"--any" )== 0 )any = true; 220else { 221 std::fprintf (stderr ,"usage: prefill_ws_parity_test [--device N] [--any]\n" ); 222return 2 ; 223 } 224 } 225int ndev = 0 ; 226if (cudaGetDeviceCount (& ndev )!= cudaSuccess || ndev == 0 ) { 227 std::puts ("prefill_ws_parity_test: no CUDA device (skipped)" ); 228return 77 ; 229 } 230try { 231ck (cudaSetDevice (device ),"cudaSetDevice" ); 232cudaDeviceProp prop {}; 233ck (cudaGetDeviceProperties (& prop ,device ),"cudaGetDeviceProperties" ); 234const bool gp100 = prop .major == 6 && prop .minor == 0 ; 235 std::printf ("prefill_ws_parity_test on %s (%d.%d)%s\n" ,prop .name ,prop .major ,prop .minor , 236gp100 ?"" :": not a GP100, so the counts are for information only" ); 237if (!gp100 && !any ) { 238 std::puts ("prefill_ws_parity_test: not a compute capability 6.0 card (skipped; --any runs it for information)" ); 239return 77 ; 240 } 241 ws::set_mode (1 ); 242 std::mt19937 rng (20261026u ); 243const ggml_type gus []= {GGML_TYPE_IQ2_XXS ,GGML_TYPE_IQ2_XS ,GGML_TYPE_IQ2_S ,GGML_TYPE_IQ3_XXS ,GGML_TYPE_IQ3_S }; 244const ggml_type dns []= {GGML_TYPE_Q2_0 ,GGML_TYPE_IQ4_NL }; 245size_t total_diff = 0 ,total_fast = 0 ; 246double worst_err = 0.0 ; 247int cases = 0 ,declined = 0 ; 248for (ggml_type gt :gus ) 249for (ggml_type dt :dns ) { 250// a spread of rows per expert (u from ~2 to ~150), and a tiny layer with one-row experts 251const std::vector < std::vector < int32_t >> shapes = {counts (24 ,1 ,12 ,rng ),counts (24 ,5 ,40 ,rng ), 252counts (20 ,60 ,300 ,rng ), {1 ,2 ,65 ,1 ,64 ,63 }}; 253for (const auto & cnt :shapes ) { 254const Result r = run_case (gt ,dt ,cnt ,1000u + (uint32_t )cases ,dt == GGML_TYPE_IQ4_NL ); 255++ cases ; 256if (!r .ran ) {++ declined ; std::printf (" %-8s -> %-6s %zu experts: ws declined (not faster here)\n" ,ggml_type_name (gt ),ggml_type_name (dt ),cnt .size ());continue ; } 257const size_t bad = r .gu + r .hq + r .dm + r .dm_ref_hq + r .dm_fast ; 258total_diff += gp100 ?bad :0 ; 259total_fast += r .fast_vs_default ; 260worst_err = std::max (worst_err , std::max (r .e_gu ,r .e_dm_rh ));// Dm after the full chain also carries int8 flips of H 261 std::printf (" %-8s -> %-6s %2zu experts %5d rows: bytes differ GU %zu Hq %zu Dm %zu Dm(down alone) %zu Dm(fast) %zu" 262" fast vs default %zu | max error / max value: GU %.2e Dm %.2e Dm(down alone) %.2e%s\n" , 263ggml_type_name (gt ),ggml_type_name (dt ),cnt .size (), 264 (int ) std::accumulate (cnt .begin (),cnt .end (),0 ),r .gu ,r .hq ,r .dm ,r .dm_ref_hq ,r .dm_fast , 265r .fast_vs_default ,r .e_gu ,r .e_dm ,r .e_dm_rh ,gp100 && bad ?" <-- FAIL" :"" ); 266 } 267 } 268if (!gp100 ) {// no verdict on this card: the float epilogue of its MMQ is not the one the kernels follow 269 std::printf ("prefill_ws_parity_test (information, %s): %d cases (%d declined), STRATA_WS_FAST vs default: %zu differing bytes, " 270"largest GU / down-alone error against this card's MMQ %.2e of the largest value -> %s\n" ,prop .name ,cases ,declined , 271total_fast ,worst_err ,total_fast == 0 && worst_err < 1e-5 && declined < cases ?"consistent" :"INCONSISTENT" ); 272return total_fast == 0 && worst_err < 1e-5 && declined < cases ?77 :1 ; 273 } 274 std::printf ("prefill_ws_parity_test: %d cases (%d declined), %zu differing bytes, STRATA_WS_FAST vs default %zu -> %s\n" ,cases , 275declined ,total_diff ,total_fast ,total_diff == 0 && total_fast == 0 && declined < cases ?"PASS" :"FAIL" ); 276return total_diff == 0 && total_fast == 0 && declined < cases ?0 :1 ; 277 }catch (const std::exception & e ) { 278 std::fprintf (stderr ,"prefill_ws_parity_test: %s\n" ,e .what ()); 279return 1 ; 280 } 281}