okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f2b41fd29
main
1// prefill_mmq_v31_test - the prompt path's MMQ products for the expert formats of the Unsloth v3.1 Qwen3.8-Flash-Next 2// sets (UD-IQ1_M .. UD-IQ4_XS): gate/up IQ2_XXS / IQ2_XS / IQ2_S / IQ3_XXS / IQ4_XS at 1280 x 2560 and down Q2_0 / 3// IQ4_NL / Q8_0 / Q5_0 at 2560 x 640, on synthetic weights quantized by ggml, against a double-precision product of ggml's 4// dequantized weights. MMQ rounds the activations to q8_1 by design, so this is a screen for layout, stride, 5// expert-bound and row-id errors, not a bit-exactness test (the bounds are those of prefill_mmq_kquant_test). 6// 7// Q5_0 has an MMQ instance only in a build with STRATA_ORCA_Q4KS_MMQ=ON (#296): without it the Q5_0 down product is 8// reported as "not in this build" (the prompt path then dequantizes to FP16 and runs cuBLAS) and does not fail. 9// 10// prefill_mmq_v31_test [--require-q5_0] --require-q5_0: a build without the Q5_0 instance fails 11// prefill_mmq_v31_test --bench [--reps N] Q5_0 down: MMQ against the dequantize-to-FP16 + cuBLAS route 12// (what a build without the instance runs), per expert-group size 13#include "strata/kernels/dequant_bf16.hpp" 14#include "strata/prefill/mmq_ids_margin.hpp" 15#include "strata/prefill/moe_mmq.hpp" 16 17#include "ggml.h" 18 19#include <cublas_v2.h> 20#include <cuda_fp16.h> 21#include <cuda_runtime.h> 22 23#include <algorithm> 24#include <chrono> 25#include <cmath> 26#include <cstdint> 27#include <cstdio> 28#include <cstdlib> 29#include <cstring> 30#include <numeric> 31#include <stdexcept> 32#include <string> 33#include <vector> 34 35namespace { 36namespace mmq= strata::prefill::mmq; 37 38void ck (cudaError_t e ,const char * what ) { 39if (e != cudaSuccess )throw std::runtime_error (std::string (what )+ ": " + cudaGetErrorString (e )); 40} 41 42struct Dev { 43void * p = nullptr ; 44explicit Dev (size_t n ) {ck (cudaMalloc (& p ,n ),"cudaMalloc" ); } 45 ~Dev () {cudaFree (p ); } 46Dev (const Dev & )= delete ; 47Dev & operator= (const Dev & )= delete ; 48}; 49 50std::vector < uint8_t > make_matrix (ggml_type t ,int64_t rows ,int64_t cols ,int expert ,int trial ) { 51 std::vector < float > w ((size_t ) (rows * cols )); 52for (int64_t r = 0 ;r < rows ;++ r ) 53for (int64_t k = 0 ;k < cols ;++ k ) { 54const int code = (int ) ((k * 37 + r * 19 + expert * 23 + trial * 11 ) %101 )- 50 ; 55w [(size_t ) (r * cols + k )]= 0.025f * std::sin (0.013f * (float ) (k + 1 )+ 0.17f * (float )r + 0.31f * (float )expert )+ 560.0015f * (float )code ; 57 } 58 std::vector < uint8_t > out ((size_t )rows * ggml_row_size (t ,cols )); 59const std::vector < float > imatrix ((size_t )cols ,1.0f ); 60ggml_quantize_chunk (t ,w .data (),out .data (),0 ,rows ,cols ,ggml_quantize_requires_imatrix (t ) ?imatrix .data () :nullptr ); 61return out ; 62} 63 64std::vector < float > make_x (int rows ,int64_t cols ,int trial ) { 65 std::vector < float > x ((size_t )rows * (size_t )cols ); 66for (int r = 0 ;r < rows ;++ r ) 67for (int64_t k = 0 ;k < cols ;++ k ) 68x [(size_t )r * (size_t )cols + (size_t )k ]= 690.45f * std::sin (0.009f * (float ) (k + 1 )+ 0.23f * (float )r + 0.07f * (float )trial )+ 700.17f * std::cos (0.021f * (float ) (k + 3 )- 0.19f * (float )r )+ 710.002f * (float ) (((k * 7 + r * 13 + trial * 5 ) %19 )- 9 ); 72 std::fill (x .end ()- cols ,x .end (),0.0f );// an all-zero row: exactly zero out 73return x ; 74} 75 76std::vector < int32_t > perm (int n ,int shift ,bool reverse ) { 77 std::vector < int32_t > p ((size_t )n ); 78for (int i = 0 ;i < n ;++ i )p [(size_t )i ]= (int32_t ) (((reverse ?n - 1 - i :i )+ shift ) %n ); 79return p ; 80} 81 82// one grouped product: experts side by side at one stride (a zeroed tail after them, as prefill.cpp stages them) 83void product (mmq::Context & ctx ,cudaStream_t s ,const char * name ,ggml_type t ,int64_t out_rows ,int64_t cols , 84const std::vector < int >& counts ,int trial ) { 85const int n = (int )counts .size (),rows = std::accumulate (counts .begin (),counts .end (),0 ); 86 std::vector < int32_t > bounds ((size_t )n + 1 ,0 ); 87for (int e = 0 ;e < n ;++ e )bounds [(size_t )e + 1 ]= bounds [(size_t )e ]+ counts [(size_t )e ]; 88const auto src = perm (rows ,trial + 1 , false),dst = perm (rows ,trial + 2 , true); 89const std::vector < float > x = make_x (rows ,cols ,trial ); 90const size_t eb = mmq::matrix_bytes ((int )t ,out_rows ,cols ); 91if (eb != (size_t )out_rows * ggml_row_size (t ,cols ))throw std::runtime_error (std::string (name )+ ": matrix_bytes" ); 92 std::vector < std::vector < uint8_t >> ws ; 93 std::vector < uint8_t > w ((size_t )n * eb + 4096 ,0 ); 94for (int e = 0 ;e < n ;++ e ) { 95ws .push_back (make_matrix (t ,out_rows ,cols ,e ,trial )); 96 std::copy (ws .back ().begin (),ws .back ().end (),w .begin ()+ (ptrdiff_t ) ((size_t )e * eb )); 97 } 98// 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) 99// from an expert's first row (mmq_ids_margin.hpp): the table has the margin, its extra entries hold row index 0 (valid; they are read, never used) 100const size_t ids_rows = (size_t ) mmq::mmq_ids_table_rows ((uint64_t )rows , (uint64_t )* std::max_element (counts .begin (),counts .end ())); 101 std::vector < int32_t > dst_table (dst ); 102dst_table .resize (ids_rows ,0 ); 103Dev dx (x .size ()* 4 ),dsrc ((size_t )rows * 4 ),ddst (ids_rows * 4 ),db (bounds .size ()* 4 ),dw (w .size ()), 104dxq (mmq::q8_bytes (rows ,cols )),dy ((size_t )rows * (size_t )out_rows * 4 ); 105ck (cudaMemcpy (dx .p ,x .data (),x .size ()* 4 ,cudaMemcpyHostToDevice ),"x" ); 106ck (cudaMemcpy (dsrc .p ,src .data (),src .size ()* 4 ,cudaMemcpyHostToDevice ),"src" ); 107ck (cudaMemcpy (ddst .p ,dst_table .data (),dst_table .size ()* 4 ,cudaMemcpyHostToDevice ),"dst" ); 108ck (cudaMemcpy (db .p ,bounds .data (),bounds .size ()* 4 ,cudaMemcpyHostToDevice ),"bounds" ); 109ck (cudaMemcpy (dw .p ,w .data (),w .size (),cudaMemcpyHostToDevice ),"w" ); 110ck (cudaMemset (dy .p ,0xff , (size_t )rows * (size_t )out_rows * 4 ),"sentinel" ); 111ck (cudaDeviceSynchronize (),"inputs" ); 112 mmq::quantize ((const float * )dx .p , (const int32_t * )dsrc .p ,dxq .p , (int )t ,cols ,cols ,rows ,s ); 113 mmq::Product p ; 114p .w = dw .p ;p .type = (int )t ;p .w_rows = out_rows ;p .w_cols = cols ;p .expert_bytes = eb ;p .n = n ; 115p .xq = dxq .p ;p .bounds = (const int32_t * )db .p ;p .ids = (const int32_t * )ddst .p ;p .total_rows = rows ; 116p .max_rows = * std::max_element (counts .begin (),counts .end ());p .dst = (float * )dy .p ;p .ld_dst = out_rows ; 117ctx .run (p ,s ); 118ck (cudaGetLastError (),"launch" ); 119ck (cudaStreamSynchronize (s ),"sync" ); 120 std::vector < float > got ((size_t )rows * (size_t )out_rows ); 121ck (cudaMemcpy (got .data (),dy .p ,got .size ()* 4 ,cudaMemcpyDeviceToHost ),"y" ); 122 123const auto * tr = ggml_get_type_traits (t ); 124 std::vector < float > ref (got .size (),0.0f ),wd ((size_t )out_rows * (size_t )cols ); 125for (int e = 0 ;e < n ;++ e ) { 126const size_t rb = ggml_row_size (t ,cols ); 127for (int64_t o = 0 ;o < out_rows ;++ o ) 128tr -> to_float (ws [(size_t )e ].data ()+ (size_t )o * rb ,wd .data ()+ (size_t )o * (size_t )cols ,cols ); 129for (int r = bounds [(size_t )e ];r < bounds [(size_t )e + 1 ];++ r ) { 130const float * xr = x .data ()+ (size_t )src [(size_t )r ]* (size_t )cols ; 131for (int64_t o = 0 ;o < out_rows ;++ o ) { 132double acc = 0 ; 133const float * wr = wd .data ()+ (size_t )o * (size_t )cols ; 134for (int64_t k = 0 ;k < cols ;++ k )acc += (double )wr [k ]* xr [k ]; 135ref [(size_t )dst [(size_t )r ]* (size_t )out_rows + (size_t )o ]= (float )acc ; 136 } 137 } 138 } 139double err2 = 0 ,ref2 = 0 ,max_abs = 0 ,zero_max = 0 ; 140for (size_t i = 0 ;i < got .size ();++ i ) { 141if (!std::isfinite (got [i ]))throw std::runtime_error (std::string (name )+ ": unwritten or non-finite output" ); 142const double d = (double )got [i ]- ref [i ]; 143err2 += d * d ;ref2 += (double )ref [i ]* ref [i ];max_abs = std::max (max_abs , std::fabs (d )); 144 } 145for (int r = 0 ;r < rows ;++ r ) 146if (src [(size_t )r ]== rows - 1 )// the zero row 147for (int64_t o = 0 ;o < out_rows ;++ o ) 148zero_max = std::max (zero_max , (double ) std::fabs (got [(size_t )dst [(size_t )r ]* (size_t )out_rows + (size_t )o ])); 149const double rms = std::sqrt (ref2 / (double )ref .size ()),rel = std::sqrt (err2 / (double )ref .size ()) /rms ; 150 std::printf ("%-22s rows %2d experts %d ref_rms %.4g rel_l2 %.5f max/rms %.4f zero row %.3g\n" ,name ,rows ,n ,rms , 151rel ,max_abs /rms ,zero_max ); 152if (rel > 0.04 || max_abs /rms > 0.35 || zero_max > std::max (1e-5 ,1e-4 * rms )) 153throw std::runtime_error (std::string (name )+ ": outside the screen" ); 154} 155 156// ---- --bench: Q5_0 down, MMQ against dequantize-to-FP16 + cuBLAS, per expert group ------------------------------- 157double median (std::vector < double > v ) { 158 std::sort (v .begin (),v .end ()); 159return v [v .size () /2 ]; 160} 161 162template < class F > 163double time_ms (F fn ,cudaStream_t s ,int reps ,int rounds ) { 164cudaEvent_t e0 ,e1 ; 165cudaEventCreate (& e0 ); 166cudaEventCreate (& e1 ); 167 std::vector < double > r ; 168for (int k = 0 ;k < rounds ;++ k ) { 169cudaEventRecord (e0 ,s ); 170for (int i = 0 ;i < reps ;++ i )fn (); 171cudaEventRecord (e1 ,s ); 172cudaEventSynchronize (e1 ); 173float ms = 0 ; 174cudaEventElapsedTime (& ms ,e0 ,e1 ); 175r .push_back (ms /reps ); 176 } 177cudaEventDestroy (e0 ); 178cudaEventDestroy (e1 ); 179return median (r ); 180} 181 182void bench (ggml_type t ,int reps ) { 183cudaStream_t s = nullptr ; 184ck (cudaStreamCreateWithFlags (& s ,cudaStreamNonBlocking ),"stream" ); 185cublasHandle_t h ; 186if (cublasCreate (& h )!= CUBLAS_STATUS_SUCCESS )throw std::runtime_error ("cublasCreate" ); 187cublasSetStream (h ,s ); 188cublasSetMathMode (h ,CUBLAS_DEFAULT_MATH ); 189const bool have_mmq = mmq::supported ((int )t ); 190constexpr int64_t N = 2560 ,FF = 640 ; 191constexpr int NE = 16 ;// experts a group holds (kGatherGroupMax) 192 std::printf ("bench %s down [%lld x %lld], %d experts a group, median of 5 rounds x %d calls\n" ,ggml_type_name (t ), 193 (long long )N , (long long )FF ,NE ,reps ); 194 std::printf ("%-8s %12s %12s %12s %8s\n" ,"rows/exp" ,"MMQ ms" ,"f16+cuBLAS ms" ,"(dequant ms)" ,"ratio" ); 195const size_t eb = (size_t )N * ggml_row_size (t ,FF ); 196 std::vector < uint8_t > w ((size_t )NE * eb + 4096 ,0 ); 197for (int e = 0 ;e < NE ;++ e ) { 198auto m = make_matrix (t ,N ,FF ,e ,1 ); 199 std::copy (m .begin (),m .end (),w .begin ()+ (ptrdiff_t ) ((size_t )e * eb )); 200 } 201Dev dw (w .size ()); 202ck (cudaMemcpy (dw .p ,w .data (),w .size (),cudaMemcpyHostToDevice ),"w" ); 203 mmq::Context ctx ; 204for (int per : {16 ,64 ,256 ,1024 }) { 205const int rows = per * NE ; 206const std::vector < float > x = make_x (rows ,FF ,3 ); 207const size_t ids_rows = (size_t ) mmq::mmq_ids_table_rows ((uint64_t )rows , (uint64_t )per );// (the identity over the whole table: mmq_ids_margin.hpp) 208 std::vector < int32_t > bounds ((size_t )NE + 1 ),iota (ids_rows ); 209for (int e = 0 ;e <=NE ;++ e )bounds [(size_t )e ]= e * per ; 210 std::iota (iota .begin (),iota .end (),0 ); 211Dev dx (x .size ()* 4 ),db (bounds .size ()* 4 ),di (iota .size ()* 4 ),dxq (mmq::q8_bytes (rows ,FF )), 212dy ((size_t )rows * N * 4 ),dwh ((size_t )N * FF * 2 ),dxh ((size_t )rows * FF * 2 ); 213ck (cudaMemcpy (dx .p ,x .data (),x .size ()* 4 ,cudaMemcpyHostToDevice ),"x" ); 214ck (cudaMemcpy (db .p ,bounds .data (),bounds .size ()* 4 ,cudaMemcpyHostToDevice ),"b" ); 215ck (cudaMemcpy (di .p ,iota .data (),iota .size ()* 4 ,cudaMemcpyHostToDevice ),"i" ); 216 std::vector < __half > xh (x .size ()); 217for (size_t i = 0 ;i < x .size ();++ i )xh [i ]= __float2half (x [i ]); 218ck (cudaMemcpy (dxh .p ,xh .data (),xh .size ()* 2 ,cudaMemcpyHostToDevice ),"xh" ); 219ck (cudaDeviceSynchronize (),"setup" ); 220double t_mmq = -1 ; 221if (have_mmq ) { 222 mmq::Product p ; 223p .w = dw .p ;p .type = (int )t ;p .w_rows = N ;p .w_cols = FF ;p .expert_bytes = eb ;p .n = NE ; 224p .xq = dxq .p ;p .bounds = (const int32_t * )db .p ;p .ids = (const int32_t * )di .p ;p .total_rows = rows ; 225p .max_rows = per ;p .dst = (float * )dy .p ;p .ld_dst = N ; 226t_mmq = time_ms ([& ] { 227 mmq::quantize ((const float * )dx .p ,nullptr ,dxq .p , (int )t ,FF ,FF ,rows ,s ); 228ctx .run (p ,s ); 229 },s ,reps ,5 ); 230 } 231const float one = 1.f ,zero = 0.f ; 232// the non-MMQ route: per expert, dequantize its matrix to FP16 and one HGEMM over its rows (what prefill.cpp does 233// for a type without an instance); the dequantize alone is timed too 234const double t_deq = time_ms ([& ] { 235for (int e = 0 ;e < NE ;++ e ) 236 strata::kernels::dequant_f16 ((int )t , (const uint8_t * )dw .p + (size_t )e * eb ,0 ,N ,FF , (uint16_t * )dwh .p ,s ); 237 },s ,reps ,5 ); 238const double t_f16 = time_ms ([& ] { 239for (int e = 0 ;e < NE ;++ e ) { 240 strata::kernels::dequant_f16 ((int )t , (const uint8_t * )dw .p + (size_t )e * eb ,0 ,N ,FF , (uint16_t * )dwh .p ,s ); 241cublasGemmEx (h ,CUBLAS_OP_T ,CUBLAS_OP_N , (int )N ,per , (int )FF ,& one ,dwh .p ,CUDA_R_16F , (int )FF , 242 (const __half * )dxh .p + (size_t )e * per * FF ,CUDA_R_16F , (int )FF ,& zero , 243 (float * )dy .p + (size_t )e * per * N ,CUDA_R_32F , (int )N ,CUBLAS_COMPUTE_32F ,CUBLAS_GEMM_DEFAULT ); 244 } 245 },s ,reps ,5 ); 246if (have_mmq ) std::printf ("%-8d %12.4f %12.4f %12.4f %7.2fx\n" ,per ,t_mmq ,t_f16 ,t_deq ,t_f16 /t_mmq ); 247else std::printf ("%-8d %12s %12.4f %12.4f %8s\n" ,per ,"(no instance)" ,t_f16 ,t_deq ,"-" ); 248 } 249cublasDestroy (h ); 250ck (cudaStreamDestroy (s ),"destroy" ); 251} 252}// namespace 253 254int main (int argc ,char ** argv ) { 255try { 256bool bench_mode = false,require_q5 = false; 257int reps = 20 ; 258for (int i = 1 ;i < argc ;++ i ) { 259if (!std::strcmp (argv [i ],"--bench" ))bench_mode = true; 260else if (!std::strcmp (argv [i ],"--require-q5_0" ))require_q5 = true; 261else if (!std::strcmp (argv [i ],"--reps" )&& i + 1 < argc )reps = std::atoi (argv [++ i ]); 262 } 263if (!mmq::built ()) { std::printf ("no MMQ in this build\n" );return 1 ; } 264int nd = 0 ; 265if (cudaGetDeviceCount (& nd )!= cudaSuccess || nd == 0 ) { std::printf ("no CUDA device\n" );return 77 ; } 266if (bench_mode ) { 267bench (GGML_TYPE_Q5_0 ,reps ); 268return 0 ; 269 } 270cudaStream_t s = nullptr ; 271ck (cudaStreamCreateWithFlags (& s ,cudaStreamNonBlocking ),"stream" ); 272int skipped = 0 ; 273 { 274 mmq::Context ctx ; 275const std::vector < std::vector < int >> batches {{1 ,3 ,3 }, {4 ,1 ,2 }, {2 ,3 }, {17 }}; 276struct Case {const char * name ;ggml_type t ;int64_t out_rows ,cols ;int salt ; }; 277const Case cases []= { 278 {"IQ2_XXS gate/up" ,GGML_TYPE_IQ2_XXS ,1280 ,2560 ,0 }, {"IQ2_XS gate/up" ,GGML_TYPE_IQ2_XS ,1280 ,2560 ,3 }, 279 {"IQ2_S gate/up" ,GGML_TYPE_IQ2_S ,1280 ,2560 ,5 }, {"IQ3_XXS gate/up" ,GGML_TYPE_IQ3_XXS ,1280 ,2560 ,7 }, 280 {"IQ4_XS gate/up" ,GGML_TYPE_IQ4_XS ,1280 ,2560 ,11 }, {"Q2_0 down" ,GGML_TYPE_Q2_0 ,2560 ,640 ,13 }, 281 {"IQ4_NL down" ,GGML_TYPE_IQ4_NL ,2560 ,640 ,17 }, {"Q8_0 down" ,GGML_TYPE_Q8_0 ,2560 ,640 ,19 }, 282 {"Q5_0 down" ,GGML_TYPE_Q5_0 ,2560 ,640 ,23 }, 283 }; 284int trial = 0 ; 285for (const auto & counts :batches ) { 286const std::string tag = "-" + std::to_string (trial ); 287for (const Case & c :cases ) { 288if (!mmq::supported ((int )c .t )) { 289if (trial == 0 ) { 290 std::printf ("%-22s not in this build (the prompt path dequantizes to FP16)\n" ,c .name ); 291if (c .t == GGML_TYPE_Q5_0 ) {++ skipped ;if (require_q5 )throw std::runtime_error ("Q5_0 MMQ required" ); } 292else throw std::runtime_error (std::string (c .name )+ ": MMQ must cover this format" ); 293 } 294continue ; 295 } 296product (ctx ,s , (std::string (c .name )+ tag ).c_str (),c .t ,c .out_rows ,c .cols ,counts ,trial + c .salt ); 297 } 298++ trial ; 299 } 300 } 301ck (cudaStreamDestroy (s ),"destroy" ); 302 std::printf ("prefill MMQ v3.1 screen passed%s\n" ,skipped ?" (Q5_0 not built)" :"" ); 303return 0 ; 304 }catch (const std::exception & e ) { 305 std::fprintf (stderr ,"prefill MMQ v3.1 screen failed: %s\n" ,e .what ()); 306return 1 ; 307 } 308}