okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f2b41fd29
main
1// prefill_mmq_kquant_test - the prompt path's MMQ products for the expert formats of Unsloth's UD-Q4_K_XL and 2// UD-Q6_K_XL (gate/up Q4_K / Q5_K / Q6_K at 1280 x 2560, down Q5_1 and Q8_0 at 2560 x 640), on synthetic weights 3// quantized by ggml's own 4// reference quantizers, against a double-precision product of ggml's dequantized weights. MMQ rounds the activations 5// to q8_1 by design, so this is a screen for layout, stride, expert-bound and row-id errors (the bounds of 6// tests/hip/prefill_mmq_parity.cpp), not a bit-exactness test. Several experts per product, permuted rows, an 7// all-zero row. The MMQ path covers gate/up Q4_K / Q5_K / Q6_K and down Q5_1 / Q8_0 (UD-Q4_K_XL / UD-Q6_K_XL). 8#include "strata/prefill/mmq_ids_margin.hpp" 9#include "strata/prefill/moe_mmq.hpp" 10 11#include "ggml.h" 12 13#include <cuda_runtime.h> 14 15#include <algorithm> 16#include <cmath> 17#include <cstdint> 18#include <cstdio> 19#include <numeric> 20#include <stdexcept> 21#include <string> 22#include <vector> 23 24namespace { 25namespace mmq= strata::prefill::mmq; 26 27void ck (cudaError_t e ,const char * what ) { 28if (e != cudaSuccess )throw std::runtime_error (std::string (what )+ ": " + cudaGetErrorString (e )); 29} 30 31struct Dev { 32void * p = nullptr ; 33explicit Dev (size_t n ) {ck (cudaMalloc (& p ,n ),"cudaMalloc" ); } 34 ~Dev () {cudaFree (p ); } 35Dev (const Dev & )= delete ; 36Dev & operator= (const Dev & )= delete ; 37}; 38 39std::vector < uint8_t > make_matrix (ggml_type t ,int64_t rows ,int64_t cols ,int expert ,int trial ) { 40const auto * tr = ggml_get_type_traits (t ); 41if (tr == nullptr || tr -> from_float_ref == nullptr )throw std::runtime_error ("no reference quantizer" ); 42const size_t rb = ggml_row_size (t ,cols ); 43 std::vector < uint8_t > out ((size_t )rows * rb ); 44 std::vector < float > row ((size_t )cols ); 45for (int64_t r = 0 ;r < rows ;++ r ) { 46for (int64_t k = 0 ;k < cols ;++ k ) { 47const int code = (int ) ((k * 37 + r * 19 + expert * 23 + trial * 11 ) %101 )- 50 ; 48row [(size_t )k ]= 0.025f * std::sin (0.013f * (float ) (k + 1 )+ 0.17f * (float )r + 0.31f * (float )expert )+ 490.0015f * (float )code ; 50 } 51tr -> from_float_ref (row .data (),out .data ()+ (size_t )r * rb ,cols ); 52 } 53return out ; 54} 55 56std::vector < float > make_x (int rows ,int64_t cols ,int trial ) { 57 std::vector < float > x ((size_t )rows * (size_t )cols ); 58for (int r = 0 ;r < rows ;++ r ) 59for (int64_t k = 0 ;k < cols ;++ k ) 60x [(size_t )r * (size_t )cols + (size_t )k ]= 610.45f * std::sin (0.009f * (float ) (k + 1 )+ 0.23f * (float )r + 0.07f * (float )trial )+ 620.17f * std::cos (0.021f * (float ) (k + 3 )- 0.19f * (float )r )+ 630.002f * (float ) (((k * 7 + r * 13 + trial * 5 ) %19 )- 9 ); 64 std::fill (x .end ()- cols ,x .end (),0.0f );// an all-zero row: exactly zero out 65return x ; 66} 67 68std::vector < int32_t > perm (int n ,int shift ,bool reverse ) { 69 std::vector < int32_t > p ((size_t )n ); 70for (int i = 0 ;i < n ;++ i )p [(size_t )i ]= (int32_t ) (((reverse ?n - 1 - i :i )+ shift ) %n ); 71return p ; 72} 73 74// one grouped product: experts side by side at one stride (a zeroed tail after them, as prefill.cpp stages them) 75void product (mmq::Context & ctx ,cudaStream_t s ,const char * name ,ggml_type t ,int64_t out_rows ,int64_t cols , 76const std::vector < int >& counts ,int trial ) { 77if (!mmq::supported ((int )t ))throw std::runtime_error (std::string (name )+ ": not covered by this build" ); 78const int n = (int )counts .size (),rows = std::accumulate (counts .begin (),counts .end (),0 ); 79 std::vector < int32_t > bounds ((size_t )n + 1 ,0 ); 80for (int e = 0 ;e < n ;++ e )bounds [(size_t )e + 1 ]= bounds [(size_t )e ]+ counts [(size_t )e ]; 81const auto src = perm (rows ,trial + 1 , false),dst = perm (rows ,trial + 2 , true); 82const std::vector < float > x = make_x (rows ,cols ,trial ); 83const size_t eb = mmq::matrix_bytes ((int )t ,out_rows ,cols ); 84if (eb != (size_t )out_rows * ggml_row_size (t ,cols ))throw std::runtime_error (std::string (name )+ ": matrix_bytes" ); 85 std::vector < std::vector < uint8_t >> ws ; 86 std::vector < uint8_t > w ((size_t )n * eb + 4096 ,0 ); 87for (int e = 0 ;e < n ;++ e ) { 88ws .push_back (make_matrix (t ,out_rows ,cols ,e ,trial )); 89 std::copy (ws .back ().begin (),ws .back ().end (),w .begin ()+ (ptrdiff_t ) ((size_t )e * eb )); 90 } 91// 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) 92// 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) 93const size_t ids_rows = (size_t ) mmq::mmq_ids_table_rows ((uint64_t )rows , (uint64_t )* std::max_element (counts .begin (),counts .end ())); 94 std::vector < int32_t > dst_table (dst ); 95dst_table .resize (ids_rows ,0 ); 96Dev dx (x .size ()* 4 ),dsrc ((size_t )rows * 4 ),ddst (ids_rows * 4 ),db (bounds .size ()* 4 ),dw (w .size ()), 97dxq (mmq::q8_bytes (rows ,cols )),dy ((size_t )rows * (size_t )out_rows * 4 ); 98ck (cudaMemcpy (dx .p ,x .data (),x .size ()* 4 ,cudaMemcpyHostToDevice ),"x" ); 99ck (cudaMemcpy (dsrc .p ,src .data (),src .size ()* 4 ,cudaMemcpyHostToDevice ),"src" ); 100ck (cudaMemcpy (ddst .p ,dst_table .data (),dst_table .size ()* 4 ,cudaMemcpyHostToDevice ),"dst" ); 101ck (cudaMemcpy (db .p ,bounds .data (),bounds .size ()* 4 ,cudaMemcpyHostToDevice ),"bounds" ); 102ck (cudaMemcpy (dw .p ,w .data (),w .size (),cudaMemcpyHostToDevice ),"w" ); 103ck (cudaMemset (dy .p ,0xff , (size_t )rows * (size_t )out_rows * 4 ),"sentinel" ); 104// the copies and the sentinel above run on the legacy stream, which a non-blocking stream does not wait for: a 105// pageable cudaMemcpy/cudaMemset can still be in flight when the kernels start (a 128-SM 4090 caught it) 106ck (cudaDeviceSynchronize (),"inputs" ); 107 mmq::quantize ((const float * )dx .p , (const int32_t * )dsrc .p ,dxq .p , (int )t ,cols ,cols ,rows ,s ); 108 mmq::Product p ; 109p .w = dw .p ;p .type = (int )t ;p .w_rows = out_rows ;p .w_cols = cols ;p .expert_bytes = eb ;p .n = n ; 110p .xq = dxq .p ;p .bounds = (const int32_t * )db .p ;p .ids = (const int32_t * )ddst .p ;p .total_rows = rows ; 111p .max_rows = * std::max_element (counts .begin (),counts .end ());p .dst = (float * )dy .p ;p .ld_dst = out_rows ; 112ctx .run (p ,s ); 113ck (cudaGetLastError (),"launch" ); 114ck (cudaStreamSynchronize (s ),"sync" ); 115 std::vector < float > got ((size_t )rows * (size_t )out_rows ); 116ck (cudaMemcpy (got .data (),dy .p ,got .size ()* 4 ,cudaMemcpyDeviceToHost ),"y" ); 117 118const auto * tr = ggml_get_type_traits (t ); 119 std::vector < float > ref (got .size (),0.0f ),wd ((size_t )out_rows * (size_t )cols ); 120for (int e = 0 ;e < n ;++ e ) { 121const size_t rb = ggml_row_size (t ,cols ); 122for (int64_t o = 0 ;o < out_rows ;++ o ) 123tr -> to_float (ws [(size_t )e ].data ()+ (size_t )o * rb ,wd .data ()+ (size_t )o * (size_t )cols ,cols ); 124for (int r = bounds [(size_t )e ];r < bounds [(size_t )e + 1 ];++ r ) { 125const float * xr = x .data ()+ (size_t )src [(size_t )r ]* (size_t )cols ; 126for (int64_t o = 0 ;o < out_rows ;++ o ) { 127double acc = 0 ; 128const float * wr = wd .data ()+ (size_t )o * (size_t )cols ; 129for (int64_t k = 0 ;k < cols ;++ k )acc += (double )wr [k ]* xr [k ]; 130ref [(size_t )dst [(size_t )r ]* (size_t )out_rows + (size_t )o ]= (float )acc ; 131 } 132 } 133 } 134double err2 = 0 ,ref2 = 0 ,max_abs = 0 ,zero_max = 0 ; 135for (size_t i = 0 ;i < got .size ();++ i ) { 136if (!std::isfinite (got [i ]))throw std::runtime_error (std::string (name )+ ": unwritten or non-finite output" ); 137const double d = (double )got [i ]- ref [i ]; 138err2 += d * d ;ref2 += (double )ref [i ]* ref [i ];max_abs = std::max (max_abs , std::fabs (d )); 139 } 140for (int r = 0 ;r < rows ;++ r ) 141if (src [(size_t )r ]== rows - 1 )// the zero row 142for (int64_t o = 0 ;o < out_rows ;++ o ) 143zero_max = std::max (zero_max , (double ) std::fabs (got [(size_t )dst [(size_t )r ]* (size_t )out_rows + (size_t )o ])); 144const double rms = std::sqrt (ref2 / (double )ref .size ()),rel = std::sqrt (err2 / (double )ref .size ()) /rms ; 145 std::printf ("%-22s rows %2d experts %d ref_rms %.4g rel_l2 %.5f max/rms %.4f zero row %.3g\n" ,name ,rows ,n ,rms , 146rel ,max_abs /rms ,zero_max ); 147if (rel > 0.04 || max_abs /rms > 0.35 || zero_max > std::max (1e-5 ,1e-4 * rms )) 148throw std::runtime_error (std::string (name )+ ": outside the screen" ); 149} 150}// namespace 151 152int main () { 153try { 154if (!mmq::built ()) { std::printf ("no MMQ in this build\n" );return 1 ; } 155cudaStream_t s = nullptr ; 156ck (cudaStreamCreateWithFlags (& s ,cudaStreamNonBlocking ),"stream" ); 157 { 158 mmq::Context ctx ; 159const std::vector < std::vector < int >> batches {{1 ,3 ,3 }, {4 ,1 ,2 }, {2 ,3 }, {17 }}; 160int trial = 0 ; 161for (const auto & counts :batches ) { 162const std::string tag = "-" + std::to_string (trial ); 163product (ctx ,s , ("Q4_K gate/up" + tag ).c_str (),GGML_TYPE_Q4_K ,1280 ,2560 ,counts ,trial ); 164product (ctx ,s , ("Q5_K gate/up" + tag ).c_str (),GGML_TYPE_Q5_K ,1280 ,2560 ,counts ,trial + 5 ); 165product (ctx ,s , ("Q6_K gate/up" + tag ).c_str (),GGML_TYPE_Q6_K ,1280 ,2560 ,counts ,trial + 17 ); 166product (ctx ,s , ("Q5_1 down" + tag ).c_str (),GGML_TYPE_Q5_1 ,2560 ,640 ,counts ,trial + 9 ); 167product (ctx ,s , ("Q8_0 down" + tag ).c_str (),GGML_TYPE_Q8_0 ,2560 ,640 ,counts ,trial + 13 ); 168++ trial ; 169 } 170 } 171ck (cudaStreamDestroy (s ),"destroy" ); 172 std::printf ("prefill MMQ K-quant screen passed\n" ); 173return 0 ; 174 }catch (const std::exception & e ) { 175 std::fprintf (stderr ,"prefill MMQ K-quant screen failed: %s\n" ,e .what ()); 176return 1 ; 177 } 178}